Pagine

Tuesday 6 June 2017

How to rewrite commit history with git

Someone accidentally commits a huge binary file with a thoughtless git add ., and you want to remove it everywhere. Perhaps you accidentally committed a file that contained a password, and you want to make your project open source. filter-branch is the tool you probably want to use to scrub your entire history. The --tree-filter option runs the specified command after each checkout of the project and then recommits the results. 

Examples:

1) To remove a file named mypasswords.txt from your entire history, you can use the --tree-filter option to filter-branch: 
$ git filter-branch --tree-filter 'rm -f mypasswords.txt' HEAD
Rewrite 802a096d79b9b5872544a6b35d6a52cbdf55274a (21/21)
Ref 'refs/heads/master' was rewritten 
2) If you want to remove all accidentally committed editor backup files, you can run something like
$ git filter-branch --tree-filter 'rm -f *~' HEAD.

--index-filter option

The --index-filter is another option similar to the tree filter but does not check out the tree, which makes it much faster.
$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch myfilename.txt' HEAD
The --ignore-unmatch option is needed because "git rm" will fail if the file is absent from the tree.

No comments:

Post a Comment