Move files and folders between git repos using patches


Some times you need to carve off code from one repo to another repo. As I build out a package I like to think about which parts might be useful elsewhere and sometimes I move them to their own repositories. This simplifies development and keeps a composable focus for my work. However, I do like preserving history and while I have not always been able to do so I recently had to do another carve out task to move some code that had been prototyped in one repo into its own repo. I primarily use git as my version control system and this is my own workflow for setting up a new repo with code carved from another repo and still preserving history.

If you put in a google search for “Moving files from one git repo to another” you will probably end up somewhere suggesting you do a git filter-branch to make a branch in repo A to then pull into repo B. I find that process a little destructive and more involved then simply pulling out all the patches for a given folder/files and applying them to the new repo. This has the added benefit of keeping both the history of what was done in the other repo (who wrote what) but also that the files were applied by the person setting up the new repo.

# Setup a directory to hold the patches
mkdir -p ~/tmp/patches/
# Create the patches
git format-patch -o ~/tmp/patches/ --root /path/to/copy
# Apply the patches in the new repo using a 3 way merge in case of conflicts
# (merges from the other repo are not turned into patches). 
# The 3way can be omitted.
git am --3way ~/tmp/patches/*.patch

# you can confirm the files and folders are the same by doing a simple
diff -qr $pathA $pathB

# Diff will output which path has items that differ from the other path.
# If there is no output the paths are the same.

Details on how git am works can be found here and git format-patch here

You can easily abort of the patch application and git will provide output as it goes through each patch. I feel this approach is more honest with the actual history of the new repository but can bring its own challenges just as the filter-branch method does. If you’re interested in patch based workflows then this is a good place to start.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *