Situation: You need to work on multiple tickets but don’t want to duplicate a repository on your computer.
A common situation is that you are either working on task and need to switch to work on another branch or complete another task. Git stashes or just switching branch is possible but sometimes you just want to open another IDE and work in parallel. But you have a problem, you have a slow connection, or large repository and or lack in local storage. What to do?
Say hello to Git Worktree.
Worktree exposes a feature of git where it allows to checkout multiple branches at the same time while maintaining just a single copy of the repository on your local storage.
Add new worktree command:
git worktree add ../workspaceOne
What does command do
While inside your repository for example /Users/MyUserName/Developer/AwesomeProject
and having main
branch checked out.
This will create new folder. /Users/MyUserName/Developer/workSpaceOne
.
Your existing /Users/MyUserName/Developer/AwesomeProject
folder remained unchanged.
In effect you have now two copies of your repository. You can give any name to this folder you like.
From here you can run below to checkout a new branch on your new worktree.
cd ../workspaceOne
git checkout branchYouWantToWorkOn
Benefits
- Stashes are now shared. This means you can open multiple Xcode’s (other your preferred IDE) and you will be able to have all stashes visible to both. One major difference between having two clones of same repository is where stashes are not shared.
- You can have
main branch
available in the original place/Users/MyUserName/Developer/AwesomeProject
. This means that to update your multiple worktree branches/folders you just need to do singlegit pull
and then performgit merge main
without jumping between branches but just local folders. - Save space on your laptop. Due to only having a single cloned of repository you save a lot of space, some repositories go into ten’s gigabytes.
Extras
Remove worktree command:
git worktree list
git worktree remove ../workSpaceOne
What does command do
list
command will print out a list of folders and branches that are current checked out via worktree.
remove
command will remove the worktree reference and delete the folder. Keep in mind your worktree must be clean and there shouldn't be an uncommitted code.
Also you stashes will remain as they are located in the root of your git repository.