batman
batman

Reputation: 5390

How to remove a middle commit without removing the changes introduced by it?

I have a commit history that looks like this:

A - B - C

Now I want the files to remain as they are, but I find that commit B is unnecessary.

So I want the history to become:

A - C

keeping the changes introduced by B.

Is this possible?

Upvotes: 1

Views: 301

Answers (2)

AD7six
AD7six

Reputation: 66368

interactive rebase and fixup/squash

An easy way to do so is to do an interactive rebase, and squash two commits together:

$ git rebase -i A

This will show an editor with a screen like so:

pick A commit message
pick B commit message
pick C commit message

# Rebase A..C onto A

Simple read the options available, modify the file in your editor, and e.g.:

To merge B into A

pick A commit message
squash B commit message
pick C commit message

To merge C into B

pick A commit message
pick B commit message
squash C commit message

Using squash allows you to then modify the commit message to your liking (for example to use the commit message of C with the resultant commit), if the commit message is not important you can instead use fixup.

Upvotes: 2

gturri
gturri

Reputation: 14639

You can squash commits B and C. Run git rebase -i sha1_of_A. It will open a text editor with a list of commits. Put fixup on the line of the C commit, save, and exit.

What will happen:

At the beginning you have:

A -B - C
       L HEAD

After merging the commits you will have:

A - B - C
  \ C'
    L HEAD

Where C and C' will have the same files.

It means that:

  • You will have the commits you want
  • Your commits B and C aren't actually lost, so you can get back to it if you have some remorses
  • When you play with interactive rebase, it's easy to add a safety net: tag the commit from where you start, so you'll be able to easily get back to it if things get complicated

Upvotes: 2

Related Questions