重写git历史记录,重写添加和删除提交

时间:2016-01-10 07:18:41

标签: git git-rebase

我有一个本地分支,我在其中进行了一些开发,提交历史非常糟糕所以我要回去并重新整理并在推送之前将其保持在合理的状态。

假设我提交了A,B,C,D,E。在提交B中,我添加了一些我想要保留的有用代码但是我还添加了一些调试代码。然后我删除了D中的调试代码。用什么方法从历史记录中完全删除它(代码没有任何用处,所以如果可能,我不想在历史记录中使用它) ?

我已尝试在A处进行变基,在没有代码的情况下重写B处的提交,但C和D需要在每个rebase步骤进行手动干预。 最好将B,D分成B-keep和B-remove,D-keep和D-remove然后删除两个提交?是否有其他方法可以在添加代码后将其删除?

我希望最终得到的历史看起来像A,B(有用),C,D(有用),E然后我可以压缩到A,B,E,例如,在这个阶段我只想删除来自历史的调试代码。

3 个答案:

答案 0 :(得分:0)

申请Q更新:

您可以使用此工具循环提交并删除不需要的提交。 https://rtyley.github.io/bfg-repo-cleaner/

阅读有关如何使用它的示例部分。

它比git filter-branch快得多但效果相同。

其他一些选择:

请在此处详细了解每个选项: How to move HEAD back to a previous location? (Detached head)

git rebase -i

编辑要清理的每个提交并从中删除代码。如果您没有太多提交,那么它很有用 - 如果您这样做 - 使用filter-branch或' bfg-repo-cleaner'

git checkout

git checkout <commit_id>

git reflog

您也可以随时使用reflog

git reflog
git checkout HEAD@{...}

这会让你回到你想要的提交

git reset HEAD --hard <commit_id>

&#34;移动&#34;回到理想的承诺。

# This will destroy any local modifications.
# Don't do it if you have uncommitted work you want to keep.
git reset --hard 0d1d7fc32

# Alternatively, if there's work to keep:
git stash
git reset --hard 0d1d7fc32
git stash pop
# This saves the modifications, then reapplies that patch after resetting.
# You could get merge conflicts, if you've modified things which were
# changed since the commit you reset to.
  • 注意:(Since Git 2.7
    您也可以使用git rebase --no-autostash

git checkout

git checkout -b <new branch> <commit_id>
git checkout HEAD~X // x is the number of commits t go back

这将检查指向所需提交的新分支

答案 1 :(得分:0)

通常的解决方法是使用git filter-branch,并结合sed, to delete line matching a pattern

# find out the desired file and execute sed on it to find out
# where is the debug code inside the file
git filter-branch --tree-filter "find . -type f -exec sed -i -e 's/pattern with debug/d' {} \;" -- A~..

您可以优化查找条件,仅查找具有特定扩展名(--name '*.java'

的文件

这将从历史记录中删除调试代码,而无需手动干预中间提交 当然,这会为所有相关的提交重写SHA1,迫使你做git push --force,所以如果你并不是唯一一个那个回购工具,那就把你的分支机构即将重置给其他合作者。

答案 2 :(得分:0)

如果提交rebase -i它只是从提交B中删除调试代码,那么您可以使用pick c9a8ee8 B pick f533903 C pick c66cc92 D pick 647ab90 E 重新排序提交和压缩,例如,当您开始重新定位时,您将在此处看到:

D

现在您需要在提交B后移动提交pick c9a8ee8 B pick c66cc92 D pick f533903 C pick 647ab90 E ,您只需要编辑文本内容:

pick

最后,您需要将squash更改为D以提交pick c9a8ee8 B squash c66cc92 D pick f533903 C pick 647ab90 E ,以下是它的外观:

D

完成变基后,提交B将成为提交IEnumerator ScreenShot(){ yield return new WaitForEndOfFrame (); Application.CaptureScreenshot ("ball.png"); Application.CaptureScreenshot ("/sdcard/Download/ball.png"); int width = Screen.width; int height = Screen.height; Texture2D tex = new Texture2D (width, height, TextureFormat.RGB24, false); tex.ReadPixels (new Rect (0, 0, width, height), 0, 0); tex.Apply (); byte[] bytes = tex.EncodeToJPG (); File.WriteAllBytes ("sdcard/Download/ball.png", bytes); File.WriteAllBytes (Application.persistentDataPath + "/ball.png", bytes); } 的一部分。

相关问题