Member-only story

git subtree: How to extract some file paths into a separate into a separate branch in git

Bryant Jimin Son
3 min readNov 21, 2023

--

Let’s say you have a git directory just having one master or main branch. Or, you have a certain directory or a file path that you want to be separated into a separate branch.

When would this happen? I’ve observed that a customer was trying to migrate form Team Foundation Server (TFS) where they could clone using git tfs command but end up aggregating clone everything as one branch — master. There are few options in git tfs where you can convert TFS “branches” there to git branches, but there were some limitations there. Easiest option was to convert everything, even branches, as folders, but you may still want to separate those folders into separate branches when you push to git platform like GitHub. What do you do?

Enter git subtree . This command will help to split certain folder/file path into own branch.

I created a very simple git directory like this using git init command. Yours might be more complicated.

My git directory

Ad you can see there are two folders SRC and IMAGES, and there are some files in root and folders underneath. Now, let’s assume that we want to take out that SRC directory into another branch. Here is my current git log look like.

git log

As you can see, I only have one git branch by typing git branch -a . But it really should not matter as you can split from any branch even if there are multiple branches.

I only have one git branch

Here is a command that I am going to execute using git subtree :

git subtree split --prefix=SRC -b branch-source

What I am doing is that I am taking that SRC directory and create a new branch called branch-source.

After git subtree

And that still preserves master branch. But when I checkout to new branch-source , you will notice that files there now just has contents from SRC.

Checking out to branch-source will show files underneath SRC

That is it! At this point, if your git directory is now linked to git platform like, you can do something like git remote add origin GIT_URL command, checkout wanted branch and push to git repository.

--

--

Bryant Jimin Son
Bryant Jimin Son

Written by Bryant Jimin Son

A cloud practitioner talking about technology, travels & career tips. But I will sometimes cover financial advises and some random stuffs.

No responses yet

Write a response