Git worktree it a git feature which allows you to checkout a single repository into multiple locations on your filesystem. It has a few rough edges, but if you follow a few simple rules it can be make context switching much easier than git's other mechanisms, such as stashing or switching branches. My folder structure will usually look something like this:
MyRepo/
master/
← The original checkout, using something like git clone <repo url> master
feature_branch_1/
← A feature branch
hotfix_branch_1/
← A quick hotfix I need to make
- Create the top-level folder:
mkdir MyRepo
- Checkout the repository's master branch as a normal checkout:
cd MyRepo; git clone <repo url> master
- Add a branch:
cd master; git worktree add -b <branch_name> ../<folder_name> HEAD
branch_name
andfolder_name
should likely be the same to avoid confusion (in larger projects, I would prependbranch_name
with my username)
- Switch to that branch:
cd ../my_branch
- When you need to create a new branch, make sure to create it from the branch you want to base it on (often, this is
master
)
git worktree remove <path_to_worktree>
from a directory containing your worktree- (Optional) Delete the local branch with
git branch -D branch_name
- (Optional) Delete the remote branch with
git push <remote> :<branch_name>
- In a worktree, the
.git
folder is just a file, so scripts modifying repo settings like git hooks may fail. The git hooks in the original repository apply to its worktrees. - You can actually checkout a worktree inside of the repository by leaving out the
../
before folder name. This is not recommended. - You can not have the same branch checked out in multiple worktrees
This would work the same way that it would without worktrees, you would need to specify the remote manually when pushing.