在提交之间移动文件

时间:2013-09-02 09:34:49

标签: git git-commit

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

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

5 个答案:

答案 0 :(得分:20)

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

开始
pick 8de731b Commit with missing file.
pick bbef925 Commit with too many files.
pick 52490ce More history.

我需要将其更改为

edit bbef925 Commit with too many files.
edit 8de731b Commit with missing file.
pick 52490ce More history.

然后,

# 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

不幸的是,在一个分支中编辑历史记录时,我不知道有什么方法可以避免在所有分支中编辑历史记录。应该尽早重新进行重新定位,以避免这样的问题。在我的简单案例中,我可以合并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

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

答案 1 :(得分:10)

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

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

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

然后再次重新加入,这次选择将提交2.1压缩为1。

答案 2 :(得分:5)

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

mv-changes <source-commit> <destination-commit> <path>...

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

请注意,如果<path>source-commit之间的中间提交中destination-commit发生了更改,则无效。

提供了更多详细信息here

答案 3 :(得分:0)

首先获取简短历史记录的信息

> 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 

所以我们可以重新确定基础并停止提交22222

> git rebase -i master 
pick 22222 corected bug 
pick 33333 added test

更改为:

edit 22222 corected bug 
pick 33333 added test

然后您将在提交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

此处将文件从提交3复制到提交2

git show 33333:path/to/file  >  path/to/file

修改提交2并继续变基

git commit --amend --no-edit path/to/file
git rebase --continue

完成!

答案 4 :(得分:0)

我遇到了同样的问题,想解释一下我做了什么。

在提交A中,我添加了一个文件f,随后在提交B中必须将其删除。

现在,我想摆脱两次提交中的文件,但也想避免拆分提交,因为其中涉及许多其他文件。我做到了

  • 恢复文件
  • 在提交ADD中再次添加它
  • 在提交REM中删除它-现在有历史记录A-B-添加-REM
  • 使用REM压扁A-然后文件从A B
  • 中消失
  • 删除提交ADD-现在文件已消失

也许这是一个古怪的解决方案,但对我来说却奏效了。
如果您出于某些原因感到不好,请发表评论。