This is a common problem for me. I make five or so commits then find that some debug code that became irrelevant or junk code from a prior used algorithm stays around. Amending them to HEAD doesn’t always make sense and making a new commit for a one-line late change feels disorderly.
The solutions I know of include the above and checking out the previous commit, branching, editing and merging again. This works fine, but I wonder if either a more idiomatic or elegant solution exists.
You can use interactive rebase to go back and edit a specific commit, as long as rewriting history is okay (basically, as long as you haven’t shared the commits with anyone else/the public).
To do so, first find the hash of the commit you want to edit. Then, tell Git to do an interactive rebase from the commit before it:
The
~1is important – it tells Git to reference the commit before the SHA you specified.This will bring up an editor with a line for each of your commits starting with the one you want to edit. Change the
pickfor that commit toedit, then save and quit out of the editor.Git will apply that commit, and then pause. You can then edit the files to remove the debug code,
git addthem, andgit commit --amendto edit the commit.Afterwards, use
git rebase --continueto apply the other commits in order, ending up back where you started (but with a new set of commits that doesn’t have your debugging code).