Repository navigation
fix(switch): atomic no-overwrite backup for --clobber - #2849
Merged
Merged
Conversation
`wt switch --clobber` backs up an existing path before clobbering it. The old code checked `backup_path.exists()` and later called `std::fs::rename`, which silently overwrites an existing destination — a time-of-check/time-of-use race that could destroy whatever appeared at the backup path in between. The backup now moves via a new `worktrunk::fs::rename_no_replace` (`renameat2(NOREPLACE)` on Linux/macOS, `MoveFileExW` on Windows): an atomic rename that fails closed when the destination already exists. On a name collision the move counts up to the next free `-N` name, so a same-second clobber no longer fails and an existing backup is never overwritten. `rustix` and `windows-sys` are declared directly to enable the required features; both were already present transitively. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
worktrunk-bot
approved these changes
May 21, 2026
The Windows backup path used `unsafe { MoveFileExW(...) }`, which the
crate's `unsafe_code = "forbid"` lint rejects — `forbid` cannot be
locally overridden, and `priority.rs` shows the crate deliberately
shells out rather than use unsafe FFI.
Replace the hand-rolled `worktrunk::fs` module with the `renamore`
crate. Its `rename_exclusive` is the same atomic no-overwrite rename
(`renameat2(RENAME_NOREPLACE)` / `renamex_np(RENAME_EXCL)` /
`MoveFileExW`), with the FFI — and its `unsafe` — encapsulated inside
the crate, so worktrunk stays free of unsafe code.
Drops the `src/fs.rs` module and the direct `rustix`/`windows-sys`
dependencies (back to transitive-only); adds `renamore`.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
worktrunk-bot
approved these changes
May 21, 2026
Collaborator
|
Same shape as #2615 and #2624 — tests that depend on environment not available under the nix sandbox. Best fixed in a follow-up against |
max-sixty
added a commit
that referenced
this pull request
May 21, 2026
…2853) The `nix-flake` CI job was red on `main`: the unit test `commands::hook_plan::tests::approve_readonly_drops_unapproved_project_keeps_user` panicked with `Failed to create config directory: Permission denied`. The test called `approve_command(.., None)`. The `None` for `approvals_path` makes `Approvals` resolve the path through `approvals_path()`, which — in the lib crate compiled in non-test mode — points at the real `~/.config/worktrunk/` directory. `approve_command` then `create_dir_all`s it. Outside a sandbox `$HOME` is writable, so the test silently passed while writing a stray `[projects.proj]` entry into the user's `approvals.toml`. The nix build sandbox has no writable config dir, so it panicked instead. This was latent on `main` since #2806 (which added the test). It only started tripping the gate now because the `nix-flake` job runs when a PR touches `Cargo.{toml,lock}`, and #2849 was the first to do so — so `nix-flake` failed there for a reason unrelated to that PR's change. The fix points `approve_command` at a `tempfile::tempdir()`-backed approvals path via the `Some(&path)` parameter it already accepts — no process-env mutation (`tests/CLAUDE.md` bans it), matching the in-file pattern in `src/config/approvals.rs`'s own tests. Same class of fix as #2615 and #2624. The two sibling tests in `hook_plan.rs` only *read* via `Approvals::load()`, which returns the default when no file exists — never creating a directory or writing — so they pass in the sandbox unchanged and were left as-is. Verified by reproducing the sandbox condition locally (test binary run with `HOME` / `XDG_CONFIG_HOME` pointed at a non-writable dir): the target test fails before the fix and passes after, and all three `hook_plan` tests still pass under a plain `cargo test`. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty
added a commit
that referenced
this pull request
May 22, 2026
`wt switch --clobber` and `wt step relocate --clobber` each had their own logic for backing up a path blocking the target, and the two had diverged. relocate used an `exists()` check followed by `std::fs::rename` — a time-of-check/time-of-use race, since `std::fs::rename` silently replaces an existing file or empty directory on Unix and could destroy a just-created backup. switch (#2849) instead used `renamore::rename_exclusive`, an atomic no-overwrite rename, and counted up through suffixes (`…-2`, `…-3`, …) on a name collision rather than failing. This PR replaces both with one shared helper in `commands::backup`. `back_up_clobbered_path_now` computes the timestamped name and delegates to the suffix-iterating `back_up_clobbered_path`, which moves the blocker with `renamore::rename_exclusive` — atomic and no-overwrite, so an existing backup is never clobbered; a name collision just lands on the next free `-N` name. relocate gains the suffix fallback (previously it failed closed on `AlreadyExists`), the timestamp computation is no longer duplicated across the two call sites, and `renamore::rename_exclusive` now has a single caller. `renamore` is already a direct dependency and keeps the platform FFI and its `unsafe` inside that crate, so worktrunk stays `unsafe_code = "forbid"`. relocate's backup name changes from `.bak-<timestamp>` to the extension-aware `.bak.<timestamp>` form used by switch (e.g. `repo.feature` → `repo.feature.bak.<timestamp>`). The `test_relocate_clobber_error_backup_exists` regression test asserted the old fail-closed behavior and is rewritten as `test_relocate_clobber_falls_back_when_backup_taken`, mirroring the switch test. CLI help and the generated doc mirrors are updated for the new naming and fallback. The shared helper carries the suffix-iteration, collision, and missing-source unit tests (moved from `resolve.rs`); the relocate `--clobber` path keeps its integration coverage. > _This was written by Claude Code on behalf of Maximilian Roos_ --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
max-sixty
added a commit
that referenced
this pull request
May 23, 2026
## Summary `wt switch --clobber` backs up an existing path before clobbering it. The old code checked `backup_path.exists()` and then, later, called `std::fs::rename` — which silently overwrites an existing destination on every platform. Anything that appeared at the backup path between the check and the rename (a same-second clobber, or a path that raced in) was destroyed: a time-of-check/time-of-use data-loss race on a `--clobber` operation. ## The fix The backup now moves with `renamore::rename_exclusive` — an atomic, no-overwrite rename: `renameat2(RENAME_NOREPLACE)` on Linux, `renamex_np(RENAME_EXCL)` on macOS, `MoveFileExW` on Windows. It fails closed (`AlreadyExists`) rather than overwriting. `renamore` keeps the platform FFI — and its `unsafe` — inside the crate, so worktrunk itself stays `unsafe_code = "forbid"`. `back_up_clobbered_path` moves the stale path with that primitive. If the timestamped backup name is already taken, it counts up — `…-2`, `…-3`, … — until it finds a free name, so a collision no longer fails the command and an existing backup is never overwritten. The loop terminates because a directory holds finitely many entries; genuine I/O errors still surface as errors. The timestamp and the move now both happen at execution time, which also closes a smaller stale-plan window — the backup path was previously computed during planning and renamed much later. ## Key files - `src/commands/worktree/resolve.rs` — `back_up_clobbered_path` retry loop. - `src/commands/worktree/switch.rs` — `execute_switch` uses it; the plan now carries `needs_clobber_backup: bool` instead of a resolved path. ## Notes - `renamore` is a new dependency. `rustix` / `windows-sys` are deliberately not added as direct dependencies — calling either's rename API requires an `unsafe` block, which this crate forbids; `renamore` encapsulates that. - `wt step relocate --clobber` has the identical check-then-`std::fs::rename` race. It is **not** fixed here — a separate branch handles relocate; when that lands it should adopt `renamore::rename_exclusive`. ## Testing `back_up_clobbered_path` has unit tests covering every branch — fresh move, `-N` fallback, many collisions, non-`AlreadyExists` error. Integration tests cover `wt switch --clobber` end-to-end, including the collision fallback (which runs on the Windows CI job). --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty
added a commit
that referenced
this pull request
May 23, 2026
…2853) The `nix-flake` CI job was red on `main`: the unit test `commands::hook_plan::tests::approve_readonly_drops_unapproved_project_keeps_user` panicked with `Failed to create config directory: Permission denied`. The test called `approve_command(.., None)`. The `None` for `approvals_path` makes `Approvals` resolve the path through `approvals_path()`, which — in the lib crate compiled in non-test mode — points at the real `~/.config/worktrunk/` directory. `approve_command` then `create_dir_all`s it. Outside a sandbox `$HOME` is writable, so the test silently passed while writing a stray `[projects.proj]` entry into the user's `approvals.toml`. The nix build sandbox has no writable config dir, so it panicked instead. This was latent on `main` since #2806 (which added the test). It only started tripping the gate now because the `nix-flake` job runs when a PR touches `Cargo.{toml,lock}`, and #2849 was the first to do so — so `nix-flake` failed there for a reason unrelated to that PR's change. The fix points `approve_command` at a `tempfile::tempdir()`-backed approvals path via the `Some(&path)` parameter it already accepts — no process-env mutation (`tests/CLAUDE.md` bans it), matching the in-file pattern in `src/config/approvals.rs`'s own tests. Same class of fix as #2615 and #2624. The two sibling tests in `hook_plan.rs` only *read* via `Approvals::load()`, which returns the default when no file exists — never creating a directory or writing — so they pass in the sandbox unchanged and were left as-is. Verified by reproducing the sandbox condition locally (test binary run with `HOME` / `XDG_CONFIG_HOME` pointed at a non-writable dir): the target test fails before the fix and passes after, and all three `hook_plan` tests still pass under a plain `cargo test`. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty
added a commit
that referenced
this pull request
May 23, 2026
`wt switch --clobber` and `wt step relocate --clobber` each had their own logic for backing up a path blocking the target, and the two had diverged. relocate used an `exists()` check followed by `std::fs::rename` — a time-of-check/time-of-use race, since `std::fs::rename` silently replaces an existing file or empty directory on Unix and could destroy a just-created backup. switch (#2849) instead used `renamore::rename_exclusive`, an atomic no-overwrite rename, and counted up through suffixes (`…-2`, `…-3`, …) on a name collision rather than failing. This PR replaces both with one shared helper in `commands::backup`. `back_up_clobbered_path_now` computes the timestamped name and delegates to the suffix-iterating `back_up_clobbered_path`, which moves the blocker with `renamore::rename_exclusive` — atomic and no-overwrite, so an existing backup is never clobbered; a name collision just lands on the next free `-N` name. relocate gains the suffix fallback (previously it failed closed on `AlreadyExists`), the timestamp computation is no longer duplicated across the two call sites, and `renamore::rename_exclusive` now has a single caller. `renamore` is already a direct dependency and keeps the platform FFI and its `unsafe` inside that crate, so worktrunk stays `unsafe_code = "forbid"`. relocate's backup name changes from `.bak-<timestamp>` to the extension-aware `.bak.<timestamp>` form used by switch (e.g. `repo.feature` → `repo.feature.bak.<timestamp>`). The `test_relocate_clobber_error_backup_exists` regression test asserted the old fail-closed behavior and is rewritten as `test_relocate_clobber_falls_back_when_backup_taken`, mirroring the switch test. CLI help and the generated doc mirrors are updated for the new naming and fallback. The shared helper carries the suffix-iteration, collision, and missing-source unit tests (moved from `resolve.rs`); the relocate `--clobber` path keeps its integration coverage. > _This was written by Claude Code on behalf of Maximilian Roos_ --------- Co-authored-by: Claude Opus 4.7 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
wt switch --clobberbacks up an existing path before clobbering it. The old code checkedbackup_path.exists()and then, later, calledstd::fs::rename— which silently overwrites an existing destination on every platform. Anything that appeared at the backup path between the check and the rename (a same-second clobber, or a path that raced in) was destroyed: a time-of-check/time-of-use data-loss race on a--clobberoperation.The fix
The backup now moves with
renamore::rename_exclusive— an atomic, no-overwrite rename:renameat2(RENAME_NOREPLACE)on Linux,renamex_np(RENAME_EXCL)on macOS,MoveFileExWon Windows. It fails closed (AlreadyExists) rather than overwriting.renamorekeeps the platform FFI — and itsunsafe— inside the crate, so worktrunk itself staysunsafe_code = "forbid".back_up_clobbered_pathmoves the stale path with that primitive. If the timestamped backup name is already taken, it counts up —…-2,…-3, … — until it finds a free name, so a collision no longer fails the command and an existing backup is never overwritten. The loop terminates because a directory holds finitely many entries; genuine I/O errors still surface as errors.The timestamp and the move now both happen at execution time, which also closes a smaller stale-plan window — the backup path was previously computed during planning and renamed much later.
Key files
src/commands/worktree/resolve.rs—back_up_clobbered_pathretry loop.src/commands/worktree/switch.rs—execute_switchuses it; the plan now carriesneeds_clobber_backup: boolinstead of a resolved path.Notes
renamoreis a new dependency.rustix/windows-sysare deliberately not added as direct dependencies — calling either's rename API requires anunsafeblock, which this crate forbids;renamoreencapsulates that.wt step relocate --clobberhas the identical check-then-std::fs::renamerace. It is not fixed here — a separate branch handles relocate; when that lands it should adoptrenamore::rename_exclusive.Testing
back_up_clobbered_pathhas unit tests covering every branch — fresh move,-Nfallback, many collisions, non-AlreadyExistserror. Integration tests coverwt switch --clobberend-to-end, including the collision fallback (which runs on the Windows CI job).