Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a common ancestor in a git merge?

Tags:

git

merge

Let's say I have a branch called master and a branch called upstream_lib.

The branch master has a subdirectory lib that is based on the code that's on the branch upstream_lib; changes in upstream_lib are merged (with the subtree strategy) to the master branch periodically. The lib directory in master has some modifications of its own that are not in upstream_lib.

However, let's say the two branches either have no common history (because the repository was just migrated to git, for instance) or the merge base is incorrect because the merges in upstream_lib have been squashed, there has been some rebasing or whatever.

The question is: given a new set of changes on upstream_lib, how to force the merge to consider as the common ancestor a specific revision of upstream_lib?

like image 323
Artefacto Avatar asked Jan 12 '11 11:01

Artefacto


People also ask

How does git find common ancestor?

git merge-base finds best common ancestor(s) between two commits to use in a three-way merge. One common ancestor is better than another common ancestor if the latter is an ancestor of the former. A common ancestor that does not have any better common ancestor is a best common ancestor, i.e. a merge base.


1 Answers

I've never used the subtree strategy, so maybe this is a suboptimal solution (and maybe it won't work ^^), but you could apply all the new commits in upstream_lib to a temporary branch off of the master line and then merge that. What I have in mind doesn't fundamentally fix your situation, so you'll have to do this kind of "manual merge" every time you want to pull in new changes, but here's how it works:

  1. Determine the fake common ancestor in the master ancestry line, say master~100.
  2. Determine the fake common ancestor in the upstream_lib line, say upstream_lib~150.
  3. Make a throwaway copy of the upstream_lib branch: git branch --no-track new_upstream_lib upstream_lib
  4. Rebase new_upstream_lib onto master~100 using the recursive strategy with the subtree option. (I don't think you can just use the subtree strategy because, as you say, the lib directory in master has changes of its own.) Here's a completely untested command for this:

    git rebase -s recursive -X subtree=lib --onto master~100 upstream_lib~150 new_upstream_lib
    

    Note that new_upstream_lib now has the whole master tree in it, even though you only care about the lib directory.

  5. Merge it: git checkout master && git merge new_upstream_lib && git branch -d new_upstream_lib.
like image 145
Jo Liss Avatar answered Sep 19 '22 17:09

Jo Liss