我开始研究一个新特性,在编码了一段时间后,我决定这个特性应该属于自己的分支。

如何将现有未提交的更改移动到新分支并重置当前分支?

我想重置当前分支,同时保留新功能的现有工作。


当前回答

选项1(现有分支)

git stash (from main/any-branch)
git checkout your-existing-branch
git stash apply 

选项2(创建新分支)

git switch -c your-new-branch

其他回答

提交更改的3个步骤

假设您在GitHub上创建了一个名为featurebranch的新分支。

提取

    git pull --all         Pull all remote branches
    git branch -a          List all branches now

检出并切换到要素分支目录。您可以简单地从上面的branch-a命令的输出中复制分支名称

git checkout-b功能分支

验证

接下来使用gitbranch命令查看当前分支。它将显示前面带有*的功能分支

git branch         

承诺

git add .   add all files
git commit -m "Rafactore code or use your message"

在源服务器上进行更新和推送更改

 git pull origin feature-branch
 git push origin feature-branch

事实上,使用GitHub Desktop有一种非常简单的方法来实现这一点,我以前不相信这是一种功能。

你所需要做的就是切换到GitHubDesktop中的新分支,它会提示你将所做的更改保留在当前分支上(将被隐藏),或者将更改带到新分支。只需选择第二个选项,将更改添加到新分支。然后,您可以像往常一样提交。

对于那些使用Visual Studio Community 2022(以及可能更早的版本)的用户,当您有未提交的更改,然后创建一个新分支时,您将看到如下对话框:

只需选择第一个选项将更改带到“[您的新分行名称]”,然后单击“继续签出”。将创建新分支,您可以继续在那里提交更改。

或者:

将当前更改保存到临时存储:$git存储基于此存储创建新分支,然后切换到新分支:$git stash branch<new branch>stash@{0}

提示:使用tab键可以减少键入存储名称。

我使用@Robin回答并列出我所做的一切,

git status                               <-- review/list uncommitted changes
git stash                                <-- stash uncommitted changes
git stash branch <new-branch> stash@{1}  <-- create a branch from stash
git add .                                <-- add local changes
git status                               <-- review the status; ready to commit
git commit -m "local changes ..."        <-- commit the changes
git branch --list                        <-- see list of branches incl the one created above
git status                               <-- nothing to commit, working tree (new-branch) is clean
git checkout <old-branch>                <-- switch back

! 如果回购有多个存储,请查看要应用于新分支机构的存储:

git stash list  
  stash@{0}: WIP on ...  
  stash@{1}: WIP on ...

并通过以下方式检查各个藏匿点,

git stash show stash@{1}

或者立即检查所有储藏物:

git stash list -p