Skip to content

Instantly share code, notes, and snippets.

@wevtimoteo
Last active February 21, 2024 22:42
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wevtimoteo/a6f4b0837cdc3749dd6b to your computer and use it in GitHub Desktop.
Save wevtimoteo/a6f4b0837cdc3749dd6b to your computer and use it in GitHub Desktop.
Moving files across git repositories preserving history
git clone <git repository A url>
cd <git repository A directory>
git remote rm origin
git filter-branch --subdirectory-filter <directory 1> -- --all
mkdir -p <target-path in="" repo-b="">
git mv -k * <target-path in="" repo-b="">
git add .
git commit

Make a copy of repository B if you don’t have one already. On line 3, you’ll create a remote connection to repository A as a branch in repository B. Then simply pull from this branch (containing only the directory you want to move) into repository B. The pull copies both files and history. Note: You can use a merge instead of a pull, but pull worked better for me. Finally, you probably want to clean up a bit by removing the remote connection to repository A. Commit and you’re all set.

git clone <git repository B url>
cd <git repository B directory>
git remote add repo-A-branch <git repository A directory>
git pull repo-A-branch master
git remote rm repo-A-branch

Source: http://gbayer.com/development/moving-files-from-one-git-repository-to-another-preserving-history/

@RochaStratovan
Copy link

This method doesn't pull in the entire history if the file or folder has been removed or renamed

@wevtimoteo
Copy link
Author

wevtimoteo commented May 18, 2022

@RochaStratovan has been a time since I did that (this snippet was written 7 years ago). And it's possible to check history for removed or renamed using --follow flag for git log. If you need to learn more about it: https://kgrz.io/use-git-log-follow-for-file-history.html

@RochaStratovan
Copy link

@wevtimoteo - I am familiar with git log --follow for finding the full history of a file.

My comment is the method above for moving files from one repository to another "with history" doesn't actually provide all the history. The method presented above doesn't follow a file that has been moved.

This only provides the history up to the point that the file has been moved or renamed.

@wevtimoteo
Copy link
Author

@RochaStratovan Yeah, without the flags from the blog post (such --follow) it won't. If you find another method of doing this that keeps the history removing the need to use --follow or other git log flag, please let me know!

@RochaStratovan
Copy link

You cannot use --follow with git filter-branch. That's my point. The method cited above won't give complete history of files that have been renamed/moved, and there is no --follow option for git filter-branch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment