You probably recognize the scenario where you are working on a new feature, things are progressing and you are creating commit after commit. After a series of commits, you realize that collaborators will get a better overview of your work if you just merged some of these together. Well, fear not, this is possible with something called a git squash.
A git squash can be accomplished with the
git rebase command. Consider the scenario where you are working on a login feature for a web site project. Your git log might look something like this:
bd6ed42 Add password input to login form d92deaf Add username input to login form 13e1380 Create login view
In the two latest commits you added the necessary inputs for the login view. You now reckon that it is for the best if these commits are merged together into a single commit with the message: “Create login form”. So lets get at it!
The first step is to enter the
git rebase -i HEAD~2 command - but what does it mean?
- The rebase command allows us to rewrite our project history (further reading about rebase).
-iflag tells git to run rebase in an interactive mode.
- The last part,
HEAD~2, tells the rebase command to work with with the grand parent of the latest commit in your current branch.
With the command entered you will see something in the lines of the following in your default text editor:
pick b1a64f0 Add username input to login form pick be832bf Add password input to login form # Rebase 3c20f69..be832bf onto 3c20f69 # # Commands: # p, pick = use commit # s, squash = use commit, but meld into previous commit # These lines can be re-ordered; they are executed from top to bottom.
If you pick squash on the second commit it will be merged into the first one. Lets do it!
pick b1a64f0 Add username input to login form squash be832bf Add password input to login form # Rebase 3c20f69..be832bf onto 3c20f69 # # Commands: # p, pick = use commit # s, squash = use commit, but meld into previous commit # These lines can be re-ordered; they are executed from top to bottom.
Save and exit your text editor. This will open a new window in your texteditor with the following contents:
# This is a combination of 2 commits. # The first commit's message is: Add username input to login form # This is the 2nd commit message: Add password input to login form # Please enter the commit message for your changes. ...
Change this text to whatever commit message you wish for, in our case “Create login form”, save and exit. Congratulations!
Trivia: The first time I did this I accidentally “lost” some of my commits (or so I think at least, it was probably possible to retrieve them again).