DEV Community

tackme
tackme

Posted on • Edited on

Integrate Current Changes into a Specific Commit without Opening the Editor

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"
Enter fullscreen mode Exit fullscreen mode

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:

  1. Temporarily commit the current changes.
  2. Perform an interactive rebase.
  3. Shift the temp commit right below the target commit.
  4. Change the temp commit's command to 'fixup'.
  5. 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^
Enter fullscreen mode Exit fullscreen mode

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^
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

Now, whenever you need to tweak a past commit, simply run git cmfr HASH.

Happy coding! 🚀

Reference

Top comments (0)