我不小心提交了一个不需要的文件(文件名。Orig而解决合并)到我的仓库几个提交前,没有我注意到它直到现在。我想从存储库历史记录中完全删除该文件。

是否有可能重写更改历史这样的文件名。奥里格从一开始就没有被添加到存储库中?


当前回答

你还可以使用:

git重置HEAD文件/路径

其他回答

你还可以使用:

git重置HEAD文件/路径

You should probably clone your repository first.

Remove your file from all branches history:
git filter-branch --tree-filter 'rm -f filename.orig' -- --all

Remove your file just from the current branch:
git filter-branch --tree-filter 'rm -f filename.orig' -- --HEAD    

Lastly you should run to remove empty commits:
git filter-branch -f --prune-empty -- --all

如果这是你想要清理的最新提交,我尝试使用git版本2.14.3 (Apple git -98):

touch empty
git init
git add empty
git commit -m init

# 92K   .git
du -hs .git

dd if=/dev/random of=./random bs=1m count=5
git add random
git commit -m mistake

# 5.1M  .git
du -hs .git

git reset --hard HEAD^
git reflog expire --expire=now --all
git gc --prune=now

# 92K   .git
du -hs .git

这就是git filter-branch的设计目的。

如果你的情况不是问题中描述的情况,请不要使用这个方法。这个配方是用来修复一个坏的合并,并在一个固定的合并中重新播放你好的提交。

尽管filter-branch会做你想做的事情,但这是一个相当复杂的命令,我可能会选择用git rebase来做这件事。这可能是个人喜好。Filter-branch可以在一个稍微复杂一点的命令中完成,而rebase解决方案则是一次执行一步等效的逻辑操作。

试试下面的食谱:

# create and check out a temporary branch at the location of the bad merge
git checkout -b tmpfix <sha1-of-merge>

# remove the incorrectly added file
git rm somefile.orig

# commit the amended merge
git commit --amend

# go back to the master branch
git checkout master

# replant the master branch onto the corrected merge
git rebase tmpfix

# delete the temporary branch
git branch -d tmpfix

(注意,你实际上不需要一个临时分支,你可以用一个'detached HEAD'来做到这一点,但你需要注意git commit——modify步骤生成的提交id,以提供给git rebase命令,而不是使用临时分支名称。)