DEV Community

Chris L
Chris L

Posted on • Updated on

Switch context faster with git worktree

Working with git has made lives of many developers in the world a lot easier but it also brought some quirks, especially for those who work in fast paced environments. Having multiple branches and working on many things at once is a normal thing nowadays.

So, what do you do when you're working on a feature, you're deep down the rabbit hole, and suddenly, you have to switch and work on something else like a hotfix?

For me, personally, it meant that I'd stash my changes, fetch master, create a new branch and restart my editor to not have cluster of opened files. That also meant that when I finished working on the hotfix and when I got back to the original feature my reaction was somewhat like this:

confused

Let's introduce git worktree.

A git repository can support multiple working trees, allowing you to check out more than one branch at a time
https://git-scm.com/docs/git-worktree

But what does it mean?

Using worktree you can easily create a local copy of your desired branch outside your main repo, work on it like you'd normally would, without having to stash anything!

Enough talk, show me the code!

In your main repo dir do

git worktree add -b super_important_hotfix ../super_important_hotfix origin/master
Enter fullscreen mode Exit fullscreen mode

This will create a new directory with an exact copy of your repository (at origin/master) and switch to a new branch called super_important_hotfix.

You can now work on your super important hotfix without polluting the main dir.

touch super_important_hotfix.txt
git add super_important_hotfix.txt
git commit -m 'Fixed bug'
git push
Enter fullscreen mode Exit fullscreen mode

Go back to your main repo dir and eveything is exactly the same you left it!

tada

Once you're done with you hotfix you can remove the dir we created for it and run git worktree prune from the original directory to cleanup references to it.

You can have a more in depth look at git worktree here

Happy coding!

Love Ruby, new tech, and working remotely? Check out https://leadfeeder.com/jobs and don't forget to mention my name!

Top comments (1)

Collapse
 
epsi profile image
E.R. Nurwijayadi

Yes. Very useful worktree. I use it for SSG.

epsi-rns.gitlab.io/devops/2020/02/...

Compare Head for Each Branch