Difficulty: Beginner
Estimated Time: 10 minutes

An important aspect of Git is how clean you keep your repository and history. A clean repository is easier to work with and understand what's happened.

This scenario will cover how you can re-write your Git history using Rebase to restructure your commits to ensure they're understandable before you push your changes.

Recommendation

You should only rebase commits that have not been shared with other people via push. Rebasing commits causes their commit-ids to change which can result in losing future commits.

The ability to re-write history is useful to keep your history of the repository clean and accurate. This will help in future to indicate reasons for change or to debug problems.

This scenario has been added to your scrapbook where you can review the examples and commands you executed.

Recommendation

You should only rebase commits that have not been shared with other people via push. Rebasing commits causes their commit-ids to change which can result in losing future commits.

Don’t stop now! The next scenario will only take about 10 minutes to complete.

Scenario 9 - Re-writing History

Step 1 of 4

Amending Commit Messages

Re-writing the repositories history is done using git rebase -interactive. By putting rebase into interactive mode you have more control over the changes you want to make. After launching into interactive mode you are given six commands to perform on each commit in the repository. By using the editor which opens, by default Vim, you define which actions you want to perform on each commit.

In this example we want to change the commit. To put it into this state we need to change the word "pick" next to the commit to match the action you want to perform based on the list shown in the Vim window, in this case "reword".

In this example we want to change the commit message.

Start

To begin we need to enter Interactive Rebase mode using git rebase --interactive --root

Select Interactive Mode

To begin with Vim can be a little confusing, to edit text you need to first type i which will put you into "insert mode".

We want to edit the "comit" typo in the first commit message "Initial comit of the list". For the commit change the word "pick" to match the command we want to perform on the commit, in this case "reword".

To save and exit press esc key then :wq. This will open another Vim editor window.

Changing Message

Again using Vim, edit the commit message to change "comit" to "commit". After saving and exiting Vim you will see the output of Git changing the commit. Use git log --oneline to see the updated commit message.

Protip

The --root argument allows you to rebase all commits in the repository, including the first commit.

A faster alternative to change the last commit message is using git commit --amend and make the change using Vim.