Git remove a file in a commit

来源:互联网 发布:java虚拟机原理pdf 编辑:程序博客网 时间:2024/05/18 01:06


http://www.turnkeylinux.org/blog/git-fix-commits

Git - Fixing commit mistakes

I use Git. I use it a lot. I basically use it for everything I do, from code revision control to revisioning my notes, my journal, even my email archive (don't ask, it's a long story).
 
As with anything you do, you are bound to make mistakes. When it comes to coding and revision control, mistakes can range from bad commit messages, to buggy code, to code that shouldn't have been committed together with other code, or even at all.
 
Here are a couple of tips I find myself using quite often.
 

Correcting mistakes in the last commit

This is very easy with git-commit --amend, For example:
 
I decide I don't like the commit description I used.
git-commit --amend # just edit the description
 
I want to edit buggy code I just committed to path/to/file.
editor path/to/filegit-add path/to/filegit-commit -v --amend # note your recent changes are part of the commit
 
I want to remove a file I included accidentally in the last commit (e.g., because I want to commit changes to that file separately).
git-reset HEAD^1 path/to/file # this doesn't delete your changes to path/to/filegit-commit --amend -vgit-commit -v path/to/file # make a new commit with changes to path/to/file
 

Correcting mistakes in previous commits

This also uses git-commit --amend, but involves two extra steps:
1) git-checkout <bad-commit>   ... make your changes ...2) git-commit --amend -v3) git-rebase --onto HEAD <bad-commit> <checked-out-branch>
 
If a conflict occurs while re-applying your commits, you may have to manually resolve the conflict and thengit-rebase --continue. See the manual page for further details.
 
For example, I notice I made a mistake in commit 0f0d8a27622e7bf7f008983c4b8ee23bfb9843ab several revisions ago and I'm checked out to branchmaster.
 
To correct the commit history:
git-checkout 0f0d8a27622e7bf7f008983c4b8ee23bfb9843abeditor path/to/filegit-add path/to/filegit-commit --amend -vgit-rebase --onto HEAD 0f0d8a27622e7bf7f008983c4b8ee23bfb9843ab master
 

Implications

Note that by editing your commit history you are effectively re-applying your changes, and thus creating new commits with new commit ids. For example, this means you'll have to recreate existing tags.