Helpful Git Commands to Slice & Dice Commits
This Conway's Game of Life repo is the
basis for the examples here, specifically, the activate-demo
and main
branches.
git cherry-pick
Say you have a bunch of commits in a branch that you want to break up into multiple commits (for
smaller Pull or Merge Requests). If you have confidence that your commits are atomic, use git cherry-pick
to copy them to a new branch. Use git log
to find the commit you want to copy in
your current working branch, grab its SHA. Checkout the main branch and create a new branch
off of it. Then change to the new branch and cherry-pick using:
git cherry-pick <SHA-of-COMMIT>
This is useful when you want to grab a single commit from one branch and place it in another one.
git rebase -i
But what if you have multiple commits you want to rearrange or move?
Rebase them. This is a very powerful tool. You can rewrite large chunks of history in one go
with this command. You can reorder commits. You can delete commits.
When using this command, you specify the number of previous commits you'd like to rebase with:
git rebase -i HEAD~5
This would target the previous 5 commits. The image below demonstrates the look of the rebase
menu with 5 commits. One thing to note is that the commits are listed oldest first.
Rebase commands:
p, pick <commit>: Actually use the commit in the result.
r, reword <commit>: Edit the commit message and use it.
e, edit <commit>: Amend this commit and use it.
s, squash <commit>: Use it but meld into the previous commit.
f, fixup <commit>: Like "squash," but discard this commit's log message.
x, exec <command>: Run command (the rest of the line) using the shell.
b, break: Stop here (continues rebase with git rebase --continue).
d, drop <commit>: Remove the commit.
l, label <label>: Label the current HEAD with a name.
t, reset <label>: Reset HEAD to a label.
m, merge: Create a merge commit.
As you can see, there is a lot you can do with this command. The most useful features for me are
typically squashing or rewording multiple commit messages in one step.
Interactive Rebase is useful for editing multiple commits in a branch at the same time.
git reflog
This command is useful if you make mistakes using the previous commands. The reflog contains all
the changes made to the tips of branches.
It's useful to find a safe place to reset your current working branch in case you've made a
mistake using cherry-pick or rebase. For instance, you can see the current HEAD (the tips of the
branches) on both your remote and local branches. If you haven't pushed your incorrect local
changes to a remote branch yet, you can recover the old HEAD from the remote branch locally—thus
reverting your mistake.
Using reflog gives you a map back to safety if you've made mistakes in your branch.