Removing commit from git history

2019-07-09 20:17发布

问题:

I've discovered that I have a file committed to my repo year ago, which I never wanted to be there. Before I make my repo public I'd like to revert, or actually remove commit which introduced this file so no one will be able to access this file.

I've used interactive rebase so I was able to delete unwanted commit. It looked promising but after applying ~400 commits from 800 there is a conflict.

The conflict is caused by nonlinear history - there was a branch and one file was modified in both branches (lets say feature1 and feature2). As far as I've noticed git rebase tried to make this parallel history linear and it failed at those parallel, conflicting modifications. I don't want to try to fix it as there are much more such situations and It would be a big effort to fix all of them.

So my question is: is it possible to simply remove one commit with reconstruction of branch history without any influence on other commits?

My file was added once and was never modified, so none of other commits touch it.

回答1:

You could try the filter-branch command.

git filter-branch --prune-empty --tree-filter 'rm <filename-to-delete> || true' HEAD

If the wrong commit just added the file to remove, the entire commit will be skipped (option --prune-empty).

I've tested this with a simple repo with a branch and a merge, and the merge was quite cleverly preserved. So you should not expect conflicts. And filter-branch creates a backup branch as well, sir. :-)