git: Copying between repos

Tags: til git

Copying part of a source repository with all it's history to an arbitrary path inside a destination repository is possible via .patch file.

Capture all src commits as a .patch:

cd ~/repo1
git log \
    --pretty=email \
    --reverse \
    --binary \
    --full-index \
    --patch-with-stat \
    --first-parent \
    -m \
    -- dir1 \
    > dir1.patch

Then apply them under arbitrary directory on dest:

cd ~/repo2
git am \
    -p2 \
    --directory=dest1 \
    < ~/repo1/dir1.patch

The -p2 flag says to drop 2 levels of path prefix from the source when writing to the destination, so tweak that depending on how the source and destination look.

Published on: 21 Jul 2025