我开始了一些新功能的工作,在编写了一些代码之后,我决定这个功能应该在它自己的分支上。
如何将现有未提交的更改移动到新分支并重置我当前的?
我想重置我当前的分支,同时保留新功能的现有工作。
我开始了一些新功能的工作,在编写了一些代码之后,我决定这个功能应该在它自己的分支上。
如何将现有未提交的更改移动到新分支并重置我当前的?
我想重置我当前的分支,同时保留新功能的现有工作。
Git 2.23 添加了新的switch
子命令,以试图消除由于checkout
(切换分支、恢复文件、分离 HEAD 等)的重载使用而产生的一些混乱。
从这个版本的 Git 开始,将 checkout 命令替换为:
git switch -c <new-branch>
行为是相同的并且保持不变。
使用以下内容:
git checkout -b <new-branch>
这将使您当前的分支保持原样,创建并签出一个新分支并保留您的所有更改。然后,您可以暂存文件中的更改以提交:
git add <files>
并提交到您的新分支:
git commit -m "<Brief description of this commit>"
工作目录中的更改和索引中暂存的更改尚不属于任何分支。这会更改这些修改将结束的分支。
您不会重置原始分支,它会保持原样。最后一次提交<old-branch>
仍然是相同的。因此你checkout -b
然后提交。
或者:
将当前更改保存到临时存储:
$ git stash
基于此存储创建一个新分支,并切换到新分支:
$ git stash branch <new-branch> stash@{0}
提示:使用 tab 键减少输入存储名称。
如果您在编写代码时一直在主分支上进行提交,但现在想将这些提交移动到不同的分支,这是一种快速的方法:
将您当前的历史记录复制到一个新分支上,同时带来任何未提交的更改:
git checkout -b <new-feature-branch>
现在强制原来的“混乱”分支回滚:(不切换到它)
git branch -f <previous-branch> <earlier-commit-id>
例如:
git branch -f master origin/master
或者如果你做了 4 次提交:
git branch -f master HEAD~4
警告: git branch -f master origin/master
将重置该分支的跟踪信息。因此,如果您已将master
分支配置为推送到其他地方,origin/master
那么该配置将丢失。
警告:如果你在分支后变基,有一些提交可能会丢失的危险,这在此处描述。避免这种情况的唯一方法是使用cherry-pick 创建新的历史记录。该链接描述了最安全的万无一失的方法,尽管不太方便。(如果您有未提交的更改,您可能需要git stash
在开始和git stash pop
结束时进行。)
常见的情况如下:我忘记为新功能创建新分支,而在旧功能分支中完成所有工作。我已将所有“旧”工作提交给主分支,我希望我的新分支从“主”发展而来。我的新工作没有一次提交。这是分支结构:“master”->“Old_feature”
git stash
git checkout master
git checkout -b "New_branch"
git stash apply
如果您提交它,您还可以挑选单个提交 ID。当我开始在 master 中工作时,我经常这样做,然后想在我推送到我的 origin/ 之前创建一个本地分支。
git cherry-pick <commitID>
如此处所述,您可以使用cherry-pick 做很多事情,但这对您来说可能是一个用例。
我使用@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
! 如果 repo 有多个存储,请查看将哪一个应用于新分支:
git stash list
stash@{0}: WIP on ...
stash@{1}: WIP on ...
并通过以下方式检查个人藏匿处,
git stash show stash@{1}
或一次检查所有藏匿处:
git stash list -p
假设您在 GitHub 上创建了一个名为feature-branch的新分支。
拿来
git pull --all Pull all remote branches
git branch -a List all branches now
签出并切换到功能分支目录。您可以简单地从上面的 branch -a 命令的输出中复制分支名称
git checkout -b feature-branch
证实
接下来使用 git branch 命令查看当前分支。它将在前面显示带有 * 的功能分支
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