首页 > 解决方案 > 如何从 git 中排除提交?

问题描述

昨天在 git 历史中出现了不应该存在的提交。

这是一个截图

在此处输入图像描述

之所以发生这种情况,是因为需要清理位于.gitignore但仍被 git 跟踪的文件。为了做到这一点,我们在 SO 上使用了这个答案

https://stackoverflow.com/a/23839198/5709159

一切都像它应该的那样工作。但我们意识到,实际上并非所有.gitignore(错误)下的文件都应该被删除......

问题是 - 目前这些提交已被推送,我们需要排除它们(还原)

有一些想法怎么做?

有没有办法获取所有这些已删除的文件(我们可以在提交中看到它们)并将其再次包含在新提交中?

PS文件在 git 中,但随后它们被删除并推送到 git。现在我们需要让他们回来。

例如我们有这样的提交历史A - B - C - D。我们在提交中有一些重要的文件,A然后在提交中B这些文件被删除,然后在提交中C - D我们定期提交逻辑实现等等。因此,在提交中被删除的文件B我们需要取回。我们需要排除 commitB和 leave commits C - D。像这样的东西A - C - D。或者另一种方式是A - B - C - D - B

标签: git

解决方案


当然你可以恢复

git revert <SHA of erroneous commit>

或者,您可以重写完整的历史记录,但这将更新所有可能危险的 SHA(如果其他人已经在分支上工作)

为此,您必须冻结其他开发人员才能在此期间工作

git checkout branchA   // one of the problematic branch
git rebase -i <sha1 befor the pb>
-->   mark the "remove ignored file" commit as `edit`
// this will stop into the "guilty commit"
// at this point we undo the commit 
git reset HEAD^ 
// and then redo do the job like it should have 
....
// including the  "git commit "
// you can even do more than one git "commit"
git rebase --continue

// then 
git push -f origin branchA

其他开发人员现在可以再次拉动

注意:为了更安全地执行此操作,您可以创建一个工作分支并在结果不符合预期时将其删除

git checkout branchA   // one of the problematic branch
git checkout -b branchA-before-rework // just in case

git checkout -b A-rework-1
git revert <SHA1 erroneous commit>

// ? happy :)
git branch -f branchA   // will force branchA to here
git push -f origin branchA
// not happy try something else

git checkout branchA   // one of the problematic branch
git checkout -b A-rework-2
// do above "git rebase -i" stuff EXCEPT push -f
// ? not happy drop it
git checkout branchA   // one of the problematic branch
git checkout -b A-rework-n
// ? happy :)
git branch -f branchA   // will force branchA to here
git push -f origin branchA

推荐阅读