Skip to content

Instantly share code, notes, and snippets.

@martinbuberl
Last active March 27, 2025 10:43
Show Gist options
  • Save martinbuberl/b58fd967f271f32f51f50aee62e7332c to your computer and use it in GitHub Desktop.
Save martinbuberl/b58fd967f271f32f51f50aee62e7332c to your computer and use it in GitHub Desktop.
Import an Existing Git Repository into Another

Import an Existing Git Repository into Another

Before: Folder Structure (Two Separate Repositories)

XXX
 |- .git
 |- (project files)
YYY
 |- .git
 |- (project files)

After: Folder Structure (XXX Imported into YYY as a Subdirectory)

YYY
 |- .git  <-- This now contains the full change history from XXX
 |- ZZZ   <-- This was originally XXX, now a subdirectory of YYY
    |- (project files)
 |- (project files from YYY)

Steps to Import

Run the following commands inside YYY to import XXX as a subtree:

git remote add XXX_remote <path-or-url-to-XXX-repo> # Add XXX as a remote
git fetch XXX_remote # Fetch history from XXX
git merge -s ours --no-commit XXX_remote/master # Merge without modifying YYY's files
git read-tree --prefix=ZZZ/ -u XXX_remote/master # Move XXX into subdirectory ZZZ
git commit -m "Imported XXX as a subtree." # Commit the changes
git remote rm XXX_remote # Remove temporary remote
git push # Push changes to the repository

Explanation

  • Preserves full commit history of XXX.
  • Places XXX’s files inside ZZZ/ within YYY.
  • Does not modify YYY’s existing files during the merge.

Source: Stack Overflow

@opcloete
Copy link

opcloete commented Aug 1, 2018

Git amazes me daily. Thanks for the notes!

@calarasiu
Copy link

Thanks for the notes. It saved me a lot of browsing

@MattFL
Copy link

MattFL commented Feb 19, 2021

Thank you this was very helpful! @christillman your tip as well!

@sshveta
Copy link

sshveta commented Apr 30, 2021

Very useful. Thanks !

@SmartByAccident
Copy link

Doesnt keep file histories

@hustc12
Copy link

hustc12 commented Jul 4, 2022

Thanks! It's very helpful!

@Deepti0512
Copy link

If I delete XXX now, will it cause any effect in YYY ?

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