Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(help): name the doc-entry-point command from clap, not an argv scan (#3762)

Maximilian Roos0b277557260d
diff --git a/src/help.rs b/src/help.rs
index 69a9c1e7b..e05393c03 100644
--- a/src/help.rs
+++ b/src/help.rs
@@ -155,11 +155,18 @@ impl PageMode {
/// On a help/version/doc-generation request, prints output and calls
/// `process::exit(0)`. Otherwise returns so the caller can continue normal parsing.
///
-/// `alias_help_context` is computed by the caller from the same early-parse
-/// pass that extracts global options. When `Some`, the configured aliases are
+/// `alias_help_context` and `subcommand` both come from the caller's
+/// early-parse pass over the real argv, the same one that extracts global
+/// options. When `alias_help_context` is `Some`, the configured aliases are
/// spliced into the rendered output — at the top level for `wt --help`, or
-/// under the Aliases section for `wt step --help`.
-pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::HelpContext>) {
+/// under the Aliases section for `wt step --help`. `subcommand` is the command
+/// the doc-generation entry points below render, taken from clap rather than
+/// re-scanned here, so `wt.exe`, a renamed binary, or `wt -C <path> list
+/// --print-schema` all name the same thing.
+pub fn maybe_handle_help_with_pager(
+ alias_help_context: Option<crate::commands::HelpContext>,
+ subcommand: Option<&str>,
+) {
let args_os: Vec<OsString> = std::env::args_os().collect();
let args: Vec<String> = args_os
.iter()
@@ -176,20 +183,20 @@ pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::
} else {
PageMode::Web
};
- handle_help_page(&args, mode);
+ handle_help_page(subcommand, mode);
process::exit(0);
}
// Check for --print-schema flag (output the JSON Schema for a command's
// --format=json payload)
if args.iter().any(|a| a == "--print-schema") {
- handle_print_schema(&args);
+ handle_print_schema(subcommand);
process::exit(0);
}
// Check for --help-description flag (output meta description for docs)
if args.iter().any(|a| a == "--help-description") {
- handle_help_description(&args);
+ handle_help_description(subcommand);
process::exit(0);
}
@@ -407,16 +414,11 @@ fn extract_about_and_subtitle(cmd: &clap::Command) -> (Option<String>, Option<St
/// Combines the command's `about` (definition) and `long_about` subtitle into
/// a single description suitable for `<meta name="description">`. This is used
/// by the docs sync test to auto-populate the `description` field in frontmatter.
-fn handle_help_description(args: &[String]) {
+fn handle_help_description(subcommand: Option<&str>) {
let mut cmd = cli::build_command();
cmd = crate::completion::inject_hook_subcommands(cmd);
cmd = cmd.color(ColorChoice::Never);
- let subcommand = args
- .iter()
- .filter(|a| *a != "--help-description" && !a.starts_with('-') && !a.ends_with("/wt"))
- .find(|a| !a.contains("target/") && *a != "wt");
-
let Some(subcommand) = subcommand else {
eprintln!("Usage: wt <command> --help-description");
return;
@@ -447,12 +449,7 @@ fn handle_help_description(args: &[String]) {
///
/// One command has a schema today, because one payload is versioned. The
/// subcommand is the axis a second would arrive on.
-fn handle_print_schema(args: &[String]) {
- let subcommand = args
- .iter()
- .filter(|a| !a.starts_with('-') && !a.ends_with("/wt"))
- .find(|a| !a.contains("target/") && *a != "wt");
-
+fn handle_print_schema(subcommand: Option<&str>) {
let Some(subcommand) = subcommand else {
eprintln!(
"Usage: wt <command> --print-schema
@@ -467,10 +464,7 @@ Commands with schemas: list"
}
let schema = crate::commands::list::json_v2::schema_document();
- println!(
- "{}",
- serde_json::to_string_pretty(&schema).expect("schema serializes")
- );
+ crate::output::print_json(&schema).expect("schema serializes");
}
/// Generate a full documentation page for a command.
@@ -495,20 +489,11 @@ Commands with schemas: list"
/// ```
///
/// This is used to generate docs/content/merge.md etc from the source.
-fn handle_help_page(args: &[String], mode: PageMode) {
+fn handle_help_page(subcommand: Option<&str>, mode: PageMode) {
let mut cmd = cli::build_command();
cmd = crate::completion::inject_hook_subcommands(cmd);
cmd = cmd.color(ColorChoice::Never);
- // Find the subcommand name (the arg before --help-page, or after wt)
- let subcommand = args
- .iter()
- .filter(|a| *a != "--help-page" && !a.starts_with('-') && !a.ends_with("/wt"))
- .find(|a| {
- // Skip the binary name
- !a.contains("target/") && *a != "wt"
- });
-
let Some(subcommand) = subcommand else {
eprintln!(
"Usage: wt <command> --help-page
diff --git a/src/main.rs b/src/main.rs
index 4ebdbfdd2..77f7cab5f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -754,15 +754,22 @@ fn parse_cli() -> Cli {
// Apply -C / --config before help handling so `wt -C other --help`
// and `wt --config custom.toml step --help` resolve aliases against the
// requested repo and user config (not the process cwd / default config).
- // The same early parse also tells us whether this is help for the top
- // level or `wt step`, so the splice path in `augment_help` has no
- // separate arg scanner.
- let (directory, config, config_overrides, alias_help_context) = parse_early_globals();
+ // The same early parse also names the command and tells us whether this is
+ // help for the top level or `wt step`, so neither the splice path in
+ // `augment_help` nor the doc-generation entry points has its own arg
+ // scanner.
+ let EarlyGlobals {
+ directory,
+ config,
+ config_overrides,
+ alias_help_context,
+ subcommand,
+ } = parse_early_globals();
apply_global_options(directory, config, config_overrides);
// Handle --help with pager before clap processes it.
// Exits the process on a help/version/doc request; otherwise returns.
- help::maybe_handle_help_with_pager(alias_help_context);
+ help::maybe_handle_help_with_pager(alias_help_context, subcommand.as_deref());
// TODO: Enhance error messages to show possible values for missing enum arguments
// Currently `wt config shell init` doesn't show available shells, but `wt config shell init invalid` does.
@@ -799,29 +806,41 @@ fn apply_global_options(
}
}
-/// Parse global options (`-C`, `--config`, `--config-set`) and detect whether this
-/// invocation renders help that should include the configured aliases — in a
-/// single pass against the real `Cli` definition.
+/// What the pre-clap pass reads off the real argv.
+#[derive(Default)]
+struct EarlyGlobals {
+ directory: Option<std::path::PathBuf>,
+ config: Option<std::path::PathBuf>,
+ config_overrides: Vec<String>,
+ alias_help_context: Option<commands::HelpContext>,
+ /// The top-level command, for the doc-generation entry points
+ /// (`--help-page`, `--help-description`, `--print-schema`); `None` when
+ /// argv names none. A name the `Cli` definition doesn't declare still
+ /// arrives, through the `external_subcommand` arm that carries user
+ /// aliases, so those entry points can name it back in their own errors.
+ subcommand: Option<String>,
+}
+
+/// Parse global options (`-C`, `--config`, `--config-set`), name the command,
+/// and detect whether this invocation renders help that should include the
+/// configured aliases — in a single pass against the real `Cli` definition.
///
/// Uses `ignore_errors(true)` so unknown args, missing values, and `--help`
/// don't abort parsing — we just read what matched. This lets `wt -C other
/// --help` apply `-C` before the help path renders, so `augment_help`
/// resolves aliases against the requested repo instead of the process cwd.
+/// It's also what lets the doc-generation flags, which the `Cli` definition
+/// doesn't declare, ride along without derailing the parse.
///
/// Using `cli::build_command()` rather than a hand-rolled mini-command keeps
/// the global-flag definitions in one place (the derive on `Cli`), so renaming
/// `-C` or adding a value-taking global doesn't silently desync this path.
-fn parse_early_globals() -> (
- Option<std::path::PathBuf>,
- Option<std::path::PathBuf>,
- Vec<String>,
- Option<commands::HelpContext>,
-) {
+fn parse_early_globals() -> EarlyGlobals {
let cmd = cli::build_command()
.ignore_errors(true)
.disable_help_flag(true);
let Ok(matches) = cmd.try_get_matches_from(std::env::args_os()) else {
- return (None, None, Vec::new(), None);
+ return EarlyGlobals::default();
};
let directory = matches.get_one::<std::path::PathBuf>("directory").cloned();
let config = matches.get_one::<std::path::PathBuf>("config").cloned();
@@ -838,7 +857,13 @@ fn parse_early_globals() -> (
Some(("step", sub)) if sub.subcommand_name().is_none() => Some(commands::HelpContext::Step),
_ => None,
};
- (directory, config, config_overrides, alias_help_context)
+ EarlyGlobals {
+ directory,
+ config,
+ config_overrides,
+ alias_help_context,
+ subcommand: matches.subcommand_name().map(str::to_owned),
+ }
}
fn init_command_log(command_line: &str) {
diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rs
index 27196fc28..9e83248da 100644
--- a/tests/integration_tests/help.rs
+++ b/tests/integration_tests/help.rs
@@ -11,11 +11,12 @@
//! only the presentation varies.
#![cfg(not(windows))]
-use crate::common::{add_standard_env_redactions, wt_command};
+use crate::common::{add_standard_env_redactions, configure_cli_command, wt_bin, wt_command};
use ansi_str::AnsiStr as _;
use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
+use std::process::Command;
/// Insta settings shared by every help / version / usage snapshot: the
/// standard env redactions plus the snapshot path. Routing all of them through
@@ -385,3 +386,46 @@ fn test_print_schema_rejects_unknown_command() {
);
}
}
+
+/// The doc-generation entry points take their command from the early clap
+/// parse, so neither the binary's name nor a global option carrying a value
+/// reaches the answer.
+///
+/// A hand-rolled argv scan recognized the binary by the shape of its path,
+/// which made `wt.exe list --print-schema` — the name every Windows install
+/// ships — a request for a command named after the binary, and read the
+/// `<path>` in `wt -C <path> list --print-schema` as the command. The name is
+/// exercised through a symlink because this module is Unix-only.
+#[test]
+fn test_dev_entry_points_take_command_from_clap() {
+ let dir = tempfile::tempdir().expect("create tempdir");
+ let renamed = dir.path().join("wt.exe");
+ std::os::unix::fs::symlink(wt_bin(), &renamed).expect("symlink wt binary");
+
+ for args in [
+ &["list", "--print-schema"][..],
+ &["merge", "--help-page"][..],
+ &["merge", "--help-description"][..],
+ &["-C", ".", "list", "--print-schema"][..],
+ ] {
+ let mut cmd = Command::new(&renamed);
+ configure_cli_command(&mut cmd);
+ cmd.current_dir(dir.path());
+ let output = cmd
+ .args(args)
+ .output()
+ .unwrap_or_else(|e| panic!("failed to run wt.exe {args:?}: {e}"));
+
+ assert_eq!(
+ output.status.code(),
+ Some(0),
+ "wt.exe {args:?} should succeed; stderr: {:?}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ !output.stdout.is_empty(),
+ "wt.exe {args:?} printed nothing; stderr: {:?}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+}