We have been using ‘Git’ as it was easy to handle everything from small to large projects with speed and efficiency. Also it was the widely used version control system with flexibility in place. It was easy to learn and moreover all, the lightning fast performance tends to make us of it.
We have always had a sort of trouble whenever we work on a “branch X” and the other “branch Y” needs change. In this case we would usually stash the changes that we made and switch over the branch and work on it and come back and apply stash but this looked some kind of extra work though it is not.
But since Git 2.5 has introduced a new command “worktree”, the above said work can be reduced.
A new worktree command allows you to maintain multiple checked out work trees of the same root repository. It’s fantastic.
Before this command existed one had a few ways to switch context and work on different streams at the same time:
• Stash the current uncommitted changes and checkout a different branch (using git stash).
• Create work-in-progress (i.e. WIP) commits in the current branch to save ones work and switch branch.
• Create a separate full clone of the repository to keep two ongoing development efforts separate and parallel.
• Set the GIT_WORK_TREE or GIT_DIR environment variables, as explained here.
With worktree one can create a sub-folder of the root project with a specific checked out branch – or ref for that matter – and keep working on it until done. The command saves you from having to create separate – out of band – clones.
So imagine you’re happily working on the develop branch but you are tasked to work for a few days on the rewrite branch that has massive changes. You can create a worktree for this extended work and leave your other ongoing effort where it is. The syntax of the command is:
git worktree add [-f] [–detach] [-b <new-branch>] <path> [<branch>]
So in our example the command would become:
git worktree add rewrite-folder rewrite
The command creates a sub-folder in the root of your project named – surprise – rewrite-folder which contains the checked out branch rewrite.
We can push and pull from that sub-folder as if we are at the root of our Git project and when we are done with that work we can simply delete the folder rewrite-folder. The administrative files stored in .git/worktrees will be eventually pruned, but if you want to be thorough you can easily prune that data with:
git worktree prune [-n] [-v] [–expire <expire>]
Hope the above information will be useful until next time.