DEV Community

Cover image for Git Worktree
Kumar Nitesh
Kumar Nitesh

Posted on

Git Worktree

I am not sure why I had no idea about this gem. I have been using Git for almost 10 year and discovered this just few days back and from that time it has become an essential part of my workflow.

Scenario: Deep down working on a feature branch for an app, suddenly a big issue was found in production for which you have to find a solution and deploy hotfix

Here was my workflow:

Workflow 1

  • Commit all my work in my feature branch, even when I know it's not even half done and obviously will not compile.
  • Checkout master -> create hotfix branch --> make changes and deploy
  • Checkout my feature branch, undo last commit, and start working again.

Workflow 2

  • Stash changes to feature branch. Most of the time I will forget to stash untracked files, so stash again with a message "this also needs to be unstashed-- "
  • Checkout master -> create hotfix branch --> make changes and deploy
  • Checkout feature branch, pop up last stash and second last stash, continue working

The problem with above workflow was, if I move to work on something else, and come back after considerable time, I will not remember where I left, and god forbid If I have more stash changes and my stash message are not even understandable by me after a week.

How Git Worktree helped me out.

Now whenever I have to work on a feature, I add a new worktree. In case I have to go and work in another branch, I just change worktree folder and start working on that branch. I don't have to commit half or not working code or have to stash them (with appropriate message) anymore. I can just switch folder and start working in a new branch.

How to add a worktree

git worktree add -b "feature/your-branch-name"

Full list of commands for worktree

git worktree add [-f] [--detach] [--checkout] [--lock [--reason <string>]] [-b <new-branch>] <path> [<commit-ish>]
git worktree list [-v | --porcelain]
git worktree lock [--reason <string>] <worktree>
git worktree move <worktree> <new-path>
git worktree prune [-n] [-v] [--expire <expire>]
git worktree remove [-f] <worktree>
git worktree repair [<path>…​]
git worktree unlock <worktree>
Enter fullscreen mode Exit fullscreen mode

Read more here
Let me know how you use worktree.

Thanks
Kumar Nitesh

Latest comments (1)

Collapse
 
namkata profile image
NamKata

Good. Depending on the usage of each individual and the company, the working flow of the team. Thanks for your sharing