Contents
Outline
Git Worktree is a built-in Git feature that lets you create a new directory to work in, unlike regular branches. It sets up a whole separate working environment for you.
This comes in really handy when you need to work on another branch while keeping your current one intact. For example, if an urgent bug fix comes up while you’re in the middle of feature development, or you need to check out another branch for a code review, you can jump right into a separate directory without having to stash or commit anything.
- Official docs: https://git-scm.com/docs/git-worktree
Creating a separate directory with Worktree
You can use the following commands to create a new branch and set up a working environment in a separate directory.
git worktree add -b feature/service/add-test ../new-directory
cd ../new-directory
yarn
code .
Here’s what each command does:
git worktree add -b feature/service/add-test ../worktree: Creates a new branch calledfeature/service/add-testand sets up a worktree in the../new-directorydirectory.cd ../new-directory: Moves into the newly created worktree directory.yarn: Installs the dependency packages.code .: Opens the directory in VS Code.
Using Worktree
In the separate workspace created with Worktree, you can leverage generative AI to write test code and handle other tasks.
Removing a Worktree
Once you’re done, create a PR and merge it first.
Then, follow these steps to remove the Worktree.
- First, check the list of currently registered Worktrees.
# Run this from the original repository directory (not the worktree directory)
git worktree list
- Then remove the Worktree with the following command.
git worktree remove ../new-directory
Completed
That’s it! We’ve covered how to work in parallel across separate directories using Git Worktree. Whenever you need to work on a different branch while keeping your current one untouched, give Worktree a try. It’s especially useful when working alongside generative AI, so if you’re using AI in your workflow, definitely consider taking advantage of it.
Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!
App promotion
Deku.Deku created the applications with Flutter.If you have interested, please try to download them for free.