Programming Kraftwerkflows: git-worktree

git-worktree

git-worktree enables us to manage multiple working trees attached to the same repository. Like most (all?) git-* commands, you interact with it via git worktree rather than git-worktree. I came to know git-worktree via a Google search: “working on 2 git branches at the same time”. Thanks Google!

Why use worktree?

I’m glad you asked that. Most codebases are contributed to by a team. That means plenty of pull requests. Pull requests are important even if you’re not on a team, but you’ll inevitably have more of them when a team is involved. Now PRs are great, but often your teammates cannot review your changes immediately. Does that mean you can pack up and go home to drink clamatos preparados? Maybe, but maybe not.

I want to stay productive even when my PR will be sitting there for a couple days. Sometimes the right way to fill that time is with work on another project, sometimes not. Even when you do need to stay hacking on the same project, you can usually simply checkout another branch get your work done there before moving back to the previous branch when your team starts providing feedback. There is another scenario though, and that’s the scenario in which you want to use git-worktree. In this scenario, your team’s feedback starts trickling in while you’re not at a good stopping point in another branch. You want to essentially work on two branches at the same time. Some folks will just cp -r repo repo_2 in this scenario. Those folks might wonder why that’s no good enough. The reasons are profound but quite simple to understand. There are essentially 2:

  1. Copying a large project takes a long time. In a plain cp -r execution, there’s at least two things happening that are unnecessary and take the bulk of that time.
    1. Copying all of node_modules. Using git-worktree in concert w/ a symbolic link can be better here.
    2. Copying all of your git history. git-worktree doesn’t do this.
  2. When you cp -r you’re more likely to end up with the two folders out of sync in a serious way. This isn’t merely anecdotal—git-worktree keep your remotes etc. in sync

How to use it

First, you need to have git 2.5+. Before becoming interested in using git-worktree I was using git 2.2. I simple brew upgrade git gave me git 2.9 and it’s working great! git worktree add ../ignite_002 master will create a new folder named ignite_002 and set it’s head to master, as long as you’re not already on master.

Conclusion

I’m new to git-worktree, but so far I’m finding it a useful workflow upgrade that I’ll apply in a limited set of situations. It represents the biggest improvement to my git workflow in months.
If I’ve piqued your interest, read on:

Cheers and happy Kraftwerking my fellow Gitlians!