Merge git repository in subdirectory

后端 未结 7 1331
有刺的猬
有刺的猬 2020-11-30 19:32

I\'d like to merge a remote git repository in my working git repository as a subdirectory of it. I\'d like the resulting repository to contain the merged history of the two

7条回答
  •  没有蜡笔的小新
    2020-11-30 19:55

    I wanted to

    1. keep a linear history without explicit merge, and
    2. make it look like the files of the merged repository had always existed in the subdirectory, and as a side effect make git log -- file work without --follow.

    Step 1: Rewrite history in the source repository to make it look like all files always existed below the subdirectory.

    Create a temporary branch for the rewritten history.

    git checkout -b tmp_subdir
    

    Then use git filter-branch as described in How can I rewrite history so that all files, except the ones I already moved, are in a subdirectory?:

    git filter-branch --prune-empty --tree-filter '
    if [ ! -e foo/bar ]; then
        mkdir -p foo/bar
        git ls-tree --name-only $GIT_COMMIT | xargs -I files mv files foo/bar
    fi'
    

    Step 2: Switch to the target repository. Add the source repository as remote in the target repository and fetch its contents.

    git remote add sourcerepo .../path/to/sourcerepo
    git fetch sourcerepo
    

    Step 3: Use merge --onto to add the commits of the rewritten source repository on top of the target repository.

    git rebase --preserve-merges --onto master --root sourcerepo/tmp_subdir
    

    You can check the log to see that this really got you what you wanted.

    git log --stat
    

    Step 4: After the rebase you’re in “detached HEAD” state. You can fast-forward master to the new head.

    git checkout -b tmp_merged
    git checkout master
    git merge tmp_merged
    git branch -d tmp_merged
    

    Step 5: Finally some cleanup: Remove the temporary remote.

    git remote rm sourcerepo
    

提交回复
热议问题