I've been using a little known feature for some time now and thought it might be worthy of a post for those (like myself) who prefer the Console world of GIT.
Para-phrasing from the Git Documentation:
You are in the middle of a refactoring session, unable to
commitand you need to
checkoutanother branch to code review, reference or something else. You might typically use git-stash to store your changes away temporarily, however, your working tree is in such a state of disarray that you don’t want to risk disturbing any of it. Use a Git Worktree.
I think we can all agree that this is an all too common scenerio?
Worktree's are also extremely useful during Code Review. You don't want to commit your changes, but need to checkout someone elses branch to ensure the work they've done actually works. Or perhaps you need to checkout the code to better understand how it works.
In simple terms, a worktree represents a linked clone of your master worktree. This means its extremely fast to work with and because its generally transient/temporary, you can simply delete it once you're done.
So lets take a look at a typical workflow.
# git worktree add $PATH $BRANCH # Adds a new worktree at 'path' and performs a checkout of 'branch' # path: prs/5.2.0 # branch: release/5.2.0 git worktree add prs/5.2.0 release/5.2.0
Simply `cd` into the directory and hack away. The sub-folder is a complete checkout of the branch you specified and has its own `.git` folder. So any changes you make here are affected only on that branch – leaving your original branch untouched.
cd prs/5.2.0``open .
Push and Prune
If you made changes to your worktree, simply push those changes back up to your origin as usual. Then you can remove the sub-folder and prune your worktree from Git.
git push # optional cd ../.. rm -rf prs # you can remove just the 5.2.0 folder if you have multiple worktree's git worktree prune
Its important to remove your Worktree when done, because Git only allows 1 worktree per branch. If you need to remember where you created your Worktree, you can list them using:
git worktree list
Worktree's are a great tool to have in your bag. Using this approach I found I'm more likely to checkout someone's branch during Code Review to ensure it works.