如何在Git中用分叉建立共同祖先?

How to establish a common ancestry with a fork in Git?

我有一个 git 存储库,其中包含项目 foo 的分支:

origin/master
+src/
|  +foo/
|     +A/
|     +B/
|     +C/
+stuff/

我还有一个项目foo的镜像:

upstream/master
+foo/
   +A/
   +B/
   +C/

我在 git 中还没有共同的祖先。我想建立一个共同的祖先以使将来的合并更容易,并合并自从我分叉以来对上游 foo 所做的任何更改。

我试图在上游之上对 foo 进行变基:

C:\src>git rebase -s recursive -X subtree=foo/ --root upstream/master

但是,这并没有达到我想要的效果。我最终 origin/master 看起来和 upstream/master 完全一样,其中包含 none 的更改,完全没有 stuff.

origin/master
+foo/
   +A/
   +B/
   +C/

我需要做什么才能将上游 foo 与我的 src/foo 合并?

我只能做这样的事吗?

C:\src>git merge upstream/master -s recursive -X subtree=foo/

我的建议是使用 git filter-branch 重写 upstream,就好像 foo/ 从一开始就是 src/foo/ 一样。基于 :

git filter-branch --commit-filter '
    TREE="";
    shift;
    SUBTREE=`echo -e 040000 tree $TREE"\tsrc" | git mktree`
    git commit-tree $SUBTREE "$@"' -- --all

那应该给我们:

upstream/master
+src/
   +foo/
      +A/
      +B/
      +C/

此时您应该能够简单地将 upstream/master 合并到 origin/master 中,得到一个看起来像这样的 git log --oneline --graph --decorate

*    (HEAD, master) Merge branch 'master' of upstream
|\
| *  (upstream/master) fourth upstream commit
| *  third upstream commit
* |  (origin/master) fourth origin commit
| *  second upstream commit
* |  third origin commit
| *  first upstream commit
*    second origin commit
*    first origin commit

这是一对本地存储库的概念证明 - 请注意 git pull 报告 "warning: no common commits":