TL;DR
Set up the following alias in your Git configuration.
[alias]
cmfr = "!f() { git commit --fixup \"$1\"; GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash \"$1\"^; }; f"
Now you can execute git cmfr HASH
to apply the changes.
How it works
When integrating current changes into the most recent commit, we typically use the commit --amend
command. Adding --no-edit
lets us do this without opening the editor. But what if we need to alter not the latest commit, but an earlier one?
The usual steps for this are somewhat cumbersome:
- Temporarily commit the current changes.
- Perform an interactive rebase.
- Shift the temp commit right below the target commit.
- Change the temp commit's command to 'fixup'.
- Save and exit the editor.
This process involves more steps than necessary. Using --fixup
and --autosquash
can simplify it. The commands below bring you directly to step 4 of the aforementioned process:
> git commit --fixup HASH
> git rebase -i --autosquash HASH^
Then just close the editor and you are done. Since we've simplified the process considerably, we'd also like to bypass the editor-closing step.
In Git, the rebase editor can be changed by setting the GIT_SEQUENCE_EDITOR
environment variable. This variable can be set to vi, emacs, vscode, sed, etc. Interestingly, using the bash built-in command :
(a no-operation command) for this variable simulates an immediate exit without performing any action. Using this feature, the following commands can execute all steps in just two commands:
> git commit --fixup HASH
> GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash HASH^
The final step is to save this sequence as an alias:
[alias]
cmfr = "!f() { git commit --fixup \"$1\"; GIT_SEQUENCE_EDITOR=: git rebase -i --autosquash \"$1\"^; }; f"
Now, whenever you need to tweak a past commit, simply run git cmfr HASH
.
Happy coding! 🚀
Top comments (0)