How can I easily fixup a past commit?

前端 未结 12 2331
执笔经年
执笔经年 2020-12-02 03:48

I just read amending a single file in a past commit in git but unfortunately the accepted solution \'reorders\' the commits, which is not what I want. So here\'s my question

12条回答
  •  悲&欢浪女
    2020-12-02 04:30

    A bit late to the party, but here is a solution that works as the author imagined.

    Add this to your .gitconfig:

    [alias]
        fixup = "!sh -c '(git diff-files --quiet || (echo Unstaged changes, please commit or stash with --keep-index; exit 1)) && COMMIT=$(git rev-parse $1) && git commit --fixup=$COMMIT && git rebase -i --autosquash $COMMIT~1' -"
    

    Example usage:

    git add -p
    git fixup HEAD~5
    

    However if you have unstaged changes, you must stash them before the rebase.

    git add -p
    git stash --keep-index
    git fixup HEAD~5
    git stash pop
    

    You could modify the alias to stash automatically, instead of giving a warning. However, if the fixup does not apply cleanly you will need pop the stash manually after fixing the conflicts. Doing both the saving and popping manually seems more consistent and less confusing.

提交回复
热议问题