Skip to content

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

feat(step): show aliases in `wt step --help`; list user + project separately (#2141)

Maximilian Roosfaab53f1f89d
diff --git a/docs/content/step.md b/docs/content/step.md
index 0afc19104..7045ab951 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -48,7 +48,7 @@ wt step - Run individual operations
The building blocks of <b>wt merge</b> — commit, squash, rebase, push — plus standalone utilities.
-Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span class=c>[COMMAND]</span>
+Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span class=c>&lt;COMMAND&gt;</span>
<b><span class=g>Commands:</span></b>
<b><span class=c>commit</span></b> Stage and commit with LLM-generated message
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index 453d29909..cf3c7a2d2 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -41,7 +41,7 @@ wt step - Run individual operations
The building blocks of wt merge — commit, squash, rebase, push — plus standalone utilities.
-Usage: wt step [OPTIONS] [COMMAND]
+Usage: wt step [OPTIONS] <COMMAND>
Commands:
commit Stage and commit with LLM-generated message
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index f8d884b4a..a24772ce2 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1092,6 +1092,7 @@ pre-merge = [
/// The building blocks of `wt merge` — commit, squash, rebase, push — plus standalone utilities.
#[command(
name = "step",
+ arg_required_else_help = true,
after_long_help = r#"## Examples
Commit with LLM-generated message:
@@ -1203,7 +1204,7 @@ Alias names that match a built-in step command (`commit`, `squash`, etc.) are sh
)]
Step {
#[command(subcommand)]
- action: Option<StepCommand>,
+ action: StepCommand,
},
/// Run configured hooks
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 1310f5fcc..1100676a5 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -390,30 +390,27 @@ fn alias_prepared_command(cmd: &worktrunk::config::Command, context_json: &str)
}
}
-pub(crate) fn step_list() -> anyhow::Result<()> {
- // Route through clap's own `-h` error path so styles, display_name, and
- // global settings (`disable_help_subcommand`, etc.) are propagated from
- // the root Cli. Rendering the subcommand's help directly via
- // `find_subcommand_mut(...).render_help()` skips that propagation.
- let mut cmd = crate::cli::build_command();
- let help = match cmd.try_get_matches_from_mut(["wt", "step", "-h"]) {
- Ok(_) => bail!("Expected clap to emit help, got a successful parse"),
- Err(e)
- if matches!(
- e.kind(),
- clap::error::ErrorKind::DisplayHelp
- | clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand,
- ) =>
- {
- e.render().ansi().to_string()
- }
- Err(e) => return Err(anyhow::anyhow!("Failed to render step help: {e}")),
- };
+/// Where an alias came from. When the same name is defined in both configs,
+/// the listing shows both entries in runtime order (user first, then project)
+/// rather than merging them, so users see the real commands from each source.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum AliasSource {
+ User,
+ Project,
+}
+/// Splice the Aliases section into clap-rendered `wt step` help, if any
+/// aliases are configured.
+///
+/// Called from the help path in `help.rs` — which covers `wt step`
+/// (via `arg_required_else_help`), `wt step -h`, and `wt step --help`,
+/// all of which flow through clap's `DisplayHelp` error. Tolerates
+/// running outside a repository: user-config aliases still list,
+/// project-config aliases just get skipped.
+pub(crate) fn augment_step_help(help: &str) -> String {
let aliases = load_aliases_for_listing();
if aliases.is_empty() {
- eprint!("{help}");
- return Ok(());
+ return help.to_string();
}
// Place the Aliases section right after Commands so it sits next to the
@@ -428,21 +425,13 @@ pub(crate) fn step_list() -> anyhow::Result<()> {
crate::cli::help_styles().get_header().render()
);
match help.find(&options_heading) {
- Some(pos) => {
- eprint!("{}", &help[..pos]);
- eprint!("{aliases_section}\n\n");
- eprint!("{}", &help[pos..]);
- }
+ Some(pos) => format!("{}{aliases_section}\n\n{}", &help[..pos], &help[pos..]),
None => {
// Clap's styling changed; fall back to appending so we don't
// silently drop the aliases list.
- eprint!("{help}");
- eprintln!();
- eprint!("{aliases_section}");
+ format!("{help}\n{aliases_section}")
}
}
-
- Ok(())
}
/// Format the list of aliases as a styled help section.
@@ -451,22 +440,39 @@ pub(crate) fn step_list() -> anyhow::Result<()> {
/// bold+cyan names) so the Aliases section blends in with the rest of
/// `-h` output. Returns the block without leading or trailing blank lines —
/// the caller positions it.
-fn render_aliases_section(aliases: &BTreeMap<String, CommandConfig>) -> String {
+///
+/// When a name is defined in both user and project config, two rows are
+/// shown (user first, then project, matching runtime order). Both rows
+/// carry a source marker so the reader can tell which pipeline is which.
+fn render_aliases_section(entries: &[(String, CommandConfig, AliasSource)]) -> String {
use std::fmt::Write as _;
+ // Names appearing in both sources need source markers to be distinguishable.
+ let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
+ for (name, _, _) in entries {
+ *counts.entry(name.as_str()).or_insert(0) += 1;
+ }
+
let mut out = String::new();
let _ = writeln!(out, "{}", cformat!("<bold><green>Aliases:</></>"));
- let name_width = aliases.keys().map(|n| n.len()).max().unwrap_or(0);
+ let name_width = entries.iter().map(|(n, _, _)| n.len()).max().unwrap_or(0);
let mut first = true;
- for (name, cfg) in aliases {
+ for (name, cfg, source) in entries {
if !first {
out.push('\n');
}
first = false;
let padding = " ".repeat(name_width - name.len());
let summary = format_alias_summary(cfg);
+ // Shadowed-by-builtin is a warning (yellow) and takes precedence over
+ // the source marker so the row doesn't pile up suffixes.
let suffix = if BUILTIN_STEP_COMMANDS.contains(&name.as_str()) {
cformat!(" <yellow>(shadowed by built-in)</>")
+ } else if counts.get(name.as_str()).copied().unwrap_or(0) > 1 {
+ match source {
+ AliasSource::User => cformat!(" <dim>(user)</>"),
+ AliasSource::Project => cformat!(" <dim>(project)</>"),
+ }
} else {
String::new()
};
@@ -479,28 +485,64 @@ fn render_aliases_section(aliases: &BTreeMap<String, CommandConfig>) -> String {
out
}
-/// Load merged aliases (user + project) for display.
+/// Load aliases for display as a flat list sorted by name, with source tagged.
+///
+/// Duplicate names (same alias in both user and project) appear twice — once
+/// per source, user first, matching runtime execution order. Showing each
+/// separately preserves the individual command text; merging them would
+/// reduce to an uninformative step count when both are unnamed singles.
+///
+/// Project config is parsed directly from TOML here instead of going through
+/// `ProjectConfig::load`, which emits deprecation/unknown-field warnings as a
+/// side effect. Help is an informational surface that should stay quiet —
+/// users see those warnings from `wt config show` and execution paths. The
+/// `aliases` table has no deprecated forms, so skipping the migration is safe.
///
/// Tolerates missing or unloadable config: this is a discovery surface, not
/// an execution surface, so we'd rather show the built-in commands than
/// error out when a repo isn't detected or a config file is malformed.
/// `step_alias` surfaces those errors at execution time.
-fn load_aliases_for_listing() -> BTreeMap<String, CommandConfig> {
- let Ok(user_config) = UserConfig::load() else {
- return BTreeMap::new();
- };
- let (project_id, project_config) = match Repository::current() {
- Ok(repo) => (
- repo.project_identifier().ok(),
- ProjectConfig::load(&repo, true).ok().flatten(),
- ),
- Err(_) => (None, None),
- };
- let mut aliases = user_config.aliases(project_id.as_deref());
- if let Some(pc) = project_config.as_ref() {
- append_aliases(&mut aliases, &pc.aliases);
+fn load_aliases_for_listing() -> Vec<(String, CommandConfig, AliasSource)> {
+ let repo = Repository::current().ok();
+ let project_id = repo.as_ref().and_then(|r| r.project_identifier().ok());
+
+ let user_aliases = UserConfig::load()
+ .ok()
+ .map(|uc| uc.aliases(project_id.as_deref()))
+ .unwrap_or_default();
+
+ let project_aliases = repo
+ .as_ref()
+ .and_then(load_project_aliases_silent)
+ .unwrap_or_default();
+
+ let mut entries: Vec<(String, CommandConfig, AliasSource)> = user_aliases
+ .into_iter()
+ .map(|(n, c)| (n, c, AliasSource::User))
+ .chain(
+ project_aliases
+ .into_iter()
+ .map(|(n, c)| (n, c, AliasSource::Project)),
+ )
+ .collect();
+
+ // Sort by name; for ties, user before project (derived Ord on AliasSource)
+ // so duplicates display in runtime execution order.
+ entries.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
+ entries
+}
+
+/// Parse `.config/wt.toml` directly, extracting just `aliases`, without
+/// triggering `ProjectConfig::load`'s deprecation warning and hint-writing
+/// side effects. See `load_aliases_for_listing` for why.
+fn load_project_aliases_silent(repo: &Repository) -> Option<BTreeMap<String, CommandConfig>> {
+ let path = repo.project_config_path().ok().flatten()?;
+ if !path.exists() {
+ return None;
}
- aliases
+ let contents = std::fs::read_to_string(&path).ok()?;
+ let config: ProjectConfig = toml::from_str(&contents).ok()?;
+ Some(config.aliases)
}
/// One-line summary of an alias's command(s) suitable for a help listing.
@@ -989,4 +1031,46 @@ test = "cargo test"
let cfg = cfg_from_toml(r#"cmd = ["echo a", "echo b"]"#);
assert_eq!(format_alias_summary(&cfg), "<2 steps>");
}
+
+ #[test]
+ fn test_render_aliases_section_source_annotations() {
+ // Names unique to one source have no annotation. Names defined in
+ // both sources show two rows (user first, matching runtime order)
+ // and each row carries a source marker so the reader can tell them
+ // apart. Shadowed-by-builtin takes precedence over the source marker.
+ let entries = vec![
+ (
+ "only-user".to_string(),
+ cfg_from_toml(r#"cmd = "echo u""#),
+ AliasSource::User,
+ ),
+ (
+ "only-project".to_string(),
+ cfg_from_toml(r#"cmd = "echo p""#),
+ AliasSource::Project,
+ ),
+ (
+ "shared".to_string(),
+ cfg_from_toml(r#"cmd = "echo from-user""#),
+ AliasSource::User,
+ ),
+ (
+ "shared".to_string(),
+ cfg_from_toml(r#"cmd = "echo from-project""#),
+ AliasSource::Project,
+ ),
+ ];
+ // Caller passes pre-sorted entries; mirror that here.
+ let mut sorted = entries;
+ sorted.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));
+ let rendered = render_aliases_section(&sorted);
+ let rendered = rendered.ansi_strip();
+ insta::assert_snapshot!(rendered, @r"
+ Aliases:
+ only-project echo p
+ only-user echo u
+ shared echo from-user (user)
+ shared echo from-project (project)
+ ");
+ }
}
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index f69dac227..3ed3d8cbf 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -28,7 +28,7 @@ pub(crate) mod statusline;
pub(crate) mod step_commands;
pub(crate) mod worktree;
-pub(crate) use alias::{AliasOptions, step_alias, step_list};
+pub(crate) use alias::{AliasOptions, augment_step_help, step_alias};
pub(crate) use config::{
handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,
handle_config_create, handle_config_show, handle_config_update, handle_hints_clear,
diff --git a/src/help.rs b/src/help.rs
index f01658611..da655dcfc 100644
--- a/src/help.rs
+++ b/src/help.rs
@@ -128,7 +128,7 @@ pub fn maybe_handle_help_with_pager() -> bool {
let mut cmd = cli::build_command();
cmd = cmd.color(clap::ColorChoice::Always); // Force clap to emit ANSI codes
- match cmd.try_get_matches_from_mut(args) {
+ match cmd.try_get_matches_from_mut(&args) {
Ok(_) => false, // Normal args, not help
Err(err) => {
match err.kind() {
@@ -137,6 +137,15 @@ pub fn maybe_handle_help_with_pager() -> bool {
// Use .ansi() to preserve them; .to_string() strips ANSI codes.
let clap_output = err.render().ansi().to_string();
+ // Splice configured aliases into `wt step --help` / `-h`
+ // so the help here matches bare `wt step`. Scoped to the
+ // step subcommand only — other help passes through.
+ let clap_output = if is_help_for_step(&args) {
+ crate::commands::augment_step_help(&clap_output)
+ } else {
+ clap_output
+ };
+
// Render markdown sections (tables, code blocks, prose) with proper wrapping.
// Since we disabled clap's wrapping above, our renderer controls all line breaks.
let width = worktrunk::styling::terminal_width();
@@ -170,6 +179,34 @@ pub fn maybe_handle_help_with_pager() -> bool {
}
}
+/// True when the help being rendered is for `wt step` (no subcommand past
+/// `step`). Used to splice the configured-aliases listing into the help
+/// output, matching the bare `wt step` behavior.
+///
+/// Scans positional args rather than re-parsing with clap because clap's
+/// `DisplayHelp` error doesn't expose the command path at which help was
+/// requested. Handles the two global flags that take values (`-C <path>`,
+/// `--config <path>`) so `wt -C some/path step --help` still classifies.
+/// The `--config=path` attached form needs no special handling — the value
+/// is part of the same arg, which already gets skipped as a flag.
+fn is_help_for_step(args: &[String]) -> bool {
+ const VALUE_FLAGS: &[&str] = &["-C", "--config"];
+ let mut positionals = Vec::new();
+ let mut i = 1; // skip binary name
+ while i < args.len() {
+ let arg = args[i].as_str();
+ if VALUE_FLAGS.contains(&arg) {
+ i += 2; // skip flag and its value
+ continue;
+ }
+ if !arg.starts_with('-') {
+ positionals.push(arg);
+ }
+ i += 1;
+ }
+ positionals == ["step"]
+}
+
/// Get the help reference block with configurable color output.
///
/// `ColorChoice::Always` produces ANSI codes for HTML conversion (web docs).
diff --git a/src/main.rs b/src/main.rs
index e12cb2c4f..5f0a56ac0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -243,10 +243,7 @@ fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {
}
}
-fn handle_step_command(action: Option<StepCommand>) -> anyhow::Result<()> {
- let Some(action) = action else {
- return commands::step_list();
- };
+fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {
match action {
StepCommand::Commit(args) => {
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 297f7c957..a447606bb 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -753,6 +753,33 @@ fn test_step_list_no_aliases(mut repo: TestRepo) {
assert_cmd_snapshot!(make_snapshot_cmd(&repo, "step", &[], Some(&feature_path)));
}
+/// `wt step --help` includes the same Aliases section as bare `wt step`.
+///
+/// Without this, users running `--help` in the normal discovery flow would
+/// see only built-in commands and miss their configured aliases.
+#[cfg(not(windows))]
+#[rstest]
+fn test_step_help_includes_aliases(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+deploy = "make deploy BRANCH={{ branch }}"
+"#,
+ );
+ repo.commit("Add alias config");
+ let feature_path = repo.add_worktree("feature");
+
+ let settings = setup_snapshot_settings(&repo);
+ let _guard = settings.bind_to_scope();
+
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["-h"],
+ Some(&feature_path)
+ ));
+}
+
/// Declining approval prevents alias execution
#[rstest]
fn test_alias_approval_decline(mut repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
index f8fe8142e..6d1726776 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
@@ -36,7 +36,7 @@ wt step - Run individual operations
The building blocks of wt merge — commit, squash, rebase, push — plus standalone utilities.
-Usage: wt step [OPTIONS] [COMMAND]
+Usage: wt step [OPTIONS] <COMMAND>
Commands:
commit Stage and commit with LLM-generated message
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
index c73b65b0b..99a627881 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
@@ -34,7 +34,7 @@ exit_code: 0
----- stderr -----
wt step - Run individual operations
-Usage: wt step [OPTIONS] [COMMAND]
+Usage: wt step [OPTIONS] <COMMAND>
Commands:
commit Stage and commit with LLM-generated message
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap b/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap
new file mode 100644
index 000000000..b67b42ed3
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_help_includes_aliases.snap
@@ -0,0 +1,73 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - step
+ - "-h"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+wt step - Run individual operations
+
+Usage: wt step [OPTIONS] <COMMAND>
+
+Commands:
+ commit Stage and commit with LLM-generated message
+ squash Squash commits since branching
+ rebase Rebase onto target
+ push Fast-forward target to current branch
+ diff Show all changes since branching
+ copy-ignored Copy gitignored files to another worktree
+ eval [experimental] Evaluate a template expression
+ for-each [experimental] Run command in each worktree
+ promote [experimental] Swap a branch into the main worktree
+ prune [experimental] Remove worktrees merged into the default branch
+ relocate [experimental] Move worktrees to expected paths
+
+Aliases:
+ deploy make deploy BRANCH={{ branch }}
+
+Options:
+ -h, --help Print help (see more with '--help')
+
+Global Options:
+ -C <path> Working directory for this command
+ --config <path> User config file path
+ -v, --verbose... Verbose output (-v: hooks, templates; -vv: debug report)
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap b/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap
index 413c8194d..f443d3f43 100644
--- a/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap
@@ -45,7 +45,7 @@ exit_code: 0
----- stderr -----
wt step - Run individual operations
-Usage: wt step [OPTIONS] [COMMAND]
+Usage: wt step [OPTIONS] <COMMAND>
Commands:
commit Stage and commit with LLM-generated message
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap b/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap
index 252b37601..06687a516 100644
--- a/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap
@@ -45,7 +45,7 @@ exit_code: 0
----- stderr -----
wt step - Run individual operations
-Usage: wt step [OPTIONS] [COMMAND]
+Usage: wt step [OPTIONS] <COMMAND>
Commands:
commit Stage and commit with LLM-generated message
@@ -60,10 +60,10 @@ Usage: wt step [OPTIONS] [COMMAND]
prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
-Aliases:
- deploy make deploy BRANCH={{ branch }}
- port echo http://localhost:{{ branch | hash_port }}
- squash this shadows the built-in (shadowed by built-in)
+Aliases:
+ deploy make deploy BRANCH={{ branch }}
+ port echo http://localhost:{{ branch | hash_port }}
+ squash this shadows the built-in (shadowed by built-in)
Options:
-h, --help Print help (see more with '--help')