What it is
A worktree is a directory that is linked to a specific branch, this branch can be
changed through git checkout
or git switch
. You can’t change to
a branch that is already linked to a worktree, in this case you have
to change directory.
Why I use it
Worktrees are extremely useful when you work with different branches at the same
time. The main strength is the possibility to jump from one branch to another,
without the need to stash
or commit
the pending
changes. This avoids the creation of temporary1 commits, that in most cases
will remain in the commit history.
How many times have you had to resolve an urgent bug in production while you were developing something now? It can happen, in this case you stash or commit all your unstaged code, switch to your main branch, fix the bug, commit it and then return to the previous branch and retrieve all your stashed code. This procedure can be tedious and time-consuming operation.
With worktree you can handle this case more easily. Each time you have to abandon what you are doing and make some implementation to another branch, all you have to do is change the directory. Make all the changes you have to do and then return to your working branch, previous directory. And you will find all your unstaged changes still there.
How I use it
Create worktree
To create a worktree run:
git worktree add <pat_to_directory> <branch_name>
Where <path_to_directory>
will be the new location of the worktree and
<branch_name>
is the initial branch of the worktree.
I found it useful to put all my worktrees, including the main branch, in a directory named forest. Usually I use a custom script that creates the worktree in the forest directory and copies from the main branch all the env/secrets files, to the newly created worktree directory.
Hop between worktrees
To hop from one worktree to another, quicker than cd /path/to/worktree/
into it, I wrote this useful alias
cd $FDIR/$(ls $FDIR | fzf --height "25%" --header "Choose the workingtree" --reverse --border)
Where the $FDIR
contains the path to the forest directory.
With the use of fzf
we can list all the worktrees, and with a few characters, you can identify the
directory and change location.
Remove a worktree
Usually, before doing the removal I list all worktrees, git worktree list
, and then I proceed
with the removal, git worktree remove
. This operation simply deletes the worktree directory.
Note: you could delete the worktree directory with the rm
command, but by doing this
you could leave something pending. In this case, you can remove all pending things by
executing git worktree prune
.
-
“There is nothing more permanent than a temporary solution” ↩︎
Git