How can I easily fixup a past commit?

前端 未结 12 2319
执笔经年
执笔经年 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

    UPDATE: A cleaner version of the script can now be found here: https://github.com/deiwin/git-dotfiles/blob/docs/bin/git-fixup.

    I've been looking for something similar. This Python script seems too complicated, though, therefore I've hammered together my own solution:

    First, my git aliases look like that (borrowed from here):

    [alias]
      fixup = !sh -c 'git commit --fixup=$1' -
      squash = !sh -c 'git commit --squash=$1' -
      ri = rebase --interactive --autosquash
    

    Now the bash function becomes quite simple:

    function gf {
      if [ $# -eq 1 ]
      then
        if [[ "$1" == HEAD* ]]
        then
          git add -A; git fixup $1; git ri $1~2
        else
          git add -A; git fixup $1; git ri $1~1
        fi
      else
        echo "Usage: gf  "
      fi
    }
    

    This code first stages all current changes(you can remove this part, if you wish to stage the files yourself). Then creates the fixup(squash can also be used, if that's what you need) commit. After that it starts an interactive rebase with the --autosquash flag on the parent of the commit you give as the argument. That will open your configured text editor, so you could verify that everything is as you expect and simply closing the editor will finish the process.

    The if [[ "$1" == HEAD* ]] part (borrowed from here) is used, because if you use, for example, HEAD~2 as your commit(the commit you want to fix current changes up with) reference then the HEAD will be displaced after the fixup commit has been created and you would need to use HEAD~3 to refer to the same commit.

提交回复
热议问题