gitrebasefixup

Programmatically fixup last commit into previous


Every time I want to fixup my latest commit into the second latest commit, I do this

git rebase HEAD~2 -i
<replace pick with fixup on line 2>

Is there a way to do this in an automated script, without human interference?

I tried this and it doesn't work:

git commit --fixup=HEAD

Solution

  • git reset HEAD~1 --soft
    git commit --amend --no-edit
    

    or

    git reset HEAD~2 --soft
    git commit -C ORIG_HEAD^ --reset-author 
    

    or

    head=`git log -1 --pretty=%H HEAD~1`
    git reset HEAD~2 --hard
    git merge --squash ORIG_HEAD
    git commit -C $head --reset-author
    

    or

    head=`git log -1 --pretty=%h HEAD~1`
    git reset HEAD~2 --hard
    git cherry-pick -n HEAD..ORIG_HEAD
    git commit -C $head --reset-author
    

    The first is enough in your case. The other three are just for fun here, which might be useful in other cases.

    Update: the explanation of the second:

    Suppose we have A-B-C as the latest three commits and C is the head. What you want is to squash B and C into a single commit which reuses B's commit message.

    git reset HEAD~2 --soft resets HEAD to A and keeps the changes of B and C in the index and in the working tree. Then a following git commit creates a commit that includes the changes in the index, aka the changes of B and C.

    As its name implies, ORIG_HEAD points to the original head, in this case the one before last reset, which is C. And ORIG_HEAD^ means the first parent of ORIG_HEAD, which is B. -C ORIG_HEAD^ means to reuse the commit message of B without edit.

    More about --soft, -C and --reset-author.