DEV Community

Kenichiro Nakamura
Kenichiro Nakamura

Posted on

Git worktree? What, Why and When

I recently started using git worktree to see if it solves my pain-point and it does in some scenario. As it takes too long to explain how it works in blog, I just share scenario and you can learn what it is in YouTube videos if you want.

pain point?

While I work on new feature in my branch, I often need to checkout another branch for code review of a pull request.

If I try to checkout to the PR branch, I may fail if I have working file(s).

error: Your local changes to the following files would be overwritten by checkout:
        test.txt
Please commit your changes or stash them before you switch branches.
Aborting
Enter fullscreen mode Exit fullscreen mode

Then, I need to git stash to move my working files into stash stack or, git add/commit to clean my branch.

Why this happens?

This is because git uses same working directory for all branches. This infers if we use separate working directory for branches, we won't encounter file conflict issue.

That's what we often do. We often clone to another directory for PR and keep original directory for our work. But we have to clean it by ourselves, and we need to clearly remember which folder contains which branch changes.

Worktree

In this situation, git worktree does this for us. It creates directory for each branch, but it still works exactly same for git workflows. As it adds additional folders and objects, there are many best practices, as we may not expect others do the same, so we need to fully understand how worktree works. There are many useful videos in YouTube which explains very detail.

References

git worktree doc
Tech Tuesday - Git Worktrees
How to Use Git Worktree | Checkout Multiple Git Branches at Once

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay