Saving Time With Multiple Working Trees in Git

Ronald Klazar
Statuscode
Published in
2 min readFeb 21, 2018
Jacaranda Trees in Spring — Olivier Street, Pretoria, South Africa

A working tree is a set of files for a branch that is linked to the repository. A repository consists of a main working tree and zero or more linked working trees. The files in a linked working tree are stored in a different directory to that of the main working tree. The essential use of having multiple working trees is to obviate the need to switch between branches within the same working tree.

For example, let’s say that your application’s repository has a branch called master, which contains the production version of your source code. Whenever you want to produce a patch, you create a new branch from master, implement the patch, get it tested, and then eventually merge the patch branch back into master.

However, let’s say that you’re working on a great new feature on a branch called moneyMaker and that this feature will take a long time to complete. While you’re working on the new feature, you have all your tools, IDE, and perhaps even your application up and running off the source in moneyMaker. Suddenly, a critical issue in the production code comes up and you need to produce a quick patch. Switching back to master and then to a new patch branch might imply shutting down your application, turning off the tools, possibly closing the workspace in your IDE, and stashing your uncommitted changes in moneyMaker. This kind of switching becomes costly when one has to repeat it frequently.

Instead, create a new working tree for the master branch. Now you’ll have the original, main working tree for moneyMaker and a separate working tree wherein you can create branches and switch between branches without interrupting your work on the new feature.

Since working trees are linked to the repository’s admin files, anything that you do in a working tree is recorded in your repository’s history. For instance, one can create a branch in one working tree and check it out in another working tree. Git prevents one from checking out the same branch in multiple working trees so one needn’t worry about mangling a branch. And when you’re done using a linked working tree, all you need to do is to delete the files and then prune the tree (or have git do the pruning for you).

The following are some quick commands to get you started:

Create a new working tree at <path> and checkout <branch> in the new working tree:

git worktree add <path> <branch>

Prune working trees after deleting their files with:

git worktree prune

The Git Documentation provides a complete reference and includes some variations you may find useful.

--

--

Ronald Klazar
Statuscode

Computational Intelligence Researcher; Web developer