Home > Mobile >  Git manually merge 2 commits that are not HEAD
Git manually merge 2 commits that are not HEAD

Time:12-07

If we have a branch with commits a -> b -> c (HEAD), and a, b has conflicts that cannot be auto-merged, how can we discard c and manually resolve the conflict of a and b again to produce a new commit?

Say in commit a, we have a file foo.txt. In commit b, we modified foo.txt (we we later regret) and added bar.txt. Then we have a bogus commit c. How to produce a commit with the a's version of foo.txt and with b's bar.txt present?

CodePudding user response:

You can do an interactive rebase (as illustrated here):

git rebase -i a~

In the "todo" list generated by this rebase, you would:

  • drop c
  • squash b
  • pick a

b would be squashed with a, c would be no more.


For a more targeted approach:

Say in commit a, we have a file foo.txt.
In commit b, we modified foo.txt (that we later regret) and added bar.txt.
Then we have a bogus commit c.

How to produce a commit with the a's version of foo.txt and with b's bar.txt present?

You can easily restore a file from any older commit:

# Before Git 2.24 (not recommeded, please upgrade Git)
git show <sha-a>/the/root/myfile.txt --output=myfile.txt
git add myfile.txt

# Git 2.24 
git restore -s <SHA1> -SW -- afile
# no git add needed: already done by restore -S (for staging)

You then make a new commit, with the right content restored.

  •  Tags:  
  • git
  • Related