This content originally appeared on DEV Community and was authored by Kumar Nitesh
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>
Read more here
Let me know how you use worktree.
Thanks
Kumar Nitesh
This content originally appeared on DEV Community and was authored by Kumar Nitesh

Kumar Nitesh | Sciencx (2022-04-09T04:41:55+00:00) Git Worktree. Retrieved from https://www.scien.cx/2022/04/09/git-worktree/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.