r/ProgrammerTIL • u/cdrini • Apr 18 '21
Other Language [git] TIL about git worktrees
This one is a little difficult to explain! TIL about the git worktree command: https://git-scm.com/docs/git-worktree
These commands let you have multiple copies of the same repo checked out. Eg:
cd my-repo
git checkout master
# Check out a specific branch, "master-v5", into ../my-repo-v5
# Note my-repo/ is still on master! And you can make commits/etc
# in there as well.
git worktree add ../my-repo-v5 master-v5
# Go make some change to the master-v5 branch in its own work tree
# independently
cd ../my-repo-v5
npm i # need to npm i (or equivalent) for each worktree
# Make changes, commits, pushes, etc. as per usual
# Remove the worktree once no longer needed
cd ../my-repo
git worktree remove my-repo-v5Thoughts on usefulness:
Sooo.... is this something that should replace branches? Seems like a strong no for me. It creates a copy of the repo; for larger repos you might not be able to do this at all. But, for longer lived branches, like major version updates or big feature changes, having everything stick around independently seems really useful. And unlike doing another git clone, worktrees share .git dirs (ie git history), which makes them faster and use less space.
Another caveat is that things like node_modules, git submodules, venvs, etc will have to be re-installed for each worktree (or shared somehow). This is preferable because it creates isolated environments, but slower.
Overall, I'm not sure; I'm debating using ~3 worktrees for some of my current repos; one for my main development; one for reviewing; and one or two for any large feature branches or version updates.
Does anyone use worktrees? How do you use them?
- Docs: https://git-scm.com/docs/git-worktree
- Cool YouTube video where I learned about worktrees: https://www.youtube.com/watch?v=2uEqYw-N8uE
View all comments
Show parent comment
2
u/18randomcharacters Apr 20 '21
without getting into the details of different release management practices....
the point is, I have a work in progress that's TONS of changes. Not committed yet.
Now something comes up that I want to fix really quick, and I don't want it tied to my huge WIP branch. I want to just fix it and push a fix. Without worktree, I have to stash my changes, change branches (to master probably), new branch, do the fix, commit, push branch, change back to my WIP branch, unstash changes.
With worktree, I just create a new worktree for a new branch, and go do the changes there, and I never have to stash/unstash my WIP changes.