Jason R. Coombs
Jason R. Coombs

Reputation: 42724

How to recover merge commit after checkout?

I started on master and sought to merge a series of commits from branch: git merge branch. I resolved half a dozen conflicts between that branch and master. Then I was ready to commit, but decided for sanity I wanted to commit the merge commit to a new branch, experimental, so I ran git checkout -b experimental, then committed the resolved commits. When I did, to my dismay, I found that the new commit on experimental had only one parent (master), effectively a squash commit.

Is there a way to re-do the merge without having to re-do the merge conflicts? That is, I'd like to create a commit in new branch whose parents are master and branch and whose changes resolve to experimental. Is it possible?

Also, how could I have avoided losing the parents in my original situation, where I decided I wanted to commit the merge to a different branch?

Upvotes: 1

Views: 1306

Answers (2)

Jason R. Coombs
Jason R. Coombs

Reputation: 42724

I figured it out.

I first create a new merge commit that has the ancestry I'm seeking. I use --strategy ours to save time resolving merges:

git checkout -b remerge master
git merge branch -s ours

I then checkout the experimental branch and use reset --soft:

git checkout experimental
git reset --soft remerge
git commit -a --amend

And then cleanup:

git branch -D remerge

To avoid this in the first place, the only thing I can think of is I should have committed the merge in the original branch (master), then created a branch, then reset master.

Upvotes: 3

che
che

Reputation: 12273

If you have all the changes you want in experimental, you can make a new commit using git commit-tree:

  • use git cat-file commit experimental to get tree hash (i.e. contents you want in the merge commit)
  • make a merge commit manually: git commit-tree -p master -p branch ${tree_hash} -m 'commit msg'

This will print a hash of a new commit, which you can then merge into master, and fix commit message using git commit --amend.

Upvotes: 2

Related Questions