0

I have the following structure in my repo:

|-commit9 [bugfix]
|-commit8
|-commit7
|-commit6
|-commit5 [branch-2]
|-commit4
|-commit3
|-commit2 [branch-1]
|-commit1
o-master

The bugfix is applied on top of other commits. How do I move the commit8 and commit9 to an earlier point, for example, immediately on top of master?


I followed the instructions in here: How to inject a commit between some two arbitrary commits in the past? and now my repo looks as follows:

|-commit7
|-commit6
|-commit5
|-commit4
|-commit3
|-commit2
|-commit1
|-commit9 [bugfix]
|-commit8
| |-commit9 [bugfix]
| |-commit8
| |-commit7
| |-commit6
| |-commit5 [branch-2]
| |-commit4
| |-commit3
| |-commit2 [branch-1]
| |-commit1
|/
o-master

So commit8 and commit9 are where I intended originally, but the rest of the commits are duplicates and I don't have the branch names of course.

How do I get a "linear" history now?

Community
  • 1
  • 1
Kristof Pal
  • 966
  • 4
  • 12
  • 28
  • Why would you want to do this? The bugfix came after the bug was discovered in certain commits, so I don't see any particular value in moving this commit before them. Wouldn't a squash on the commits between branch 1, branch 2 and bugfix suffice? – Makoto Aug 24 '16 at 20:23
  • @Makoto all of the commits were made such that to force the bug. And the bugfix belongs to "deep in the code" so every subsequent commit should have it included – Kristof Pal Aug 24 '16 at 20:33

1 Answers1

1

Well you're getting there.

First of all, push to a remote or clone your local repo in another place. Just to be sure. After that lets fix that master branch. Be sure you're on that branch before we continue.

git checkout master

Now we don't want those other commit, just 8 and 9. Since they're already there we can simply reset the master branch to commit 9 and remove the other commits. No worries, your commits are still in the branches so nothing should be lost.
Replace [commit9@master] with the sha of your commit.

git reset --hard [commit9@master]

Now go ahead and checkout the bugfix branch and reset it to commit 7 the same way as we did with the master branch.

git checkout bugfix
git reset --hard [commit7@bugfix]

Now for the last part to get back to a linear flow you can merge your hotfix back to master and have all your work at the same place.

git checkout master
git merge bugfix

Answering the original question

I guess the easiest way would have been to checkout your master branch. Cherry-pick the two commits you wanted to move. Go back to your original branch and reset it back two commits. The latter can be done by using

git reset --hard HEAD^2

Which means remove two commits from my current position.

Little warning: Moving commits can be dangerous. Since you made your commits based on a certain change set, the same code might not behave the same way in its new position. Seeing your moved code might depend on code no longer existing.

Maarten Bicknese
  • 1,498
  • 1
  • 14
  • 27