如何将文件中的所有更改移动到新分支?

How can I move all changes in a file to a new branch?

提问人:Ronny Efronny 提问时间:11/8/2023 更新时间:11/8/2023 访问量:21

问:

这是我经常遇到的问题,我想知道是否有方便的解决方案。

假设我在一个分支上工作,后来提交了几次,这里修复,那里更改,突然这个分支影响的文件比我计划的要多。有时他们中的一些人彼此无关。 我想对一个或多个文件进行所有更改,并将它们移动或复制到另一个分支。

挑剔提交不是一种选择,因为每个提交都可能影响了多个文件。

例:

提交 1 - 对 foo 的更改。创建了 taz。

提交 2 - 对 bar、taz 的更改。

提交 3 - 更改为 foo、bar。

提交 4 - 对 taz 的更改。

在这一点上,realize 与此分支无关,因此我想创建一个新分支,其中仅进行了所有更改。barbar

这可能吗?

git 分支

评论


答:

1赞 eftshift0 11/8/2023 #1

很容易定义,因为它肯定需要一些工作,因为 git 不可能猜到与 bar 相关的部分......所以,你可以这样做:

git checkout -b bar main
git cherry-pick --no-commit <id-commit-2> # apply first commit of bar
# now, you need to surgically remove all changes related to taz
# if it's a directory of its own, it's simple: git checkout HEAD -- directory-of-taz
# if it's intertwined in the files, then you need to edit them
# when you only have stuff related to bar left over in the project:
git add . # if there's anything left outside of the index, that is
git cherry-pick --continue
git cherry-pick --no-commit <id-commit-3>
# same thing

也可以通过交互式变基来完成,但在开始玩游戏之前创建分支:

git checkout -b bar main
git rebase -i <id-commit-1> # it has to be the commit _previous_ of the first commit you want to see in the final branch
# you get a list with 3 commits, you set the first 2 commits to to 'e' or 'edit'
# you drop the last one
# save and exit
# rebase will stop right after applying the second commit, first one won't be applied
# then you edit the files so that changes related to taz are gone
git add .
git commit --amend
git rebase --continue
# remove all foo changes
git add .
git commit --amend
git rebase --continue

你完成了......现在你必须从原始分支中清理它,对吧?你可以通过做变基和恢复(通过在每个变基上编辑正确的提交)你所拥有的内容来实现这一点,然后一次倒退一个变基......这是为了尽量减少处理冲突的必要......如果你想在单个变基中做到这一点,一旦你利用了在变基期间恢复的分支中应用的最早的提交,你将在处理的每个提交中面临冲突,因为这些更改将随着变基的进行而消失。barbar~1barbar