Home > Net >  Prevent git commit --amend from trying to amend an already submitted change?
Prevent git commit --amend from trying to amend an already submitted change?

Time:10-03

We are using Gerrit for code reviews.

The normal workflow is:

  1. git commit
  2. run a script to push the commit, which does:
    1. git commit --amend, which I think triggers a hook
    2. git push

Every now and then, I forget to do the commit and I totally mess myself up by calling the script first, which then amends the last commit, which has already been submitted (merged).

If I don't get too far ahead of myself, I can do:

git reset --soft HEAD~1

And then I can fix it, albeit with a bit of pain. If I get too far ahead, then I end up having to fix conflicts, rebase, fix conflicts again before I am back in-sync with the branch (master in this case). The conflict resolution is usually not too difficult, but it wastes a lot of time if it was a bunch of files.

What I would like to do, is to have a safeguard in the script to somehow detect if the last commit has been submitted (aka merged via Gerrit) and abort the script in that case, because there is probably never a scenario where I want to amend a commit

A web search proved fruitless to find a solution, hopefully someone in the SO community has a way to work around this?

TIA, -Dave

CodePudding user response:

Your script is a perfect use case for git hooks : https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks have you heard of pre-commit hook ? in that case you don't need any custom scripts. Also, if you insist on using a script, in that case I would suggest to add additional logic into amend part and add a tag #modified to the commit message or whatever, to indicate that you have already ran the script. When you run the script the second time the script must check the commit message and abort in case the tag #modified is already in the message.

CodePudding user response:

You DON'T need to execute the "git commit --amend" command to trigger the "commit-msg" hook (the Gerrit hook which adds the Change-Id in the commit message).

You just need to execute:

git commit
git push origin HEAD:refs/for/BRANCH

If you really need to execute the "git commit --amend" command after the "git commit" one, is because you're doing something wrong.

  • Related