在切换到第二个分支之前忘记提交更改,现在我的更改出现在两个分支上



在更改为feature-24并在那里进行不同的更改之前,我忘记提交对分支feature-23的更改。现在,两个分支都显示了我在两个分支之间所做的所有更改。

如何将更改分开,使每个分支只显示我对它们所做的原始更改。

第一步,保存您的修改,即使您的更改混合在一起:

git add -u       # -u will add all tracked files,
# another option is -a (for 'all')
# or explicitly name the files/folders :
# git add file1 file2 dir3 ...
git commit       # create a commit
git branch tmp   # create a tmp branch at that commit location
git reset HEAD~  # return one commit behind
# important note: *not* --hard

现在可以从分支tmp访问文件的内容。


如果要在feature-23上提交的文件与feature-24上的文件是分开的,则操作很简单:

# suppose you currently are on branch feature-24 :
git add relevant-file1 relevant-file2
git commit  # create the commit for feature-24
# now go to the other branch :
git checkout feature-23
git add relevant-file3 relevant-file4
git commit   # create commit for feature-23

如果某些更改在同一个文件上(部分更改应转到feeature-23,另一部分转到feature-24(并且没有太多交织(例如:在diff中是明显分离的块(,则可以使用git add -p:

git add -p relevant-file1
# an interactive session will ask you to add or ignore each chunk in the diff
git add -p relevant-file2
git add relevant-file3
git commit
# then switch to the other branch, and proceed

还有一个随标准git:git gui一起提供的图形工具。

它的GUI有点笨重,但它提供了大量有用的功能。您将获得磁盘上的内容(工作树(、要提交的内容(索引(的图形演示,以及逐文件差异视图,您可以在其中右键单击并添加/删除完整的块或单独的行。

有两种情况:

如果更改在分支特征23中,则特征24在差异文件中。解决会更容易

您需要签出到每个分支并提交相关文件

如果两个分支之间的更改在同一个文件中,则需要提交部分文件,如