worktrunk icon indicating copy to clipboard operation
worktrunk copied to clipboard

sdkman emits "Could not find .sdkmanrc" when removing the current worktree

Open donvince opened this issue 6 months ago • 9 comments

Summary

Running wt remove from inside the worktree being removed causes sdkman to emit:

Could not find .sdkmanrc

and fail to deactivate the previous worktree's SDK correctly.

Root cause

execute_instant_removal_or_fallback immediately renames the worktree directory (to a staging path) during the binary's execution — before the binary exits and before the shell sources the directive file.

Sequence:

  1. Binary runs → renames worktree dir (.sdkmanrc now gone at old path)
  2. Binary exits
  3. Shell sources directive file → executes cd /main/path
  4. sdkman's chpwd hook fires → looks for .sdkmanrc at the previous (removed) worktree path → not found

The cd directive is written correctly, but the directory is already gone when sdkman checks it.

Expected behaviour

sdkman finds .sdkmanrc at the previous worktree path when its hook fires, deactivates the old SDK cleanly, then loads the SDK from the main worktree's .sdkmanrc.

Proposed fix

When changed_directory=true (user is inside the removed worktree), skip execute_instant_removal_or_fallback and instead write the removal as a backgrounded shell command into the directive file:

( git -C '/main/path' worktree remove '/worktree/path' && git -C '/main/path' branch -d 'branch-name' ) &

This ensures the sequence becomes:

  1. Binary exits
  2. Shell sources directive file: a. cd '/main/path' → sdkman fires while .sdkmanrc still exists at the old path ✅ b. ( git worktree remove ... ) & → deletion runs in background after cd

The changed_directory=false path (removing a different worktree) is unaffected.

Environment

  • wt 0.50.0
  • macOS
  • sdkman with a .sdkmanrc in the worktree being removed

donvince avatar May 14 '26 23:05 donvince

Thanks for reporting this. The analysis matches the code on main at 8fba3f8:

So by the time the shell wrapper sources the directive and chpwd fires, sdkman walks into the placeholder and the .sdkmanrc is gone.

One trade-off a maintainer will need to weigh: the synchronous rename + branch -D was specifically added to avoid a race where the user creates a new worktree with the same branch name before the background rm -rf completes (handlers.rs:130-138). Deferring the rename to the background command — as the proposed fix would — re-opens that window. The longer design space (Option A: fully deferred cleanup with a pending marker; Option B: sync rename + rm -rf placeholder) is captured in build_remove_command_staged; the sdkman/chpwd constraint is a new input that wasn't in scope when those were last evaluated.

A maintainer will take a closer look.

worktrunk-bot avatar May 14 '26 23:05 worktrunk-bot

what would git worktree remove show?

max-sixty avatar May 15 '26 00:05 max-sixty

I ran git worktree remove in both relevant scenarios on git 2.x.

From inside the worktree being removed (cd /worktree && git worktree remove .): exit 0, no stdout/stderr output, the directory is deleted synchronously, and the shell's PWD is invalidated (getcwd fails until the next cd).

From the main worktree, matching the proposed fix's git -C '/main' worktree remove '/worktree': exit 0, silent on a clean worktree. With any untracked file present — including .sdkmanrc itself when not tracked — it fails: fatal: '<path>' contains modified or untracked files, use --force to delete it (exit 128). There is no -v flag, so there's no verbose mode to lean on.

Two implications for the proposed fix:

  1. git worktree remove is itself synchronous — the directory is gone before the command returns, same as wt's current fs::rename path in stage_worktree_removal. The fix works only because it runs after the cd directive, so chpwd fires while .sdkmanrc still exists. The reordering is doing the work — git's removal command does not behave differently from fs::rename here.

  2. The current path bypasses git's dirty-file check entirely; wt does its own validation in prepare_worktree_removal and then renames the dir. Swapping in git worktree remove re-introduces that check, so the background command would need --force (mirroring wt's own decisions) — otherwise an untracked file in the worktree, including .sdkmanrc when not committed, would cause the deferred removal to fail silently after the cd.

Minimal reproduction of the untracked-file failure:

mkdir main && cd main && git init -q
echo x > x && git add x && git commit -q -m initial
git worktree add ../feature -b feature
echo 'java=21' > ../feature/.sdkmanrc   # untracked

git worktree remove ../feature
# fatal: '../feature' contains modified or untracked files, use --force to delete it

worktrunk-bot avatar May 15 '26 00:05 worktrunk-bot

but @worktrunk-bot the question is how sdkman would operate if we removed the worktree with git

my guess is that it would operate the same as worktrunk. you would need to install it, repro with wt remove and then see if there's a difference with git worktree remove

max-sixty avatar May 15 '26 03:05 max-sixty

You were right that this isn't unique to wt remove — but the ordering of operations matters, and that's what the proposed fix changes. Tested with sdkman installed on Linux (zsh, sdkman_auto_env=true, SDKMAN_ENV set to the worktree to simulate sdk env):

# Command(s) run from inside /feature sdkman output
A wt remove Could not find /…/feature/.sdkmanrc.
B git worktree remove . Could not find /…/feature/.sdkmanrc. (fires on user's next cd)
C cd ../main && git worktree remove ../feature clean — sdk env clear runs while .sdkmanrc still exists
D cd ../main && wt remove feature clean (same shape as C)

So git worktree remove from inside the deleted worktree produces the same error as wt remove — git doesn't behave differently here. Both delete the directory before any shell cd fires, so chpwd → sdk env clear walks into a missing .sdkmanrc.

The difference is purely ordering. In A, the wt binary renames the directory before the zsh wrapper sources the cd directive (stage_worktree_removal runs inside the binary; the wrapper's builtin cd runs after). In C/D, the cd happens first, so sdkman cleans up against a still-present .sdkmanrc, then deletion happens against an inert path.

The proposed fix puts A into the C/D shape — which is the only path in the matrix that sdkman handles cleanly.

Repro harness (zsh + sdkman)
# in ~/.sdkman/etc/config: sdkman_auto_env=true
source ~/.sdkman/bin/sdkman-init.sh

mkdir -p /tmp/sdk-test && cd /tmp/sdk-test
git init -q main && cd main && git commit -q --allow-empty -m init
git worktree add ../feature -b feature
echo 'java=21.0.0-tem' > ../feature/.sdkmanrc
git -C ../feature add .sdkmanrc && git -C ../feature commit -qm sdkmanrc

cd ../feature
export SDKMAN_ENV="$PWD"   # what `sdk env` would set after loading .sdkmanrc
wt remove --yes            # scenario A
# git worktree remove .    # scenario B (same error)

worktrunk-bot avatar May 15 '26 03:05 worktrunk-bot

OK, so to confirm, wt and git have exactly the same behavior?

max-sixty avatar May 15 '26 03:05 max-sixty

Yes — same outcome, slightly different timing.

Trigger of chpwd sdkman result
wt remove (inside) wt-injected cd /main fires immediately after binary exit Could not find /…/feature/.sdkmanrc.
git worktree remove . (inside) user's next manual cd (git leaves shell in invalid cwd) Could not find /…/feature/.sdkmanrc. (deferred until user moves)

Both walk into a missing .sdkmanrc and fail to deactivate. wt just surfaces the error sooner because it auto-cd's; git defers it to whenever the user next types cd. The underlying failure mode is identical.

worktrunk-bot avatar May 15 '26 03:05 worktrunk-bot

OK — @donvince do you see anything different? Otherwise I think this would be on sdkman to handle a removed cwd...

max-sixty avatar May 15 '26 03:05 max-sixty

Thanks @max-sixty for digging into this. You're right: git worktree remove . from inside the worktree breaks sdkman the same way, so this is sdkman's to fix. They track it as sdkman/sdkman-cli#1241, which is deferred until their native CLI.

The failure is worse than one warning. sdk env clear returns early when .sdkmanrc is missing, so SDKMAN_ENV stays set and the error repeats on every later cd. In bash, sdkman runs from PROMPT_COMMAND, so it repeats at every prompt. The SDKs also stay pinned to the removed worktree's versions.

For anyone else who hits this, here is the zsh workaround I'm using. Put it after sourcing sdkman-init.sh. If the directory that set the env has gone, it restores the default SDK versions and unsets SDKMAN_ENV before sdkman's own hook runs:

# When the directory whose .sdkmanrc set the env is deleted (wt remove,
# git worktree remove), `sdk env clear` fails on every later cd and leaves
# the SDKs pinned. Restore defaults first. sdkman/sdkman-cli#1241
if (( $+functions[sdkman_auto_env] )); then
    _sdkman_env_gone() {
        [[ -n $SDKMAN_ENV && ! -f $SDKMAN_ENV/.sdkmanrc ]] || return 0
        local candidate link
        for candidate in $SDKMAN_CANDIDATES; do
            link=$SDKMAN_CANDIDATES_DIR/$candidate/current
            [[ -h $link ]] && sdk use $candidate ${$(readlink $link):t} >/dev/null
        done
        unset SDKMAN_ENV
    }
    chpwd_functions=(_sdkman_env_gone $chpwd_functions)
fi

I tested it with wt remove from inside a worktree pinned to Java 21. There's no warning, Java goes back to the default, and later cds stay quiet.

donvince avatar Oct 24 '26 00:10 donvince