Git Subtree

Splitting a Subfolder out into Its Own Repository with Git Subtree

I have secretly been working on a project for a number of months now. It got a point where I decided it will be best to split some folders in the project out into their own Git repositories. Previously, the project was a large monolithic application.

I didn’t want to just split them out on a blank slate but have their Git histories maintained. After some research, I finally settled for Git subtree, one out of the many Git contributed software.

In this post, I will show us some ways we could use to split out a folder into its own repository using Git subtree.

Using my jquery-modal fork for demonstration, we’ll be splitting the examples folder into its own Git repository.

I assume you have the repo cloned to your machine already and you’ve cd into the jquery-modal folder, otherwise do that now via:

git clone https://github.com/collizo4sky/jquery-modal
cd jquery-modal

Note, all git subtree command must be run from the top-level of your working tree which is path/to/jquery-modal in our example.

Method 1

To split out the folder and immediately push to its own repository at https://github.com/collizo4sky/jquery-modal-examples, use git subtree push command as shown below

git subtree push --prefix examples https://github.com/collizo4sky/jquery-modal-examples master

where:

* --prefix or -P option (also known as a flag or switch) specify the name of the sub-directory or sub-folder to split out and

* https://github.com/collizo4sky/jquery-modal-examples is the Git repo the split sub directory will be pushed to.

* master the branch to push to.

Method 2

If you feel there is a lot of magic being done in method 1 or you would love to have more control of the splitting and pushing to the git repo, here you go.

The command below will split out the subfolder and output a SHA-1 hash of the split commit.

git subtree split --prefix examples

Push the commit to the git repository that will store the split.

git push https://github.com/collizo4sky/jquery-modal-examples e243c380a434bf5:refs/heads/master

Method 3

If you will like to make some changes before pushing the split into its own git repo, you will have to:

– split the subfolder.

git subtree split --prefix examples

– checkout the split to a new branch called modif, assuming the split commit hash is e243c380a434bf54af384ef6c7bca2623710f2c5

git checkout -b modif e243c380a434bf5

– make the change & push to its git repository.

git push -u https://github.com/collizo4sky/jquery-modal-examples master

You can simplify the splitting and checkout to a new branch with the command below.

git subtree split --prefix examples --branch modif

La Fin.

Don't miss out!
Subscribe To Newsletter

Receive the best WordPress, Git, Web development and programming tutorials.

Invalid email address
Give it a try. You can unsubscribe at any time.