Two elderly gentlemen playing golf at a country club

Git: Editing your commits with rebase - part 2/2

In the previous post, we have seen two of the things that are possible to do with interactive rebase:

  • change the commits order
  • edit the commits message

In this post, we’re going to see how to merge two commits and also how to divide a commit in two.

Remembering

I strongly recommend you read the previous post, to get used to the rebase flow. So, we run again the command:

And then, we see a screen like that:

So far, nothing new. Let’s move on…

Merging commits

Let’s merge the commits related to CSS and JS adjustments, which probably are similar (they even could edit the same code) and perhaps it makes sense if they were only one commit.

To do that, we type squash in a commit. Doing that, git understand we want to merge this marked commit with the previous one (above).

After that, we see a screen that shoes both commits messages:

Now we just have to remove or comment the lines with the commits messages and insert the new message:

And… done! Now if we run a log of the commits, we will see something similar to:

Splitting a commit

As we’re crazy, now we want to revert the previous process and spit the commit that was merged. Jokes apart, we can do it, for example, in a commit that with a lot of changes and perhaps we could split it to make the git commit story better to understand. So we run the rebase:

We see a screen that we are used to knowing; then we change the word pick for edit in the commit we want to edit.

So, quit the edit mode and we’re going to see this:

This is the cool part. What happened here was the rebase stopped in the commit we specified. Now we have three options:`

  • git commit --amend => to change the commit editing/adding one or more files.
  • git rebase --continue => to move on with therebase without doing anything (use this same command before the previous on to continue with the rebase).
  • git reset HEAD^ => Return the commit we are stopped.

At this point, if we run a git status we would see the files that were modified in the commit:

Now we could add the files and commit them. Theoretically, here you do the commits splitting. For our example, we could do something like:

What we did was adding files step by step and make commits. With all of this done, we could move on with the rebase:

And… done! Now if we look the log, we would have something like that:

Forcing the push

As well remembered by Cícero Pablo, when we use the interactive rebase , if you already have a repository with a history of commits, you must do push with the --force flag.

Some notes.

  • The file names/structure and messages of all commits are just an example.
  • We used the word screen to make reference each return of the terminal.
  • By default, my terminal editor is vim, that makes easier to edit the screens that I commented in the previous topic.
See all posts...