How to Quickly Compare Two Builds with Worktrees

Written by: on September 2, 2016

One of the best parts of software development is that things are constantly changing. However, this can also lead to some challenges in development. Let’s say you’ve recently built an animation and after design reviews it, you find out your fancy animation is close, but not quite right. You are assigned a ticket to adjust your animation and bring it in line with specifications. You start by making your bugfix branch and begin coding. After fine-tuning the animation, you have a really hard time seeing the difference.

You could checkout the develop branch and run again to compare, but that changes things externally from the IDE which will then reindex and recompile your code wasting minutes of your valuable time.


Source: xkcd:

This is where git worktrees come in handy. You can think of a worktree as a separate window looking into a separate branch of your git repository. This is subtly different from a separate clone of a repository. With a clone, you have two repositories. Making a commit on one requires pushing changes to another to see them and to be able to run a diff between those changes. A worktree is the same repository. Make a commit on one worktree and you can immediately diff that commit on the other worktree.

To create a worktree you simply call git worktree ../project-develop develop. This creates a directory named “project-develop” pointed at the develop branch. From there, open your favorite IDE to that new directory as a separate window and start the lengthy compile process.

Once finished you can deploy your development build and start testing. Then switch back to the other open window of your IDE and deploy the build of your feature branch. You’ll notice that it didn’t have to recompile since you never had to switch branches. From here you can compare the animations quickly.

However, worktrees do require a little bit of cleanup. You can’t checkout a branch in your main directory that is already checked out in a worktree directory. In this situation simply delete the worktree directory and tell git that it has to check for deleted worktrees. Use the commands: rm -r ../project-develop and git worktree prune. After calling worktree prune, git should understand that the worktree no longer exists and once again you can checkout your development branch inside of your main repo directory.

Eric Young

Eric Young

Eric is a developer at POSSIBLE Mobile. Eric develops Android apps by day, hacks on Rust programs by night, and constantly tries to find ways to make his code more maintainable.

Add your voice to the discussion: