DEV Community

Camille Briand
Camille Briand

Posted on

You should try git worktrees

What is it?

git worktree is a git command enabling to create copies of the repository to work on several branches at the same time without having to constantly use git stash for context switching.

Why is it cool?

It is cool because it happens quite often that you are working on your branch when something urgent comes up. In that case what you usually do is stash your changes or commit as is with a commit message like "WIP login form (TO SQUASH)" (and let's be honnest, that commit won't be squashed). Then you checkout on the branch the urgent work needs to be done, you start to do the work and something even more urgent comes up. Here we go again: git stash, git checkout hotfix/even-more-urgent-stuff, ... I think you got the point, we all have repos where git stash list is scaringly huge and more often than not you don't put messages on each stash to remember exactly what it you were doing and why.

With git worktrees, you will have copies of your repo tracking each branch, allowing you to simply cd into the copy you want to do the required changes. When you have to move on to more urgent stuff, that means you don't necessarily have to commit right now nor have to stash your changes anymore: you just cd into the workspace you created for tracking that other branch.

The drawbacks

There is only a single drawback that comes to my mind: many IDEs do not integrate well with having several copies of a repo opened at the same time, hence the need for closing and reopening projects that are - in fact - the same project but in another directory.
Where I see this feature of git actually speeding up my workflow without overcomplicating it is when I work mainly from the terminal, with IDEs like Vim or just opening my IDE from the right directory/workspace and closing it when I need to move on to another branch. This second option can take a lot more time, especially in IDEs where the launch is slow (looking at you IntelliJ).

Disclaimer

I don't actually have had the time to explore that feature extensively so if that article interested you, I highly encourage you to look for more articles explaining how this feature works with actual commands.
If I use it more in my day-to-day work, I will write a follow-up article explaining more precisely how I use it, what are the commands and the eventual shortcuts I use.

More links to look at

Documentation for the git worktree command: https://git-scm.com/docs/git-worktree

ThePrimeagean on Youtube has a great video displaying his use of git worktree: https://youtu.be/2uEqYw-N8uE

Using git worktree with GitKraken: https://www.gitkraken.com/learn/git/git-worktree

Top comments (0)