Squash, fixup and remove commits on GitHub

Multiple numbers of commits on a pull-request can be merged into a single commit using the squash and fixup option provided by Github. This article is to check how to merge different commits on your Github repository or remove any unwanted commits on your pull request.

Consider the following example to do this -

1. Create a local git branch on your terminal. 

$ git checkout upstream/master -b test_branch

where -

"upstream" is the name of the remote URL that is being cloned. You can view the remote branch name by typing git remote -v on your terminal.

"master" is the remote branch name.

"test_branch" is the local name of my branch.

2. Modify different files and commit the changes. So let's say I have 3 changed files which is committed separately as shown below -

$ git commit first_file_name -m "first_commit";
$ git commit second_file_name -m "second_commit";
$ git commit third_file_name -m "third_commit";

You can also type -a to commit all your changes shown under git diff. It will add all your changes to a single commit hash.

Squash all your commits into one.

To squash your commits, enter the below command on your terminal -

git rebase -i HEAD~3

where -

-i is for --interactive mode which lists the number of commits into an editor.

~3 is to limit the list to last three commits.

The above command will open an editor which looks like -

pick 3d913cf5ed first commit
pick 11aba84be8 second commit
pick dc3ea0f1c6 third commit
.
.
followed by some list of commands...

To merge your "second commit" into your first, replace "pick" word on the first column with "squash" and save the file. This will merge the two commits and will preserve the commit log message - "second commit".

Fixup

As the list of command on the editor says, this command behaves just like squash, but will also discard the commit log message. It completely merges the second commit and consider them as single commit with only one log message. To do this replace "pick" work from the line you want to merge upward with "fixup" and save the file.

Remove commit from the PR

You can do this by simply deleting the line and save the file. The commit will be removed from your github.

Push your changes to Github

After all the above changes are made, if the editor is vi - save the file by pressing `Esc` key(come out of edit mode) and typing ":wq"(Save and Quit) and Enter. 

You can now push your changes to your repository by -

$ git push -f origin test_branch

where "origin" is the branch on Github UI, from where the pull request is made, -f is to push forcefully.