Tom’s Meandering Mind

Poignant articles on webdev & start-ups, pointless bytes, and pure lunacy. 
« Back to blog

Git Tip: Spin Off a Directory Into a New Branch the "Right Way"

One root directory in our git repository accounts for about 99.999% of files in the project. Tired of checking out 13,000 files each time I needed to switch between branches, I decided it was time to cut the ties that bind and send this directory tree off into the world (as a new branch). Thankfully, there is a simple and clean way to accomplish this task.

git-subtree to the Rescue

git subtree is a very handy project and is described (concisely) thusly:

An experimental alternative to the git submodule command.

It can (appropriately) be acquired from github. From here, things are pretty easy. The following assumes you have a folder media inside your repo which you would like to spin off into a branch (creatively) named media:

$ cd /var/repos/my-cool-thing
$ git subtree --prefix=media --branch=media
$ git push origin media:media

Now, just wait. In my case, wait a couple hours. See, wasn't that easy? Actually, I feel silly telling you all this. I'm sure you would have investigated the matter yourself. To which you reply,

Fuckin'-A. I don't need no smart branch-makin' developer to show me where the bear shit in the buckwheat!

Now that I've ruined a quote from a timeless motion picture, let's move on! There are two really handy advantages to using this method, rather than something even simpler or built-in:
  1. Only the commit history for the relevant files is retained
  2. Unlike the git submodule command, git subtree doesn't produce any special constructions (like .gitmodule files or gitlinks) in your repository
git subtree has many other uses outside of this basic case, though, and I encourage you to explore them. For instance, when the command completes, it will spit out a commit hash to stdout which corresponds to the current HEAD of your new tree; you can do whatever you want with it – go wild! Rather than just using the branch, I could have spun it into its own repository and linked it back to the main one, for instance. Read the manpage for more.

Until next time, cats and kittens!

Comments (0)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    twitter