Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to make git repo to be another's repo subfolder preserving history

Hacky way (let me know if you know better one)

Let's say you have repo Main and repo Proto, you want to put your Proto under Main, so folder structure will be the following:

|-SRC
   |---proto

and you also want to preserve commit history, so everybody can see what you were doing while developing proto, sounds like pretty easy task. The easiest way is to create folder structure similar to Main repo SRC\proto and start working using is as a root, but if you like me, you didn't think about this beforehand, so you path would be harder:

  • create orphan branch in you Proto repo $ git checkout --orphan tmp
  • create folder structure similar to Main repo (SRC\proto) $ mkdir SRC\proto
  • commit this empty folders (dont forget to add .gitkeep since git doesn't track directories)
  • rebase your master branch onto tmp $ git checkout master; git rebase tmp
  • run nuclear command to move all your files from ./ to ./SRC/proto
    • $ git filter-branch --tree-filter 'mv * ./SRC/proto; git mv -k * ./SRC/proto' HEAD
      • this command will move all files from root dir to sub-dir on every commit in the history and re-commit files, which should result in a new root dir for all files
    • important caveat is that that command won't move files starting with . like .editorconfig or .bowerrc , we will fix it in the next step
      • note that you don't want to move .gitignore but merge it with your another repo's one
  • now add your Proto repo as a remote to your Main repo $ git remote add proto ~/proto/.git
    • replace ~/proto/.git to your local file system path to .git folder of your proto repository
  • rebase on top of your main repo master your proto/master branch
@juanavelez

This comment has been minimized.

Copy link

@juanavelez juanavelez commented Jan 3, 2018

What is the last command? I tried

git rebase proto master

but I get

fatal: Needed a single revision
invalid upstream proto

Thank you - Juan

@Noah-Huppert

This comment has been minimized.

Copy link

@Noah-Huppert Noah-Huppert commented Apr 26, 2018

@juanavelez I had to run 2 commands for the last step:

First to make Git aware of the branches in my local Git repo. Since I was trying to merge in a branch other than master:

git fetch proto

Next to rebase I ran:

git rebase proto/mybranch

The slash between the remote name and the branch name tells Git to look for a specific commit (Learned from this SO question).

Additionally a note on the git remote add step. You must use a absolute path. I found that if you did not Git could not access the local repository.

Hope this helps.

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