Skip to content

Add git-style external subcommand dispatch (wt-<name>) - #2054

Merged
max-sixty merged 7 commits into
mainfrom
fix/external-subcommands
Apr 10, 2026
Merged

max-sixty merged 7 commits into
mainfrom
fix/external-subcommands

Conversation

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Summary

  • wt foo now runs wt-foo from PATH when foo is not a built-in, mirroring git foo → git-foo. Third-party tools like a hypothetical wt-sync can be installed and invoked as wt sync without touching this repo.
  • Built-ins always take precedence (clap only dispatches External when no built-in matched), so external binaries cannot shadow existing subcommands.
  • Nested subcommand hints still pre-empt the PATH lookup — wt squash continues to suggest wt step squash rather than searching for wt-squash.
  • When nothing matches, wt prints a git-style 'foo' is not a wt command error with a Levenshtein-based typo suggestion (replacing the old clap InvalidSubcommand handler).
  • The global -C <path> flag is forwarded as the child's working directory, matching git's semantics.
  • Child exit codes (including Unix signal codes) are propagated verbatim. wt does not decorate child failures with its own error line — the child has already reported whatever it needed to.

Requested in #2053 — the original PR added wt sync as a built-in, but the preferred approach is a generic extensibility mechanism so wt sync can call any wt-sync binary on PATH.

Implementation

  • Commands::External(Vec<OsString>) captured via clap's #[command(external_subcommand)].
  • src/commands/external.rs owns the dispatch: nested-suggestion check first, then which::which("wt-<name>"), then run with Command::status() inheriting stdio.
  • main() dispatches External directly (instead of via dispatch_command) so the parsed -C <path> can be forwarded as the child's cwd.
  • The nested-suggestion path moved from clap's built-in error renderer to our module; help snapshots updated to the cleaner worktrunk-style output (✗ / ↳).

Test plan

  • cargo test --test integration external_subcommand — 7 new integration tests cover happy path, not-found error, typo suggestion, nested suggestion winning over PATH lookup, exit-code propagation (exit 42), -C flag forwarding, and --help passthrough.
  • cargo test --bins — 3 new unit tests for closest_subcommand (typo, unrelated, hidden).
  • cargo test --test integration — full suite passes (1407 tests).
  • cargo test --lib --bins — full unit suite passes (500 tests).
  • cargo fmt --check and cargo clippy --all-targets --all-features -- -D warnings.
  • Manual smoke tests: wt wt-<name>, wt unknown, wt siwtch, wt squash, wt -C /tmp wt-<name>, wt wt-<name> --help, child exit code 42 propagation.

When the user runs `wt foo` and `foo` is not a built-in subcommand, wt now
looks for `wt-foo` on PATH and runs it with the remaining arguments. This
mirrors git's behaviour where `git foo` finds `git-foo`, so third-party
tools like `wt-sync` can be installed and invoked as `wt sync`.

Built-in subcommands always take precedence — clap only dispatches to the
External variant when no built-in matched, so an external `wt-switch` can
never shadow `wt switch`. Nested subcommand hints (`wt squash` →
`wt step squash`) still pre-empt the PATH lookup, preserving the existing
help behaviour. When no match and no external binary is found, wt prints
a git-style "'foo' is not a wt command" error with a Levenshtein-based
typo suggestion.

The global `-C <path>` flag is forwarded as the child's working directory
so `wt -C /tmp sync` behaves the same as `cd /tmp && wt-sync`. Child exit
codes (including signal codes on Unix) are propagated verbatim, and wt
does not decorate child failures with its own error line — the child has
already reported whatever it needed to.

Requested in #2053.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@max-sixty max-sixty left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why don't we add docs here? Consider a new PR which adds guidance in CLAUDE.md for docs requirements; namely that all the user API should be documented; new features should generally be labeled an experimental

and then at the object-level, fix that issue in this PR

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The shell-integration test test_source_flag_forwards_errors will fail on this PR. CI runs it via the pre-merge hook (--features shell-integration-tests, see .config/wt.toml) in test (linux), test (macos), and again in code-coverage. Two updates needed:

1. Test assertion needs updating. At tests/integration_tests/shell_wrapper.rs#L1606-L1612 the assertion looks for "unrecognized subcommand", but after this PR wt foo emits 'foo' is not a wt command. See 'wt --help'. (verified locally by building from this branch — ./target/debug/wt foo output confirms). The new error path in src/commands/external.rs::print_not_found no longer contains the string unrecognized subcommand.

        // CRITICAL: Should see wt's actual error message that the subcommand is unknown
        assert!(
            output.combined.contains("is not a wt command"),
            "{}: Should show actual wt error message 'is not a wt command'.\nOutput:\n{}",
            shell,
            output.combined
        );

2. Snapshot needs regenerating. source_flag_error_passthrough.snap still contains the old clap-style rendering (error: unrecognized subcommand 'foo' + Usage: block). Regenerate with e.g. cargo insta test --accept --features shell-integration-tests -- test_source_flag_forwards_errors.


Separately, as a cleanup observation (not a blocker): enhance_and_exit_error in src/main.rs#L75-L96 still contains the InvalidSubcommand + suggest_nested_subcommand branch. With external_subcommand, clap no longer raises InvalidSubcommand for unknown top-level commands — nested-level unknowns (wt step foo) still hit this path but will never match suggest_nested_subcommand, which only maps top-level names to wt step … / wt hook …. The PR description says this handler was replaced; the dead branch can be deleted to match.

worktrunk-bot and others added 3 commits April 10, 2026 17:04
Restores the suggestion clap previously emitted, so users still see a
pointer to --help after nested-subcommand or not-found errors.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The source-flag passthrough test asserted on 'unrecognized subcommand',
which was the old clap-generated string. The not-found path now prints
'is not a wt command' (plus a --help hint on the next line), so update
both the assertion and the consolidated snapshot.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Adds a [experimental]-labelled section explaining how `wt-<name>`
binaries on PATH become `wt <name>` invocations, alongside `wt` aliases
in the existing extensibility region.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

On the docs ask: added a [experimental]-labelled "External subcommands" section to tips-patterns.md in 61c2c33, right next to wt aliases in the extensibility region. It covers PATH lookup, built-in precedence, argument passthrough, -C forwarding, and the not-found fallback. Happy to open a separate PR for the CLAUDE.md docs-requirements / experimental-labelling guidance you mentioned once this one lands.

worktrunk-bot and others added 2 commits April 10, 2026 17:28
Thread `directory` into `dispatch_command` so the external-subcommand
branch lives in the main match alongside the built-ins — the separate
`Commands::External` unreachable arm was dead code and showed up as an
uncovered line on the patch report.

Add unit tests for the two error paths the integration suite couldn't
reach: the non-UTF-8 subcommand name branch (built via `OsString::from_vec`)
and the Unix signal-exit branch (via a `kill -TERM $$` helper script),
closing the last codecov/patch gap on this PR.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Match clap's exact "For more information, try '<cmd> --help'." wording —
capital F, trailing period — so the hint reads identically to the rest of
clap's errors.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Comment thread src/commands/external.rs Outdated
eprintln!(
"{}",
hint_message(cformat!(
"the most similar command is <cyan,bold>{suggestion}</>"

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we have proper capitalization throughout our error message changes?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 4d95957 — all three messages that had lowercase first words are now capitalized to match worktrunk's sentence-case convention ("Branch X already exists", "No branch named X", etc.):

  • unrecognized subcommand 'X' → Unrecognized subcommand 'X'
  • perhaps X? → Perhaps X?
  • the most similar command is X → The most similar command is X

Regenerated the four nested_subcommand_*.snap files via cargo insta test.

Left '<name>' is not a wt command alone: it starts with the user's literal input, matching the existing "<bold>{branch}</> has uncommitted changes" pattern where a variable leads the sentence.

Match worktrunk's sentence-case convention (e.g., 'Branch X already
exists', 'No branch named X') so the first word of each standalone
error/hint line begins with a capital letter:

- 'unrecognized subcommand' -> 'Unrecognized subcommand'
- 'perhaps X?' -> 'Perhaps X?'
- 'the most similar command is' -> 'The most similar command is'

Nested-subcommand snapshots regenerated via cargo insta. The
not-found line "'<name>' is not a wt command" starts with the
user's literal input (matching the existing
'<bold>{branch}</> has uncommitted changes' pattern) and is left
unchanged.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@max-sixty
max-sixty merged commit 5709eb5 into main Apr 10, 2026
25 of 26 checks passed
@max-sixty
max-sixty deleted the fix/external-subcommands branch April 10, 2026 20:07
max-sixty added a commit that referenced this pull request Apr 14, 2026
`#[command(external_subcommand)]` (added in #2054 for `wt-<name>` dispatch)
captures every unknown subcommand, so clap's native `InvalidSubcommand`
error path was dead — `wt s` printed a custom git-style line instead of
clap's formatted error with suggestions and Usage block.

Synthesize a real `clap::Error{InvalidSubcommand}` when no `wt-<name>`
binary is on PATH and route it through `enhance_and_exit_error`, so the
output matches what clap would have produced:

    error: unrecognized subcommand 's'
      tip: some similar subcommands exist: 'step', 'switch'
    Usage: wt [OPTIONS] [COMMAND]
    For more information, try '--help'.

Nested-subcommand hints (`wt squash` → `wt step squash`) now layer on top
of clap's error via the same path instead of a separate branch, so all
unrecognized subcommands flow through one code path.

Swap Levenshtein for Jaro-Winkler > 0.7 to match clap's internal
`did_you_mean`, so short names like `s` get suggestions that match
short-prefix typos.

Exit code is now 2 (clap standard), matching pre-#2054 behavior.

Co-Authored-By: Claude <[email protected]>
max-sixty added a commit that referenced this pull request Apr 14, 2026
`#[command(external_subcommand)]` (added in #2054 for `wt-<name>`
dispatch) captures every unknown subcommand, so clap's native
`InvalidSubcommand` error path was dead — `wt s` printed a custom
git-style line instead of clap's formatted error with suggestions and
Usage block.

This PR synthesizes a real `clap::Error{InvalidSubcommand}` when no
`wt-<name>` binary is on PATH and routes it through
`enhance_and_exit_error`, so the output matches what clap would have
produced:

\`\`\`
error: unrecognized subcommand 's'
  tip: some similar subcommands exist: 'step', 'switch'
Usage: wt [OPTIONS] [COMMAND]
For more information, try '--help'.
\`\`\`

Nested-subcommand hints (`wt squash` → `wt step squash`) now layer on
top of clap's error via the same path instead of a separate branch, so
all unrecognized subcommands flow through one code path.

Swap Levenshtein for Jaro-Winkler > 0.7 to match clap's internal
`did_you_mean`, so short names like `s` get suggestions that match
short-prefix typos.

Exit code is now 2 (clap standard), matching pre-#2054 behavior.

## Test plan
- [x] `cargo run -- s` / `siwtch` / `squash` / unknown → verified output
and exit codes
- [x] `wt hook pre-merge --yes` (full test suite, 3178 tests)
- [x] Updated integration tests in `tests/integration_tests/external.rs`
- [x] Regenerated 5 snapshots (4 nested-suggestion help + 1 shell
source-flag)

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants