Editing your last few commits
Real work is messy: by the time your feature is done, the branch reads wip, fix typo, actually works now. Before asking teammates to review that (lesson 8-2), you can tidy it. Interactive rebase is Git's editor for recent history:
$ git rebase -i HEAD~3meaning "let me rework my last three commits." Git opens a todo list in your editor, one line per commit, oldest first:
pick a1b2c3d Add search box
pick e4f5a6b wip
pick c7d8e9f fix typo in search boxYou don't edit the code here. You edit the plan: change the word at the start of each line, save, close, and Git replays the commits according to your instructions.
The four verbs worth knowing
| Verb | Effect |
|---|---|
pick | keep the commit as is |
reword | keep it, but let me rewrite the message |
squash | combine this commit into the one above it — one commit results, carrying both sets of changes and both messages |
drop | delete the commit entirely |
So to clean the example, you'd squash the two fix-up commits into the real one:
pick a1b2c3d Add search box
squash e4f5a6b wip
squash c7d8e9f fix typo in search boxResult: one commit, "Add search box", containing all the work. The reviewer sees a clean, logical change.
Since this is a rebase, everything from lesson 9-1 applies: the survivors are new commits with new hashes, so tidy before pushing, and if a rebase goes sideways, git rebase --abort backs out (like merge --abort in lesson 6-2), and the reflog from lesson 4-3 still remembers the originals.
Quiz
In an interactive rebase todo list, what does changing pick to squash on a commit do?
Quiz
When is it safe to squash and reword your branch's commits with interactive rebase?
Problem
You have three messy commits and want the last two melted into the first so reviewers see one clean commit. Which todo-list verb do you put on the last two lines?