Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(step): list configured aliases in `wt step` (#2131)
Maximilian Roos371528e4cd5c
diff --git a/docs/content/step.md b/docs/content/step.mdindex cc1e1a525..6855d8bf9 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -48,7 +48,7 @@ wt step - Run individual operationsThe 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>[COMMAND]</span><b><span class=g>Commands:</span></b><b><span class=c>commit</span></b> Stage and commit with LLM-generated messagediff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex 21f2b592a..1119ca8fe 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -41,7 +41,7 @@ wt step - Run individual operationsThe 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 messagediff --git a/src/cli/mod.rs b/src/cli/mod.rsindex e71b370a1..ef36c9f2d 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -47,7 +47,7 @@ pub(super) fn parse_vars_assignment(s: &str) -> Result<(String, String), String>}/// Custom styles for help output - matches worktrunk's color scheme-fn help_styles() -> Styles {+pub(crate) fn help_styles() -> Styles {Styles::styled().header(anstyle::Style::new()@@ -1185,7 +1185,7 @@ Alias names that match a built-in step command (`commit`, `squash`, etc.) are sh)]Step {#[command(subcommand)]- action: StepCommand,+ action: Option<StepCommand>,},/// Run configured hooksdiff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 815d87930..6c117255b 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -45,7 +45,7 @@//! the EXEC directive file is scrubbed so alias bodies cannot inject//! arbitrary shell into the interactive session.-use std::collections::HashMap;+use std::collections::{BTreeMap, HashMap};use anyhow::{Context, bail};use color_print::cformat;@@ -431,6 +431,164 @@ impl AliasExecCtx<'_> {}}+/// Render `wt step` help and list any configured aliases.+///+/// Invoked when `wt step` is run with no subcommand — gives users one place+/// to discover both built-in steps and aliases. Unlike `step_alias`, this+/// tolerates running outside a repository: user-config aliases still list,+/// project-config aliases just get skipped.+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}")),+ };++ let aliases = load_aliases_for_listing();+ if aliases.is_empty() {+ eprint!("{help}");+ return Ok(());+ }++ // Place the Aliases section right after Commands so it sits next to the+ // built-ins it extends. Clap has no template-level hook for inserting+ // between sections, so we splice around the `Options:` heading in the+ // rendered output. The search prefix is derived from the same style+ // clap uses (our `help_styles().get_header()`), so if the header+ // styling changes both sides move together.+ let aliases_section = render_aliases_section(&aliases);+ let options_heading = format!(+ "{}Options:",+ 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..]);+ }+ None => {+ // Clap's styling changed; fall back to appending so we don't+ // silently drop the aliases list.+ eprint!("{help}");+ eprintln!();+ eprint!("{aliases_section}");+ }+ }++ Ok(())+}++/// Format the list of aliases as a styled help section.+///+/// Matches clap's "Commands:" / "Options:" styling (bold+green heading,+/// 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 {+ use std::fmt::Write as _;++ 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 mut first = true;+ for (name, cfg) in aliases {+ if !first {+ out.push('\n');+ }+ first = false;+ let padding = " ".repeat(name_width - name.len());+ let summary = format_alias_summary(cfg);+ let suffix = if BUILTIN_STEP_COMMANDS.contains(&name.as_str()) {+ cformat!(" <yellow>(shadowed by built-in)</>")+ } else {+ String::new()+ };+ let _ = write!(+ out,+ " {name_styled}{padding} {summary}{suffix}",+ name_styled = cformat!("<bold><cyan>{name}</></>"),+ );+ }+ out+}++/// Load merged aliases (user + project) for display.+///+/// 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);+ }+ aliases+}++/// One-line summary of an alias's command(s) suitable for a help listing.+///+/// Single-command aliases show the template's first line (with `…` if the+/// template spans multiple lines). Pipelines show the shared named-step+/// summary used by the "Running alias" announcement.+fn format_alias_summary(cfg: &CommandConfig) -> String {+ // `is_pipeline()` is `steps.len() > 1`, but a single-step concurrent+ // alias (one `HookStep::Concurrent` holding several commands) would+ // fall into the else branch and hide all but the first command. Count+ // actual commands instead.+ if cfg.commands().count() > 1 {+ let step_names: Vec<Vec<Option<&str>>> = cfg+ .steps()+ .iter()+ .map(|step| match step {+ HookStep::Single(cmd) => vec![cmd.name.as_deref()],+ HookStep::Concurrent(cmds) => cmds.iter().map(|c| c.name.as_deref()).collect(),+ })+ .collect();+ let summary = format_pipeline_summary_from_names(&step_names, |n| n.to_string(), |_| None);+ if summary.is_empty() {+ format!("<{} steps>", cfg.commands().count())+ } else {+ summary+ }+ } else {+ let cmd = cfg+ .commands()+ .next()+ .expect("CommandConfig always contains at least one command");+ let first = cmd.template.lines().next().unwrap_or("").trim_end();+ if cmd.template.lines().count() > 1 {+ format!("{first}…")+ } else {+ first.to_string()+ }+ }+}+#[cfg(test)]mod tests {use super::*;@@ -480,6 +638,58 @@ test = "cargo test"insta::assert_snapshot!(msg.ansi_strip(), @"Running alias check: build, test");}+ #[test]+ fn test_format_alias_summary_single_command() {+ let cfg = cfg_from_toml(r#"cmd = "echo hello""#);+ assert_eq!(format_alias_summary(&cfg), "echo hello");+ }++ #[test]+ fn test_format_alias_summary_multiline_gets_ellipsis() {+ let cfg = cfg_from_toml(+ r#"cmd = """+git fetch --all --prune+git rebase @{u}+""""#,+ );+ assert_eq!(format_alias_summary(&cfg), "git fetch --all --prune…");+ }++ #[test]+ fn test_format_alias_summary_pipeline_named() {+ let cfg = cfg_from_toml(+ r#"+cmd = [+ { install = "npm install" },+ { build = "npm run build", lint = "npm run lint" },+]+"#,+ );+ assert_eq!(format_alias_summary(&cfg), "install; build, lint");+ }++ #[test]+ fn test_format_alias_summary_concurrent_named() {+ // Single-step concurrent form: `[aliases.check]\nbuild=…\ntest=…`+ // — one step, multiple commands. Must use the pipeline formatter,+ // not fall back to "show first command's template".+ let cfg = cfg_from_toml(+ r#"+[cmd]+build = "cargo build"+test = "cargo test"+"#,+ );+ assert_eq!(format_alias_summary(&cfg), "build, test");+ }++ #[test]+ fn test_format_alias_summary_pipeline_all_unnamed() {+ // Anonymous pipeline entries fall back to a step count.+ let cfg = cfg_from_toml(r#"cmd = ["echo a", "echo b"]"#);+ assert_eq!(format_alias_summary(&cfg), "<2 steps>");+ }+#[test]fn test_format_alias_announcement_pipeline_named() {// Pipeline: serial named step then concurrent named step.diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 510e1bbd5..f69dac227 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};+pub(crate) use alias::{AliasOptions, step_alias, step_list};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/main.rs b/src/main.rsindex 5f0a56ac0..e12cb2c4f 100644--- a/src/main.rs+++ b/src/main.rs@@ -243,7 +243,10 @@ fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {}}-fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {+fn handle_step_command(action: Option<StepCommand>) -> anyhow::Result<()> {+ let Some(action) = action else {+ return commands::step_list();+ };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.rsindex c29f8b070..297f7c957 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -716,6 +716,43 @@ deploy = [);}+/// `wt step` with no subcommand lists built-in steps plus configured aliases.+///+/// Skipped on Windows: clap renders `[experimental]` subcommand tags+/// differently (markdown escaping), same reason `tests/integration_tests/help.rs`+/// is Windows-gated.+#[cfg(not(windows))]+#[rstest]+fn test_step_list_with_aliases(mut repo: TestRepo) {+ repo.write_project_config(+ r#"+[aliases]+deploy = "make deploy BRANCH={{ branch }}"+port = "echo http://localhost:{{ branch | hash_port }}"+squash = "this shadows the built-in"+"#,+ );+ 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", &[], Some(&feature_path)));+}++/// `wt step` without configured aliases still works — just prints help.+#[cfg(not(windows))]+#[rstest]+fn test_step_list_no_aliases(mut repo: TestRepo) {+ 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", &[], 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.snapindex 735c6b0e5..5af0090a2 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[0mThe building blocks of [1mwt merge[0m — commit, squash, rebase, push — plus standalone utilities.[0m-Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m<COMMAND>[0m+Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m[COMMAND][0m[1m[32mCommands:[0m[1m[36mcommit[0m Stage and commit with LLM-generated messagediff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snapindex 99a627881..c73b65b0b 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: [1m[36mwt step[0m [36m[OPTIONS][0m [36m<COMMAND>[0m+Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m[COMMAND][0m[1m[32mCommands:[0m[1m[36mcommit[0m Stage and commit with LLM-generated messagediff --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.snapnew file mode 100644index 000000000..413c8194d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__step_list_no_aliases.snap@@ -0,0 +1,69 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - step+ 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: [1m[36mwt step[0m [36m[OPTIONS][0m [36m[COMMAND]++[1m[32mCommands:+ [1m[36mcommit[0m Stage and commit with LLM-generated message+ [1m[36msquash[0m Squash commits since branching+ [1m[36mrebase[0m Rebase onto target+ [1m[36mpush[0m Fast-forward target to current branch+ [1m[36mdiff[0m Show all changes since branching+ [1m[36mcopy-ignored[0m Copy gitignored files to another worktree+ [1m[36meval[0m [experimental] Evaluate a template expression+ [1m[36mfor-each[0m [experimental] Run command in each worktree+ [1m[36mpromote[0m [experimental] Swap a branch into the main worktree+ [1m[36mprune[0m [experimental] Remove worktrees merged into the default branch+ [1m[36mrelocate[0m [experimental] Move worktrees to expected paths++[1m[32mOptions:+ [1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')++[1m[32mGlobal Options:+ [1m[36m-C[0m[36m [0m[36m<path>[0m Working directory for this command+ [1m[36m--config[0m[36m [0m[36m<path>[0m User config file path+ [1m[36m-v[0m, [1m[36m--verbose[0m[36m...[0m Verbose output (-v: hooks, templates; -vv: debug report)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.snapnew file mode 100644index 000000000..252b37601--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__step_list_with_aliases.snap@@ -0,0 +1,74 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - step+ 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: [1m[36mwt step[0m [36m[OPTIONS][0m [36m[COMMAND]++[1m[32mCommands:+ [1m[36mcommit[0m Stage and commit with LLM-generated message+ [1m[36msquash[0m Squash commits since branching+ [1m[36mrebase[0m Rebase onto target+ [1m[36mpush[0m Fast-forward target to current branch+ [1m[36mdiff[0m Show all changes since branching+ [1m[36mcopy-ignored[0m Copy gitignored files to another worktree+ [1m[36meval[0m [experimental] Evaluate a template expression+ [1m[36mfor-each[0m [experimental] Run command in each worktree+ [1m[36mpromote[0m [experimental] Swap a branch into the main worktree+ [1m[36mprune[0m [experimental] Remove worktrees merged into the default branch+ [1m[36mrelocate[0m [experimental] Move worktrees to expected paths++[32m[1mAliases:[39m[22m+ [36m[1mdeploy[39m[22m make deploy BRANCH={{ branch }}+ [36m[1mport[39m[22m echo http://localhost:{{ branch | hash_port }}+ [36m[1msquash[39m[22m this shadows the built-in [33m(shadowed by built-in)[39m++[1m[32mOptions:+ [1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')++[1m[32mGlobal Options:+ [1m[36m-C[0m[36m [0m[36m<path>[0m Working directory for this command+ [1m[36m--config[0m[36m [0m[36m<path>[0m User config file path+ [1m[36m-v[0m, [1m[36m--verbose[0m[36m...[0m Verbose output (-v: hooks, templates; -vv: debug report)