Git worktree 🌵

Collaboration go brrrrr

Pablo COVES

TupperGit :: 2023-06-29

Context

You’re working on

  • The next killer feature
  • A tricky profiling issue
  • Updating the codebase dependencies

Someone asks you to

  • Troubleshoot their branch
  • Add an important quickfix
  • Make a working demonstration

Solution

Git stash

  • Quick and easy
  • May fail to restore

Git commit

  • Quick and safe
  • Dirty the history

Git clone

  • Clean and safe
  • Unrelated git trees

Git worktree

  • Quick
  • Clean
  • Safe
  • Involved

Take a git repository

└── [drwxr-xr-x]  repository
    ├── [drwxr-xr-x]  .git
    ├── [-rw-r--r--]  file0
    ├── [-rw-r--r--]  file1
    ├── [-rw-r--r--]  file2
    └── [-rw-r--r--]  file3

With multiple branches

❯ git branch
  coworker
  main
* you

Create a new worktree

❯ git worktree add ../coworker coworker
Preparing worktree (checking out 'coworker')
HEAD is now at e39c79c Coworker

Completely separate worktrees

├── [drwxr-xr-x]  coworker
│   ├── [-rw-r--r--]  .git
│   ├── [-rw-r--r--]  file0
│   ├── [-rw-r--r--]  file1
│   ├── [-rw-r--r--]  file2
│   ├── [-rw-r--r--]  file3
│   └── [-rw-r--r--]  file4
└── [drwxr-xr-x]  repository
    ├── [drwxr-xr-x]  .git
    ├── [-rw-r--r--]  file0
    ├── [-rw-r--r--]  file1
    ├── [-rw-r--r--]  file2
    └── [-rw-r--r--]  file3

But common git history

❯ /bin/cat coworker/.git
gitdir: [..]/repository/.git/worktrees/coworker

Allowing one to code

❯ cd coworker
❯ edit file3
❯ git commit -am "Fix typo"
[coworker 1be9375] Fix typo
 1 file changed, 1 insertion(+), 1 deletion(-)
❯ git push

And keep the initial environment clean

❯ cd ../repository
❯ git worktree list
[..]/repository 10b0086 [you]
[..]/coworker   1be9375 [coworker]
❯ git worktree remove ../coworker/
❯ git worktree prune
[drwxr-xr-x]  .
└── [drwxr-xr-x]  repository
    ├── [drwxr-xr-x]  .git
    ├── [-rw-r--r--]  file0
    ├── [-rw-r--r--]  file1
    ├── [-rw-r--r--]  file2
    └── [-rw-r--r--]  file3

Conclusion

See also

Questions ?

https://pcoves.gitlab.io/tupper-git_worktree