Search code examples
gitmerge-conflict-resolution

How do I add a parent to a commit in git?


I recently rebranched - that is, created a new branch off master and merged in a feature branch, e.g. TASK-123, with the new branch, TASK-123-b, replacing the feature branch that was merged into it. This is a regular action in our git workflow whenever a feature branch conflicts with master.

When I merged TASK-123 into TASK-123-b, there was of course a merge conflict, which I've resolved and then committed. The new branch, TASK-123-b, and the commit merging in TASK-123, only have one parent: master

How can I modify the commit so that both master and TASK-123 are its parents? I assume git rebase will be involved, but beyond that I don't know how to add a parent branch/commit to a commit.

My commit history currently looks like this:

    master -*---*-----* ...
             \         \
  TASK-123    *---*-*   \
                         \   
TASK-123-b                * ...

I want my commit history to look like this:

    master -*---*-----* ...
             \         \
  TASK-123    *---*-*   \
                     \   \   
TASK-123-b            \---* ...

Note: I haven't pushed TASK-123-b to a remote yet, so rebasing commits on it should cause no problems with my coworkers.


Solution

  • You need to redo the merge of TASK-123 into TASK-123-b because it looks like it didn't work like you wanted it to. To do that, find the commit hash in TASK-123-b just before the merge and reset your branch pointer there:

    $ git checkout -B TASK-123-b abc123
    

    Then repeat the merge:

    $ git merge TASK-123
    

    If you reset the branch pointer, the old merge commit is going to be orphaned and won't show up in the logs unless you specifically mention it as an argument. If you want to get it back, the hash will be recorded in the reflog or you could just copy the hash down somewhere and use the checkout -B command to put it back if you decide you need to.

    If you don't want to resolve the conflict again, then don't reset the branch pointer, just merge again:

    $ git checkout TASK-123-b
    $ git merge TASK-123
    

    And remove the old branch:

    $ git branch -d TASK-123