Back to blog
Article

WorkTrunk: finally a sane way to manage Git worktrees

Why I stopped copying my .env files by hand between Git worktrees, and why I picked WorkTrunk over writing my own Python script.

gitworktrunktooling

In short

I’ve been using Git worktrees since around 2019. I discovered them while contributing to CPython, where a rebuild was all it took to check a fix. The mechanism is excellent.

The problem came from my own projects. Every new worktree started costing me four manual chores: copying .env, creating a dedicated database, reinstalling dependencies, rebuilding a Docker image named after the branch. I nearly wrote a Python script for this. I picked WorkTrunk (wt) instead, which does the job through hooks declared in a TOML file.

What I hadn’t seen coming when installing it: reviewing a contributor’s PR no longer touches my environment at all. That’s become the main reason I keep it.

Everything that follows was written and verified with WorkTrunk 0.80.0, released September 27, 2026.

Table of contents

Context: worktrees, yes, but

I discovered Git worktrees around 2019, while contributing to CPython. A core dev showed me the command. The need was very concrete: test a contributor’s branch, or check a fix, without losing what I had in progress.

Back then, the plumbing was minimal. CPython has neither a database nor an environment file. A new worktree, a ./configure && make, and I could run the test suite. The worktree was self-sufficient, which probably explains why it took me years to see its limit.

I found it brilliant right away, for one precise reason: a worktree is not a clone. I don’t duplicate the Git history, I don’t re-download anything. A single .git repository, several working directories active in parallel, each on its own branch.

The scenario it solves, everyone knows it. I’m deep into a feature, nothing is cleanly committed, and someone taps me on the shoulder for an urgent bug. Without a worktree, I stash and cross my fingers, or commit something half-baked just to switch branches. With one, I have my feature in one folder, the hotfix in another, the PR review in a third.

What changed recently is the frequency. With Claude Code, Codex and the others, running two or three fixes in parallel has become routine for me. Worktrees are what makes that tenable: each agent in its own directory, on its own branch, never touching main or its neighbor. I went from an occasional worktree to three or four open at all times.

Except my projects don’t look like CPython.

The real problem: four chores per branch

Almost all of my projects have a database and an environment file. That’s where the neat mechanism seizes up: git worktree add gives me a clean working directory, and nothing else.

Every new worktree cost me the same sequence:

  1. Copy .env from the main repository, since it’s gitignored and doesn’t follow the branch.
  2. Create a dedicated database, so a feature migration doesn’t break the data of the branch next door.
  3. Recreate the .venv with uv, also gitignored and therefore absent from the new directory.
  4. Rebuild a Docker image named after the branch, as soon as I want a preview that really embeds the code.

None of these steps is difficult. The problem is the repetition, and above all when it lands. I create a worktree precisely when I want to move fast, when someone has just interrupted me. And at that exact moment, the tool asks me for five minutes of plumbing.

A word on the third one: it isn’t handled like the others. Copying a Python .venv doesn’t work, it contains absolute paths that don’t survive a folder change. It has to be rebuilt.

Result: I used worktrees less often than I should have. A tool that costs five minutes ends up not being used in the pressed-for-time situations, i.e. exactly the ones it exists for.

Options considered

Once the problem was laid out, I had four paths.

The first, keep doing it by hand. That’s what I was doing. It works, the unit cost stays low. I ruled it out because that low cost is permanent and always lands at the worst moment. And after paying it enough times, I figured I couldn’t be the only one it annoys.

The second, write my own script. This is the path my reflex pushed me toward. Python that creates the worktree, fetches the files I need, starts a Postgres container, installs dependencies. A hundred lines, I know how to do that.

I’ve been burned before, so I know how it ends: this kind of script never stays at a hundred lines. You have to handle removing the worktree, the orphaned container, port collisions, projects that don’t share the same stack, portability across my machines. I’d have become the maintainer of an internal tool for a problem others had already solved. It wasn’t the cost of writing it that stopped me, it was the cost of ownership.

The third, satococoa/wtp, Worktree Plus. A similar project, written in Go, with post-create hooks and automatic path management. On paper it answered my need.

What made me hesitate was its pace. As I write this, the last commit dates back to March 2026, seven months ago. The repository isn’t archived and has more than 600 stars (checked on October 18, 2026 on the repo’s commit history). I won’t call it dead for that, a tool can very well simply be finished. But I didn’t want to put into my daily workflow a dependency I couldn’t say would still be maintained a year from now. Checking the date of the last commit and the archive status takes ten seconds, and it saves you from unwanted migrations later.

The fourth, WorkTrunk, the one I went with. Ten releases between July 30 and September 27, 2026, more than one a week over that stretch, then three weeks with no release (checked on October 18, 2026 on the releases page). That gap doesn’t worry me, and it mostly shows the limit of the criterion: three weeks of silence don’t say much, six months start to. What I was actually looking at was a repo where fixes land, and that was the case.

The choice: WorkTrunk

WorkTrunk, the wt command, fills the gap I had: working with worktrees as naturally as with branches, and declaring in a config file everything I was doing by hand.

Why it over my own script: it treats the four chores as a single problem, the worktree’s lifecycle. Copying ignored files, starting the database, installing dependencies, building the image, cleaning up on removal, these are all hooks on the same cycle. That’s precisely the part I would have gotten wrong in a homemade script: I would have polished creation and skimped on destruction.

I won’t pretend it’s free. I now depend on a third-party tool for part of my daily work, which is exactly the reproach I made against wtp. WorkTrunk is active today, that guarantees nothing for tomorrow, and if the project stops I’ll have to write the script I precisely avoided. I accept it because my configuration is a readable TOML file, not an opaque binary: what I automate stays reproducible by hand.

I’m also adding a layer between Git and me. It isn’t magic, it drives git worktree underneath, but it’s one more layer to understand the day something breaks. And commit message generation goes through an LLM, which is convenient, not free, and not mandatory at all.

The three commands I use every day

wt switch creates or switches to a worktree, handling naming and the path for me.

$ wt switch --create feature-auth
✓ Created branch feature-auth from main and worktree @ ~/repo.feature-auth

One command, one new directory. The -x flag runs a command right after the switch, handy for chaining into an agent:

$ wt switch -c feature-auth -x claude -- "Implement OAuth2 authentication"

-c creates the branch and the worktree, -x claude launches Claude Code inside it, and whatever follows -- goes in as the initial prompt.

wt list gives the state of all worktrees at a glance.

$ wt list
  Branch        Status    HEAD±   main↕   main…±  Remote⇅  Commit   Age  Message
@ feature-auth  +         ↑1      +27 -8  ↑1      +31      4bc72dc  2h   Add authentication module
^ main                    ^⇡                       ⇡1      0e631ad  1d   Initial commit

The @ marks the current worktree, + uncommitted changes, ↑1 one commit ahead of main. This is what I used to do with a series of cd and git status, in one table. On a repo carrying dozens of worktrees the display stays fast, and the CI status only queries the forge for branches actually pushed, which avoids paying for a request per local branch.

wt merge chains commit, squash, rebase, merge and cleanup.

$ wt merge main
◎ Generating commit message and committing changes...
✓ Committed changes @ a1b2c3d
◎ Merging 1 commit to main (no rebase needed)
✓ Merged to main (1 commit, 2 files, +53)
◎ Removing feature-auth worktree & branch in background

This is the one that surprised me most, in a good way, because it was the step I used to get most wrong: I’d delete the worktree and forget the branch, or the other way around. You can take back control when needed: --no-squash keeps the history, --no-remove keeps the worktree, --no-rebase rewrites nothing, provided main can still fast-forward.

By default, every worktree lands in a folder next to the repository, something like ~/code/myproject.feature-auth. The location is configured with worktree-path in ~/.config/worktrunk/config.toml, with template variables:

# In a hidden subfolder of the repo
worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"

# In a centralized folder, outside the repo
worktree-path = "~/worktrees/{{ repo }}/{{ branch | sanitize }}"

# Organized by remote owner, useful for multi-org setups
worktree-path = "~/development/{{ owner }}/{{ repo }}/{{ branch }}"

The picker, the one I didn’t see coming

I found it while reading wt switch --help, on a line easy to miss. With no argument, wt switch doesn’t fail: it opens an interactive picker, the list of worktrees on the left, a preview panel on the right.

I type to filter, navigate with arrow keys, Enter switches. By default the list only shows my worktrees. Three options widen it: --branches adds local branches with no worktree, --remotes remote branches, --prs open pull requests.

Shortcuts let you act directly from the list: create a worktree from the typed text, delete the selected one, copy a branch name, refresh. To be honest, I use none of them. I type three letters, confirm, that’s all I ask of the picker to create or delete.

The right-hand panel, on the other hand, I can’t do without anymore. Eight tabs, Tab to cycle, Alt-1 through Alt-8 to jump directly: the net diff since the comparison base, uncommitted changes, commits since the base, the log, ahead and behind status against the remote, an LLM-generated branch summary, and for rows with a PR, the PR itself and its comment thread. The tabs visually flag which ones have content, which saves me from opening three empty ones before landing on the one I want.

The comparison base is the merge-base with the default branch. The diff goes through Git’s pager, which is configurable. If you use delta, which replaces the raw git diff display with syntax highlighting, line numbers and a side-by-side mode, it also applies in the preview:

[switch.picker]
pager = "delta --paging=never --width=$COLUMNS"

--prs deserves a closer look, it’s the single most useful thing I found in the lot. The flag adds the repo’s open pull requests, and only the ones not already in the list: a PR whose branch is visible as a worktree or as a local or remote branch doesn’t show up twice. Each row behaves like the pr:<number> shortcut, I select, WorkTrunk fetches the ref and switches.

The filter also covers the number, title and author, so I type three letters of the title rather than hunt for a branch name. Alt-o opens the PR in the browser, the pr and comments tabs load the description and comments in the background, a column shows CI status and review state. It replaces the back-and-forth of “open GitHub, read the PR, copy the branch name, come back to the terminal.”

None of this works without gh installed and authenticated for GitHub, glab for GitLab, or the equivalent CLI for Gitea and Azure DevOps. Without them, the flag has nothing to show.

This is the one place where I see the state of all my branches and the diff of each without changing directory. With several worktrees open, it replaces “wait, which one was this again?” with a glance.

A detail I find well thought out: wt switch -x claude with no branch name opens the picker, then launches the agent in the chosen worktree.

What I actually automate with hooks

This is the part that solved my problem. I cover chores 1, 3 and 4 here; the database gets its own section right after, it’s the longest to configure. The TOML blocks that follow are independent excerpts, not a file to copy as-is: in a real .config/wt.toml, a hook type appears only once and commands of the same type are grouped under the same table.

Hooks are declared in .config/wt.toml, at the repository level, and fire at specific points in the lifecycle: at creation, before a merge, before removal. On first run, WorkTrunk asks for manual approval, so a script coming from a cloned repo doesn’t run behind your back.

A detail that cost me an evening: pre-* hooks block, post-* ones run in the background. A post-start that copies .env may well not have finished when the command passed to -x starts. Anything the next command needs therefore goes into pre-start, which blocks post-start and --execute until it’s done. Everything else, dev servers, big builds, caches, stays in post-start.

It’s a trade-off, not a rule. Putting everything in pre-start guarantees the environment but lengthens every wt switch accordingly. Putting everything in post-start makes the switch instant but guarantees nothing to whoever comes in right after.

Careful if you’re reading older docs or examples: version 0.78 renamed the context variables. worktree becomes worktree_path, repo_root becomes repo_path, main_worktree becomes repo, main_worktree_path becomes primary_worktree_path. Config templates migrate automatically on load, but scripts that read the hook’s JSON, --execute templates and --var overrides need to be updated by hand. The examples below use the new naming.

The .env

wt step copy-ignored copies gitignored files over to the new worktree. By default it takes all of them, which is rarely what I want. A .worktreeinclude at the root restricts the list:

# .worktreeinclude
.env
target/
[pre-start]
copy = "wt step copy-ignored"

This isn’t a continuously shared cache, it’s a reflink copy: disk blocks are shared as long as no file is modified. The documentation reports a 14 GB Rust target/ copied in 20 seconds versus 2 minutes for a cp -R. I don’t have a project that size to check, but on mine the copy is instant.

And I don’t have to trust my gut either, the command reports what it actually did: its summary ends with (reflinked, no extra disk), (full copy), or a partial count. The distinction matters, because reflinking depends on the filesystem. The same line announcing 29.5 GB copied doesn’t mean the same thing depending on whether blocks were shared or bytes were actually written.

Dependencies

For Python projects, the documentation advises against copying .venv, for the absolute-paths story already mentioned, and recommends rerunning uv sync. I agree, uv sync is fast enough that it isn’t worth the trouble of being clever. The hook fits on one line:

[post-start]
deps = "uv sync"

It’s in post-start because nothing I run right after the switch depends on it. If you chain into an agent or a test suite with -x, move it to pre-start.

For mise or direnv, there’s nothing to configure: wt switch does the cd, so they activate on their own. However, since each worktree is a new path on disk, the trust step has to be redone every time (direnv allow or mise trust). WorkTrunk deliberately doesn’t bypass this prompt, same logic as hook approval. It’s a friction that stays on me and I prefer it that way.

The Docker image

I develop almost always inside a container. In dev, the code is mounted as a volume, the image doesn’t move when the code changes, so there’s nothing to do per worktree.

It gets more complicated when I want a preview, or to test what would ship to prod. There I build an image that embeds the source code. If I keep the same tag across branches, I overwrite the previous image. If I keep the same container_name, I can’t run two versions at once, Docker refuses the duplicate.

The answer is the one I detail in the next section for the database: derive the names from the branch’s.

[pre-start]
set-vars = """wt config state vars set \
  app_image='{{ repo }}:{{ branch | sanitize }}' \
  app_container='{{ repo }}-{{ branch | sanitize }}'"""
docker build -t $(wt config state vars get app_image) .
docker run -d --name $(wt config state vars get app_container) \
  $(wt config state vars get app_image)

Two branches, two images, two containers, no collision. The variables are in pre-start rather than post-start, to make sure they exist when I type the build command right after the switch.

What’s left is cleanup, which doesn’t happen on its own:

[pre-remove]
cleanup-app = """docker rm -f "{{ vars.app_container }}" 2>/dev/null || true
docker image rm "{{ vars.app_image }}" 2>/dev/null || true"""

The || true are there because the container or image may already be gone, and a cleanup hook that fails for lack of something to clean up would block worktree removal. Deleting the image is a choice: it’s rebuildable, but if you want to be able to relaunch a preview later, remove the hook’s second line and only clean up the container.

An isolated database per worktree

Chore 2 remained, the one that annoyed me the most. It’s also the most interesting configuration, because it shows that hooks don’t just install dependencies: they isolate a branch’s entire runtime environment, port and database included.

[pre-start]
set-vars = """wt config state vars set \
  container='{{ repo }}-{{ branch | sanitize }}-postgres' \
  port='{{ ("db-" ~ branch) | hash_port }}' \
  db_url='postgres://postgres:dev@localhost:{{ ("db-" ~ branch) | hash_port }}/{{ branch | sanitize_db }}'"""

[post-start]
db = """docker run -d --rm \
  --name {{ vars.container }} \
  -p {{ vars.port }}:5432 \
  -e POSTGRES_DB={{ branch | sanitize_db }} \
  -e POSTGRES_PASSWORD=dev \
  postgres:18"""

[pre-remove]
db-stop = "docker stop {{ vars.container }} 2>/dev/null || true"

pre-start derives a container name, a port and a connection string from the branch name, and stores them as persisted variables. It’s blocking for the same reason as on the Docker side: setting three variables costs nothing and I want them readable as soon as I get control back.

The port is computed by hashing the branch name, with the hash_port filter, range 10000-19999. That guarantees nothing in the strict sense: ten thousand ports for an unlimited number of branches will statistically end up colliding. But it saves me from keeping a list of used ports, and on collision the container simply fails to start, loudly, which I much prefer to two branches unknowingly talking to each other.

post-start then starts Postgres with those variables, and pre-remove stops the container when the worktree disappears.

I left the database startup in the background: launching the container takes a second, but waiting for Postgres to actually accept connections would take several, on every wt switch. The trade-off is that a command launched right after with -x might find the database still cold. If that matters for your project, move this hook to pre-start with an active wait, and accept the delay.

pre-remove is the piece I missed the most when doing everything by hand. I’d create containers, and find three of them still running a week later.

The connection string is accessible outside the hooks too, which is useful for anything that needs to talk to the database:

DATABASE_URL=$(wt config state vars get db_url) alembic upgrade head

This is the command I type most often: apply a branch’s migrations against its own database, without touching the one next door. The same substitution works to launch the app, open a psql session, or plug in any tool that reads DATABASE_URL.

Variant with Docker Compose

If the stack already runs via docker-compose.yml, it’s even simpler. Compose derives its project name, and therefore the prefix for containers, volumes and networks, from the current folder’s name. Since each worktree lives in its own folder, isolation is already achieved without naming anything by hand, unlike the docker run example above.

What’s left is the host port, which does have to vary, since two stacks can’t publish on the same one. The database name could stay identical across worktrees, since each worktree has its own Postgres server, but I vary it anyway: it tells me what I’m connected to when I open a SQL client.

Both values arrive through an environment file the hook generates:

# docker-compose.yml
services:
  db:
    image: postgres:18
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-app}
      POSTGRES_PASSWORD: dev
    ports:
      - "${POSTGRES_PORT:-5432}:5432"
[post-start]
db = """cat > .env.worktree <<EOF
POSTGRES_DB={{ branch | sanitize_db }}
POSTGRES_PORT={{ ("db-" ~ branch) | hash_port }}
EOF
docker compose --env-file .env --env-file .env.worktree up -d db"""

[pre-remove]
db-stop = "docker compose down -v 2>/dev/null || true"

The generated file is called .env.worktree, not .env, and that’s not a detail: wt step copy-ignored just copied my .env with my API keys and local settings, overwriting it would make me lose them on every worktree creation. Compose accepts several --env-file flags and applies the last one on top of the previous, so .env provides the local values and .env.worktree only overrides the port and the database name. If the project has no .env, just keep the second one.

If you’re unsure what’s actually taken into account, docker compose --env-file .env --env-file .env.worktree config shows the final configuration, all variables substituted. That’s how I verified that an API key defined in .env did survive the override.

The default values (:-app, :-5432) keep docker compose up working outside a worktree. The down’s -v removes the volume along with the container, so no ghost database is left lying around. And this generated .env.worktree obviously belongs in .gitignore: it carries a port and a database name specific to a branch, it has no business being in history.

Experience report

The four chores disappeared, and they disappeared in the right place: I no longer think about them when creating a worktree. A side effect I didn’t expect, I now create worktrees for things I would have hacked together with stash before, because the entry cost dropped to a single command.

Cleanup on removal is the real gain, and it wasn’t in my initial requirements. Yet it’s where I was losing the most: orphaned branches, Postgres containers still running, ports occupied for no reason.

Some friction remains. Redoing direnv allow or mise trust per worktree, approving hooks on first run in a repo. These are deliberate security choices, I find them justified, and I haven’t tried to work around them.

One honest note: I haven’t actually tried wtp. I ruled out the option on a maintenance criterion, not on hands-on comparison, and it would be dishonest to present it otherwise.

Reviewing a contributor’s PR

If there’s only one use case to remember, it’s this one. It’s not why I installed the tool, and yet it’s exactly, seven years apart, what worktrees were shown to me for in 2019: looking at someone else’s work without sacrificing your own.

Seriously reviewing a PR means actually running it, not just reading the diff in the browser. That’s precisely what I kept putting off, and the reason wasn’t reading the code. Running a PR on my main repository meant setting aside my work in progress, switching, reinstalling its dependencies, letting its migrations run against my database. Then undoing it all. The cost was in reverting.

wt switch pr:123 removes the whole sequence. A fresh worktree, hooks chaining, .env copied, dedicated Postgres on its port, dependencies installed. I actually test the PR, in a full environment that isn’t mine. Then wt remove: the container stops, the database goes with it, my work in progress hasn’t moved an inch. The contributor’s branch, meanwhile, stays until it’s merged, which is the behavior I want for a PR I’ve only reviewed.

Taken separately, neither is worth the detour: pr: alone is just a shorter gh pr checkout, and the hooks alone automate worktree creation. It’s the combination that makes review non-destructive, and therefore cheap enough that I actually do it.

What I take away from this

The cost of a worktree isn’t in git worktree add, it’s in everything that’s gitignored. .env, dependencies, the database, images: what doesn’t follow the branch is what hurts.

Before writing a script, estimate its cost of ownership rather than its cost to write. A hundred lines to create a worktree is easy. Cleanup, collisions and portability are what cost dearly, and forever.

The removal hook is worth as much as the creation hook. pre-remove is the part people skimp on when rolling their own, and it’s the one that prevents ghost containers and orphaned databases.

And then there’s what I hadn’t planned for. A disposable environment changes your relationship to code review. As long as testing a contributor’s work costs your own database and your work in progress, you put it off. Once it costs nothing, you do it. I hadn’t bought that, I got it as a bonus, and it became the main thing.

Closing, and thanks

WorkTrunk answers a real problem, the one git worktree leaves wide open. Git gives me a clean working directory and stops there; everything that doesn’t follow the branch was left on me, and that’s exactly what made me give up on worktrees when they would have been most useful.

What makes the tool interesting beyond my own case is the choice of declarative hooks. They don’t solve four chores, they solve the category: anything you know how to write in one line of shell becomes a step in a worktree’s lifecycle, triggered at the right time and cleaned up at the end. My examples talk about Postgres and Docker, yours will talk about something else.

Which comes in handy for working with agents, too. What a coding agent needs is exactly what WorkTrunk builds: an environment of its own, complete from the first second, and disposable without a second thought. wt switch -c my-branch -x claude creates the worktree, runs through the hooks, launches the agent inside it. Three agents in parallel, each on its own branch with its own database and port, none stepping on the others’ toes. I didn’t install the tool for that, and it became one of the reasons I keep it.

The project is alive, too, and that weighs in the decision. The pace of releases, the documentation, the care for details like copy-ignored explicitly announcing what it actually did, all of that shows in daily use.

Thanks to Maximilian Roos, max-sixty on GitHub, for WorkTrunk. The repo is at github.com/max-sixty/worktrunk, the documentation at worktrunk.dev. If the tool serves you as well as it did me, a star or feedback on your usage is the least you can do.

Appendix: git worktree vs wt

This table is a reference, not a discovery path. Nobody needs these twenty lines to get started, wt switch and wt merge are enough. It’s here to place what WorkTrunk adds on top of Git, command by command. Several rows have no native equivalent: they cover needs Git doesn’t handle at all.

Task git worktree (native) wt (WorkTrunk)
Create a worktree + branch git worktree add -b feature ../repo.feature wt switch --create feature
Create and run a command inside git worktree add -b feature ../repo.feature && cd ../repo.feature && claude wt switch -c feature -x claude
Switch to an existing worktree cd ../repo.feature wt switch feature
List worktrees git worktree list (raw paths) wt list (status, ahead/behind, CI, messages)
Browse/pick a worktree no equivalent wt switch with no argument (interactive picker with live preview)
Compare a branch without switching to it git diff main...feature (from another worktree) wt step diff --branch feature
Commit git add -A && git commit -m "..." wt step commit (LLM-generated message from the diff)
Merge cleanly (squash + rebase + fast-forward) git checkout main && git merge --squash feature && git commit && git branch -d feature (+ manual cleanup) wt merge
Merge steps one by one no grouped equivalent wt step commit / squash / rebase / push
Remove a worktree git worktree remove ../repo.feature wt remove (+ branch removal if already merged)
Force removal (uncommitted changes) git worktree remove --force wt remove --force
Protect a worktree from removal git worktree lock ../repo.feature --reason "..." git worktree lock directly, WorkTrunk reuses the native command; since 0.78, wt remove and wt merge respect it, even with --force
Clean up orphaned metadata git worktree prune (administrative files only, never branches) wt step prune (worktrees and branches already merged into main, with a minimum-age guard computed since 0.78 from the branch’s reflog, not the commit date)
Copy .env, node_modules/, build caches no equivalent (manual copy) wt step copy-ignored
Run a command across all worktrees manual shell loop wt step for-each -- <command>
Automatic hooks (create, commit, merge, remove) no equivalent (external scripts) .config/wt.toml + wt hook
Pick up a GitHub/GitLab PR/MR as a worktree gh pr checkout then manual git worktree add wt switch pr:123

The table sums up the tool’s philosophy well: git worktree stays the low-level building block WorkTrunk drives, it doesn’t reinvent lock and unlock, it delegates them as-is. The added value is in the commands with no native equivalent, and for my own use, it’s copy-ignored and the hooks that changed everything.