Imagine working on a new feature on a branch and this feature is going to scoop too much time for completion. While working on the new feature, the tools, IDE, etc, unexpectedly a critical issue comes up in the production code where a quick patch is needed. Back to master and then to a new patch branch might result in shutting the application down, turning the tools off, probably closing the workspace in the IDE and stashing the uncommitted changes. This method of switching will be costly when repeated frequently. Instead of stashing or committing a code, one can create sub branches without interrupting the work.
What is worktree?
Worktree handles multiple working trees attached to the same repository. A git repository can support multiple working trees, allowing you to check out more than one branch at a time, eventually saves a lot of time.
Use of Worktree?
For example, When I’m working on a branch called feature and some high-urgency bug in master is reported or build needed from current production branch for testing, I usually stash away whatever I’m working on and create a new branch. When I’m done, I can continue working. This is a very simple model, I’ve been working like that for years.
But now Instead of stashing or committing the code with the help of work tree we can create multiple sub branches and switch between branches without interrupting our work on the new feature.
How to create Worktree?
The following are some simple and quick commands to get you started:
Create a new working tree at <path> and checkout <branch> in the new working tree:
git worktree add <path> <branch>
Using “git worktree add” a new working tree is added with the repository. The resultant Worktree is called a linked working tree and the source Worktree is called main working tree prepared by git init or git clone.
A repository contains one main working tree and either none or more linked working trees. To remove a linked working tree use “git worktree remove”.
Prune working trees after deleting their files with:
git Worktree prune
Now that a new and a better solution to all the stashing and committing issues has been found, all one has to do is make use of the Worktree and save a lump of time.