Imagine you are working on a project at work, you’ve got a bunch of code written out but nothing ready to commit yet. You get an urgent ping from your boss and there is a bug that needs to be fixed immediately. You spring into action by stashing your work, creating a new branch, and fixing the bug in no time flat. You’re a hero.
This situation is quite common, and stashing can get the job done in a pinch, but if you have even more requests for different work it can get really hard to manage what code is stashed. The solution for this is Git Worktrees, which is a native but seemingly unknown feature in git.
I got into the habit of creating a new worktree for every ticket I got at work, so that everything was kept separate and clean. Through this practice, I had a number of pain points such as having 35 worktrees in my worktree folder, most of which have already had the PR merged. It was hard to clean it out, because I had to try to remember which ones I had completed.
So, I created a CLI written in Golang to solve these problems for me called Treekanga. This tool allows for easy management of git worktrees.
Treekanga Tutorial
Instead of just regurgitating the documentation, let’s walk through a use-case together.
Firstly you can install Treekanga using brew:
brew install garrettkrohn/treekanga/treekanga
After installing, we need to create a config file in
.config/treekanga/treekanga.yml
. Let’s start with the following for a config
file:
repos:
testRepo:
defaultBranch: development
zoxideFolders:
- backend
- frontend
- We added the repo we will be using (this must match the repo name from github)
- The default branch will be used to create any new branches
- Treekanga works with Zoxide to add a specific folder structure. So in this case it will add ~/…/testRepo/backend and ~/…/testRepo/backend to Zoxide
next we’ll setup a bare repo. My preferred folder structure is to
have a parent folder for the repo, then the bare repo & worktrees in that
folder. So we’ll make our parent folder:
mkdir testRepo && cd testRepo
Next we can clone in the bare repo with the following command:
treekanga clone https://github.com/example/test
Next we will add our first worktree on a new feature that we’re working on with
this command:
treekanga add new_feature_name -p
- The p flag will pull the latest from the development branch (defined in the config file)
- It will then create a new branch and a worktree with the same name
Let’s imagine we repeat this a dozen times over the next week. At the end of
the week we realize that we have completed a number of PRs and we want to clean
out all the stale worktrees that we no longer need.
treekanga clean
- This will bring up a multi selector list that will only display worktrees where the remote branch no longer exists. We can select as many as we would like to delete and hit enter.
Thank you for reading through this tutorial, I hope you will give Treekanga a try!