2

The case: Branch A Commit1 -> Commit2 -> Commit3 -> Commit4

The head is currently in Commit4.

I would like to reset back (not hard) to Commit1 and use Commit1 as base to only implement whatever changes done in Commit4.

So the end result is: Commit1 -> Commit4

Is there any git command to do that? or I should rollback to Commit1 and implement changes done in Commit4 manually?

Thanks!

Hatjhie
  • 1,366
  • 2
  • 13
  • 27

2 Answers2

3

It is clear to me, based on your question, that you want the commit sequence to read:

... <- C1 <- new-C4   <-- branch

(remember, the arrows always point towards the past history, not forward into the future).

It's not clear to me whether you want your new commit (which I call new-C4 above) to keep the source the way it is in the old C4, or whether you want to discard all changes made in C2 and C3 while keeping just the changes made in C4.

You can achieve the latter result using git rebase, but keep in mind the usual caveat that you should never rebase a published commit. To make this happen, simply run:

git rebase -i HEAD~4

This will bring up an editor session where you can keep or discard specific commits. See the answer linked in Martin Konecny's comment, or Barry Gackle's answer.

If you want to keep the changes introduced by C2 and C3 while discarding the commits themselves, then git reset --soft followed by git commit is the correct method. See VonC's answer here.

Community
  • 1
  • 1
torek
  • 448,244
  • 59
  • 642
  • 775
1

An interactive rebase is what I would do here.

Let's say the hash to commit1 is 27af3 (I'm picking a random number here to illustrate -- do a 'git log' to get the actual hash)

You could do:

    git rebase --interactive 27af3

This will present you with a text editor screen showing a list of commits. Delete the lines containing Commit2 and Commit3, and save and quit. You will be sitting at the desired end state you indicated.

Note that this procedure will destroy commits 2 and 3, so be careful with this if you wanted to keep those for some other use.

Note also that you shouldn't do this if you've already pushed any of those four commits to a public server anywhere. Rebasing should in general only be used on strictly local portions of trees.

Barry Gackle
  • 829
  • 4
  • 17