A simple git subtree tutorial

Here is a quick overview on how to create a git subtree.

I created two public repos to play around with:

https://github.com/CariZa/testing-subtrees-main-repo
https://github.com/CariZa/testing-subtrees-sub-repo

Repository inception

Normally you would use subtrees to pull in a repo into another repo. You would have a “parent” repo that would create a subtree inside of it which basically pulled in the code of another repo.

Use this command in your terminal to see the subtree commands:

$ git subtree -h

Using subtrees to isolate code

What I tried to do is mock a working development environment with source files, and then move just the built “dist” folder into another repo for isolated use.

Empty parent repo (testing-subtrees-main-repo):

This could be where you have your src files and then where you have your dist folder after it builds. You may then want to pull the dist folder into another repo so certain users/systems only have access to dist files.

Repo:

https://github.com/CariZa/testing-subtrees-main-repo

Created a few empty folders to mimic a complex project structure

$ mkdir dist
$ mkdir src
$ mkdir someotherstuff

Add a mock final index.html in dist:

$ touch dist/index.html
$ echo “Hello World” > dist/index.html;

Push updates to parent repo:

$ git add .
$ git commit -am “Added some test folders and file”
$ git push origin master

Turn dist/ into a subtree on a second repo.

Empty sub repo (testing-subtrees-sub-repo):

Sub Repo:

https://github.com/CariZa/testing-subtrees-sub-repo

Cloned the second repo and navigated to the root of that project and added the main repo’s /dist folder to this repo. The “prefix” is basically the folder you want to pull into your repo.

$ git subtree add –prefix=dist https://github.com/CariZa/testing-subtrees-main-repo master

This pulls down just the “dist” folder from “testing-subtrees-main-repo”, in this case it created a dist folder and put the dist folder inside that folder.

Make a change to the sub repo, commit the change, and push it.

$ vi dist/dist/index.html;

Then commit the change

$ git commit -am “Updated text”

Then push the commited change back to the parent:

$ git subtree push –prefix=dist [email protected]:CariZa/testing-subtrees-main-repo.git master

Go to the main repo and pull latest changes and you should see the same change in the main repo.

You don’t need to do anything fancy in the main repo. You should just need to run the normal “git pull origin master” to get the changes.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.