How do you merge two Git repositories?

后端 未结 23 3246
耶瑟儿~
耶瑟儿~ 2020-11-21 05:45

Consider the following scenario:

I have developed a small experimental project A in its own Git repo. It has now matured, and I\'d like A to be part of larger projec

23条回答
  •  无人及你
    2020-11-21 05:59

    git-subtree is nice, but it is probably not the one you want.

    For example, if projectA is the directory created in B, after git subtree,

    git log projectA
    

    lists only one commit: the merge. The commits from the merged project are for different paths, so they don't show up.

    Greg Hewgill's answer comes closest, although it doesn't actually say how to rewrite the paths.


    The solution is surprisingly simple.

    (1) In A,

    PREFIX=projectA #adjust this
    
    git filter-branch --index-filter '
        git ls-files -s |
        sed "s,\t,&'"$PREFIX"'/," |
        GIT_INDEX_FILE=$GIT_INDEX_FILE.new git update-index --index-info &&
        mv $GIT_INDEX_FILE.new $GIT_INDEX_FILE
    ' HEAD
    

    Note: This rewrites history, so if you intend to continue using this repo A, you may want to clone (copy) a throwaway copy of it first.

    Note Bene: You have to modify the substitute script inside the sed command in the case that you use non-ascii characters (or white characters) in file names or path. In that case the file location inside a record produced by "ls-files -s" begins with quotation mark.

    (2) Then in B, run

    git pull path/to/A
    

    Voila! You have a projectA directory in B. If you run git log projectA, you will see all commits from A.


    In my case, I wanted two subdirectories, projectA and projectB. In that case, I did step (1) to B as well.

提交回复
热议问题