0

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?

Elucidase
  • 33
  • 7
  • 1
    The wording of your question is slightly confusing to me. If `a` and `b` _had_ merge conflicts, how is that relevant if in the end you have already made those commits? – Tim Biegeleisen Dec 06 '21 at 04:38
  • Please give more details. How does a and b have conflicts. Are you trying to merge the branch you're talking about into a different branch? If so, how would disregarding commit c help with this? a and b would still cause conflicts during that merge – Lasse V. Karlsen Dec 06 '21 at 08:40

1 Answers1

2

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.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 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? – Elucidase Dec 06 '21 at 13:05
  • @Elucidase I have edited the answer to address your comment/edited question. – VonC Dec 06 '21 at 13:19