Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy a directory from one git repository to another, preserving history?

I know that I can create a new repository out of a directory of a git repository. See here: https://help.github.com/articles/splitting-a-subfolder-out-into-a-new-repository/

However, how can I copy a directory from one repository to a new directory of another completely different repository, while keeping history of that directory?

Update: is it possible for that history to show up with git log?

like image 293
namin Avatar asked Sep 08 '12 00:09

namin


People also ask

How do I merge Git repositories and keep history?

To combine two separate Git repositories into one, add the repository to merge in as a remote to the repository to merge into. Then, combine their histories by merging while using the --allow-unrelated-histories command line option.

Does Git clone preserve history?

If you create a new clone of the repository, you won't lose any of your Git history or changes when you split a folder into a separate repository. Open Terminal . Change the current working directory to the location where you want to create your new repository. Clone the repository that contains the subfolder.


1 Answers

You could do this with git filter-branch. Basically you'd want to:

  1. Split out the subpath in the first project into a new repository, using the link you've already found.
  2. Push it to the second project's remote on a unique branch.
  3. Fetch that branch into the second repository, then use git filter-branch to index-filter it into the correct subdirectory:

    git filter-branch --index-filter '
        git ls-files -sz | 
        perl -0pe "s{\t}{\tnewsubdir/}" |
        GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
            git update-index --clear -z --index-info &&
            mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
    ' HEAD
    
  4. Finally, checkout the master branch of the second project (or whatever branch you're using), then merge in the newly-filtered branch.

Really not too awful an operation, all told. As AlexanderGladysh notes in the comments, you could also use a subtree merging strategy in the place of steps 3 and 4.

like image 142
Christopher Avatar answered Nov 08 '22 03:11

Christopher