How to modify a specified commit?

后端 未结 16 942
清酒与你
清酒与你 2020-11-22 01:53

I usually submit a list of commits for review. If I have the following commits:

  1. HEAD
  2. Commit3
  3. Commit2
16条回答
  •  死守一世寂寞
    2020-11-22 02:53

    Completely non-interactive command(1)

    I just thought I'd share an alias that I'm using for this. It's based on non-interactive interactive rebase. To add it to your git, run this command (explanation given below):

    git config --global alias.amend-to '!f() { SHA=`git rev-parse "$1"`; git commit --fixup "$SHA" && GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^"; }; f'
    

    Or, a version that can also handle unstaged files (by stashing and then un-stashing them):

    git config --global alias.amend-to '!f() { SHA=`git rev-parse "$1"`; git stash -k && git commit --fixup "$SHA" && GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^" && git stash pop; }; f'
    

    The biggest advantage of this command is the fact that it's no-vim.


    (1)given that there are no conflicts during rebase, of course

    Usage

    git amend-to  # e.g.
    git amend-to HEAD~1
    git amend-to aaaa1111
    

    The name amend-to seems appropriate IMHO. Compare the flow with --amend:

    git add . && git commit --amend --no-edit
    # vs
    git add . && git amend-to 
    

    Explanation

    • git config --global alias. '!' - creates a global git alias named that will execute non-git command
    • f() { }; f - an "anonymous" bash function.
    • SHA=`git rev-parse "$1"`; - converts the argument to git revision, and assigns the result to variable SHA
    • git commit --fixup "$SHA" - fixup-commit for SHA. See git-commit docs
    • GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash "$SHA^"
      • git rebase --interactive "$SHA^" part has been covered by other answers.
      • --autosquash is what's used in conjunction with git commit --fixup, see git-rebase docs for more info
      • GIT_SEQUENCE_EDITOR=true is what makes the whole thing non-interactive. This hack I learned from this blog post.

提交回复
热议问题