繁体   English   中英

在提交之间移动文件

[英]Move files between commits

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

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

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

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并将它们交换回原始提交顺序。

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

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

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

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

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

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

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

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

这里提供更多细节。

首先了解简短历史

> 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

这里将文件从commit 3复制到commit 2

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

修改提交2并继续rebase

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

做完了!

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

在提交AI中添加了一个文件f,我必须在以下提交B中删除它。

现在我想在两个提交中删除该文件,但也想避免拆分提交,因为涉及许多其他文件。 我这样做了

  • 恢复文件
  • 在提交ADD中再次添加它
  • 在提交REM中删除它 - 现在有历史A - B - ADD - REM
  • squash使用REM提交A - 然后文件从A B中消失
  • drop commit ADD - 现在文件已经消失了

也许这是一个古怪的解决方案,但对我来说它是有效的。
如果您因某些原因觉得这很糟糕,请发表评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM