在提交之间移动文件

10 git git-commit

我有两个相应的提交,在本地历史的某个地方,并且一个文件被错误地添加到第二个.我想解决这个问题.

我不明白我应该如何使用交互式rebase.我做了git rebase -i HEAD~10并选择用文件编辑提交,以便从那里检查出来.我使用git guit但是,在提交区域看不到任何文件.我可以选择修改之前的提交然后我看到文件.但是,我无法将错放的文件添加到之前的提交中,因为我没有看到当前提交中的文件开头.

dwa*_*duk 22

因此,在重新定位时,选择编辑错误添加文件的提交和要按顺序添加文件的提交.如果文件在稍后的提交中,但应该在较早的提交中,则必须对行重新排序.例如,我开始

pick 8de731b Commit with missing file.
pick bbef925 Commit with too many files.
pick 52490ce More history.
Run Code Online (Sandbox Code Playgroud)

我需要改成它

edit bbef925 Commit with too many files.
edit 8de731b Commit with missing file.
pick 52490ce More history.
Run Code Online (Sandbox Code Playgroud)

然后,

# In the commit containing an extra file
git reset HEAD^ badfile.c
git commit --amend
git rebase --continue

# Now in the commit to add it to
git add badfile.c
git commit --amend
git rebase --continue
Run Code Online (Sandbox Code Playgroud)

不幸的是,在一个分支中编辑历史记录时,我不知道有什么方法可以避免在所有分支中编辑历史记录.应该尽早重新进行重新定位,以避免这样的问题.在我的简单案例中,我可以合并master和另一个分支,但是提交不合并,然后我必须在master中重新定义,并重新排序和压缩提交,如下所示:

pick 7cd915f Commit with missing file.
fixup 8de731b Commit with missing file. #This was the higher of the two entries
pick 8b92c5a Commit with too many files.
fixup bbef925 Commit with too many files. #This was the higher of the two entries
pick 94c3f7f More history.
fixup 52490ce More history. #This was the higher of the two entries
Run Code Online (Sandbox Code Playgroud)

后期编辑:我刚注意到我不小心将提交历史记录重新排序为原始答案中的遗留物.交换rebase中的行会改变您提交的顺序; 在编辑之后,您可以再次进行rebase并将它们交换回原来的提交顺序.


elm*_*art 12

如果我没有弄错,你想要的是移动一些包含提交2到提交1的更改.

我发现最简单的方法是做两个连续的交互式rebase.

在第一个中,您将提交2拆分为两个提交:第一个包括您要移动的更改,第二个包括所有其他提交.我们现在提交1,2.1和2.2.

然后再次进行rebase,这次选择将2.1提交压缩为1.


Mik*_*sov 6

由于我经常偶然发现这个问题,我为此编写了一个脚本.它完全自动运行.你可以在Github上找到它.将其复制到本地文件系统,将其添加到PATH,您将能够将其运行为:

mv-changes <source-commit> <destination-commit> <path>...
Run Code Online (Sandbox Code Playgroud)

您还可以在Windows上的Git-Bash shell中运行该脚本.

请注意,如果<path>source-commit和之间的中间提交中有更改destination-commit,则它将不起作用.

这里提供更多细节.


jo_*_*jo_ 5

首先了解简短的历史信息

> git log --oneline -n 3 --decorate=short
333333  (HEAD -> work_AAA) added test              /*file is updated here*/
222222  corrected bug 
111111  (origin/master, origin/HEAD, master) version XXX 
Run Code Online (Sandbox Code Playgroud)

这样我们就可以变基并在提交 22222 处停止

> git rebase -i master 
pick 22222 corected bug 
pick 33333 added test
Run Code Online (Sandbox Code Playgroud)

改成 :

edit 22222 corected bug 
pick 33333 added test
Run Code Online (Sandbox Code Playgroud)

那么你将在提交 22222 中处于更新模式,它显示如下内容:

Stopped at 22222... corrected bug
You can amend the commit now, with
   git commit --amend 
Once you are satisfied with your changes, run
   git rebase --continue
Run Code Online (Sandbox Code Playgroud)

这里将文件从提交 3 复制到提交 2

git show 33333:path/to/file  >  path/to/file
Run Code Online (Sandbox Code Playgroud)

修改提交2并继续rebase

git commit --amend --no-edit path/to/file
git rebase --continue
Run Code Online (Sandbox Code Playgroud)

完毕 !