Git apply-edit - improving `git edit`

In my last post I discussed the creation of a git helper called git-edit. The subcommand is really helpful but in this short post I’m going to look at a slightly different way of adding new git functionality that is built on top of git-edit.


Problem outline

When working on a feature I often find myself writing code and thinking “this should really be in an earlier commit”. There are many reasons for doing this:

These are all good uses for git-edit. A repeating usage pattern I see in my own work is that I will create the new work and then realise that I don’t want to target head, instead I want to target an earlier commit. So to perform a git-edit I often need to stash my changes, then run git-edit followed by git stash pop. Looking in my zsh history it appears that I do this a lot so it would be useful to automate it a bit.


git alias

For a simple chain of commands like this I don’t really need to make a separate executable script as I can just leverage git’s ability to add aliases.

~/.gitconfig

[alias]
  apply-edit = !sh -c 'git stash && git edit $1 && git stash pop' -

With this alias added to my .gitconfig I can now run git apply-edit <some-sha> from my current position.

I like this flow and the fact that the pop will fail if the working directory can not be reproduced cleanly just reminds me that if I had just used a --fixup this would have been more painful and less immediate to resolve.