Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make existing folder a git subtree

Following my question Git subtree export and re-import woes I wanted to ask how I would convert a folder to a subtree.

Imagine I have a repository A where I have code that should now be shared with another project (and possibly more), so I put all shared code in folder "sub". This folder now should be extracted (without history if possible) to bare repository C. Afterwards "sub" should become a subtree from C, however without losing the history in A (very important). I also want to be able to make changes in "sub" and push these back to C.

like image 279
Frankie Avatar asked Sep 25 '12 20:09

Frankie


1 Answers

git subtree split does exactly that. Given a folder through --prefix it will generate a separate tree within you repo that you can push to another repository and then use as you see fit.

The current version of git (1.8.1) does not include subtree documentation, but you can find it here: https://github.com/apenwarr/git-subtree/blob/master/git-subtree.txt

The flow you could use is:

# In Repo A create your subtree split and push it
> git subtree split --prefix sub --branch subBranch
> git push C subBranch:master

# After some changes that touched the sub directory
> git subtree push --prefix sub C master

The last command wil re-split the tree (using the previously splited commits as to mantain the tree integrity of C) and push it to C/master.

If you want to remove the history to the content pushed to C you can use the --squash option when git split-ing and git push-ing. You must be consistent and keep using it forward, since if you start mixing squashed and non-squashed content subtree will not be able to properly split and reuse previos splits, and thus you will not be able to push it to C.

Lastly, once you created the first split of sub it is not entirely required that you delete it and reimport it as a new subtree. If you keep it git subtree will just regenerate/reuse previously created commits from other splits. If you do delete the folder and then re-add sub from the created commits it should still work, and if you are using --squash it will match what you want with C not having history, but keeping A history).

like image 109
Maic López Sáenz Avatar answered Oct 10 '22 17:10

Maic López Sáenz