首页 > 解决方案 > 如何在保留(手动解析)合并的同时从 git 历史记录中删除文件?

问题描述

我想完全从 git 历史记录中删除特定文件。它是不久前添加的;由于发生了点分支以及合并,其中一些需要手动干预。

特定文件不涉及任何合并问题。但是,当我尝试重写历史时,git 让我重做解决最初已经解决的合并的工作。我怎样才能避免这种情况?

举例说明问题的回购可以这样构建:

# intitial setup
mkdir rebase-across-manually-resolved-merge-conflicts
cd rebase-across-manually-resolved-merge-conflicts/
git init

# root commit, w/ garbage
echo "foo" > foo.txt
echo "unrelated-garbage" > unrelated-garbage.txt
git add foo.txt unrelated-garbage.txt 
git commit -m "initial checkin with undesirable content"

# branch a
git checkout -b branch-a
echo bar > foo.txt
git add foo.txt 
git commit -m "foo must be bar"

# branch b
git checkout master
git checkout -b branch-b
echo baz > foo.txt 
git add foo.txt 
git commit -m "foo must be baz"

# merging both branches into master; manual resolution of conflicts
git checkout master
git merge branch-a
git merge branch-b
echo barz > foo.txt
git add foo.txt 
git commit  -m "Merge branch 'branch-b' (manual resolution of merge conflicts)"

结果将如下所示:

*   4b874d0 (HEAD -> master) Merge branch 'branch-b' (manual resolution of merge conflicts)
|\  
| * 16e2bc4 (branch-b) foo must be baz
* | fa7418a (branch-a) foo must be bar
|/  
* ff8aa1b initial checkin with undesirable content
git rebase -r -i --root  # in the editor, change "pick" to "edit" for the line "initial checkin w..."
git rm unrelated-garbage.txt 
git commit --amend -m "initial checkin with no undesirable content"
git rebase --continue

这失败了:

# Auto-merging foo.txt
# CONFLICT (content): Merge conflict in foo.txt
# Could not apply 819e457... branch-b # Merge branch 'branch-b' (manual resolution of merge conflicts)

尝试git rebase -p -i --root(使用不推荐使用的-p选项)同样不成功。

我想要一个完全自动化的解决方案......我的真实情况比上面的例子有更多的合并和手动解决方案。

标签: git

解决方案


尝试

git filter-branch --tree-filter 'rm -f unrelated-garbage.txt' HEAD

https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History中所述。请注意该部分中的“注意”警告。您可能需要先进行备份。


推荐阅读