Git worktree? What, Why and When

kenakamu

Kenichiro Nakamura

Posted on October 10, 2022

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

πŸ’– πŸ’ͺ πŸ™… 🚩
kenakamu
Kenichiro Nakamura

Posted on October 10, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related