I know two methods to change a commit message in git.
The first is git amend, which only works for the latest commit. Since I want to be able to change older commit messages directly, this is not what I am looking for.
The second is an interactive rebase as described in this answer for example, which can also change commit messages of older commits. The procedure is to use
git rebase -i HEAD~n
where I have to manually count how large is n for my specific case, then scroll through a list of all those commits and change the one commit from pick to reword, then finally type the new commit message and force push.
Honestly, while this works, it is insanely complicated and tedious to do this. So my questions is, is there an easier to use option (perhaps in form of an alias), where this procedure is automatically performed in one step?
Ideally, I would like to have a command like:
git reword <hash> -m "New commit message"
and after that just force push. Is this possible?
Edit: I want to get rid of the interactivity, because I want to programmatically automatize some git commands from my program. Having to interact manually with git during that process kind of defeats the purpose of such an automation.
With more recent versions of Git, the simplest option seems to be git commit --fixup=reword:commit:
--fixup=[(amend|reword):]<commit>Create a new commit which "fixes up"
<commit>when applied withgit rebase --autosquash. […]--fixup=reword:<commit>creates an "amend!" commit which replaces the log message of<commit>with its own log message but makes no changes to the content of<commit>.[…]
--fixup=reword:<commit>is shorthand for--fixup=amend:<commit> --only. It creates an "amend!" commit with only a log message (ignoring any changes staged in the index). When squashed bygit rebase --autosquash, it replaces the log message of<commit>without making any other changes.
So, you would run the following commands:
git commit --fixup=reword:commit-to-amend
git rebase -i --autosquash commit-to-amend^
But this doesn't allow specifying the commit message via CLI arguments, so we need to mimic the behavior of Git by crafting the correct commit message required by autosqash:
git config alias.reword2 '!f() {
git commit --allow-empty --only -m "amend! $1
$2" &&
GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash "$1^";
}; f'
And then executed with git reword commit-to-amend 'your new message'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With