Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add `--branch` flag to `wt step commit` (#1750)
worktrunk-bot9160162af92b
diff --git a/docs/content/step.md b/docs/content/step.mdindex efec8fdff..c1b9eef56 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -121,6 +121,9 @@ wt step commit - Stage and commit with LLM-generated messageUsage: <b><span class=c>wt step commit</span></b> <span class=c>[OPTIONS]</span><b><span class=g>Options:</span></b>+ <b><span class=c>-b</span></b>, <b><span class=c>--branch</span></b><span class=c> <BRANCH></span>+ Branch to operate on (defaults to current worktree)+<b><span class=c>--stage</span></b><span class=c> <STAGE></span>What to stage before committing [default: all]diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex 5ebfb7385..e339ce397 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -119,6 +119,9 @@ wt step commit - Stage and commit with LLM-generated messageUsage: <b><span class=c>wt step commit</span></b> <span class=c>[OPTIONS]</span><b><span class=g>Options:</span></b>+ <b><span class=c>-b</span></b>, <b><span class=c>--branch</span></b><span class=c> <BRANCH></span>+ Branch to operate on (defaults to current worktree)+<b><span class=c>--stage</span></b><span class=c> <STAGE></span>What to stage before committing [default: all]diff --git a/src/cli/step.rs b/src/cli/step.rsindex 1f37c7c7c..39f965f0d 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -45,6 +45,10 @@ $ wt step commit --show-prompt | llm -m gpt-5-nano"#)]Commit {+ /// Branch to operate on (defaults to current worktree)+ #[arg(short, long, add = crate::completion::worktree_only_completer())]+ branch: Option<String>,+/// Skip approval prompts#[arg(short, long, help_heading = "Automation")]yes: bool,diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex be8cf3b2e..bdd990a75 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -10,7 +10,7 @@ use super::command_executor::CommandContext;use super::hooks::{HookCommandSpec, HookFailureStrategy, prepare_background_hooks, spawn_prepared_hooks,};-use super::repository_ext::RepositoryCliExt;+use super::repository_ext::warn_about_untracked_files;// Re-export StageMode from config for use by CLIpub use worktrunk::config::StageMode;@@ -197,24 +197,27 @@ impl CommitOptions<'_> {.map_err(worktrunk::git::add_hook_skip_hint)?;}+ // Use the worktree path from context — this is the target worktree when+ // --branch is specified, or the current worktree otherwise.+ let wt = self.ctx.repo.worktree_at(self.ctx.worktree_path);+if self.warn_about_untracked && self.stage_mode == StageMode::All {- self.ctx.repo.warn_if_auto_staging_untracked()?;+ let status = wt+ .run_command(&["status", "--porcelain", "-z"])+ .context("Failed to get status")?;+ warn_about_untracked_files(&status)?;}// Stage changes based on modematch self.stage_mode {StageMode::All => {// Stage everything: tracked modifications + untracked files- self.ctx- .repo- .run_command(&["add", "-A"])+ wt.run_command(&["add", "-A"]).context("Failed to stage changes")?;}StageMode::Tracked => {// Stage tracked modifications only (no untracked files)- self.ctx- .repo- .run_command(&["add", "-u"])+ wt.run_command(&["add", "-u"]).context("Failed to stage tracked changes")?;}StageMode::None => {@@ -223,7 +226,6 @@ impl CommitOptions<'_> {}let effective_config = self.ctx.commit_generation();- let wt = self.ctx.repo.current_worktree();CommitGenerator::new(&effective_config).commit_staged_changes(&wt,true, // show_progressdiff --git a/src/commands/context.rs b/src/commands/context.rsindex b90b70d92..c6a1acfa3 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -25,18 +25,40 @@ pub struct CommandEnv {}impl CommandEnv {- /// Load the command environment for a specific action.+ /// Load the command environment for the current worktree.///- /// `action` describes what command is running (e.g., "merge", "squash").- /// Used in error messages when the environment can't be loaded.- pub fn for_action(action: &str, config: UserConfig) -> anyhow::Result<Self> {+ /// Resolves the worktree path from the current directory. The branch is+ /// populated when available but not required — commands that need a branch+ /// should call `require_branch()` after construction.+ pub fn for_action(_action: &str, config: UserConfig) -> anyhow::Result<Self> {let repo = Repository::current()?;- let worktree_path = repo.current_worktree().root()?;- let branch = repo.require_current_branch(action)?;+ let current_wt = repo.current_worktree();+ let worktree_path = current_wt.root()?;+ let branch = current_wt+ .branch()+ .context("Failed to determine current branch")?;++ Ok(Self {+ repo,+ branch,+ config,+ worktree_path,+ })+ }++ /// Load the command environment for a named worktree (by branch name).+ ///+ /// Resolves the worktree path from the branch name rather than using+ /// the current working directory.+ pub fn for_branch(_action: &str, config: UserConfig, branch: &str) -> anyhow::Result<Self> {+ let repo = Repository::current()?;+ let worktree_path = repo+ .worktree_for_branch(branch)?+ .ok_or_else(|| anyhow::anyhow!("no worktree for branch '{branch}'"))?;Ok(Self {repo,- branch: Some(branch),+ branch: Some(branch.to_string()),config,worktree_path,})diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex c9924b13e..0e7e7e4b7 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -457,7 +457,7 @@ pub(crate) fn check_not_default_branch(}/// Warn about untracked files that will be auto-staged.-fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {+pub(crate) fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<()> {let files = parse_untracked_files(status_output);if files.is_empty() {return Ok(());diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 415521dca..234a93ca3 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -48,6 +48,7 @@ use crate::output::handle_remove_output;////// `stage` is the CLI-provided stage mode. If None, uses the effective config default.pub fn step_commit(+ branch: Option<String>,yes: bool,verify: bool,stage: Option<StageMode>,@@ -69,7 +70,10 @@ pub fn step_commit(// One-time LLM setup prompt (errors logged internally; don't block commit)let _ = crate::output::prompt_commit_generation(&mut config);- let env = CommandEnv::for_action("commit", config)?;+ let env = match branch {+ Some(ref b) => CommandEnv::for_branch("commit", config, b)?,+ None => CommandEnv::for_action("commit", config)?,+ };let ctx = env.context(yes);// CLI flag overrides config valuediff --git a/src/main.rs b/src/main.rsindex 733780f1a..7efd3eb89 100644--- a/src/main.rs+++ b/src/main.rs@@ -254,11 +254,12 @@ fn handle_hook_command(action: HookCommand) -> anyhow::Result<()> {fn handle_step_command(action: StepCommand) -> anyhow::Result<()> {match action {StepCommand::Commit {+ branch,yes,verify,stage,show_prompt,- } => step_commit(yes, verify, stage, show_prompt),+ } => step_commit(branch, yes, verify, stage, show_prompt),StepCommand::Squash {target,yes,diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 210c747a2..f1d245004 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1849,6 +1849,90 @@ fn test_step_commit_nothing_to_commit(repo: TestRepo) {});}+#[rstest]+fn test_step_commit_branch_flag(mut repo: TestRepo) {+ // Create a feature worktree and add a dirty file there+ let feature_wt = repo.add_worktree("feature");+ fs::write(feature_wt.join("feature_file.txt"), "feature content")+ .expect("Failed to write file");++ // Run step commit from the main worktree, targeting the feature branch+ assert_cmd_snapshot!({+ let mut cmd = make_snapshot_cmd(&repo, "step", &[], None); // cwd = main worktree+ cmd.arg("commit")+ .args(["--branch", "feature", "--no-verify"]);+ cmd.env(+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",+ "cat >/dev/null && echo 'feat: add feature file'",+ );+ cmd+ });++ // Verify the commit happened in the feature worktree+ let log_output = {+ let output = repo+ .git_command()+ .args(["log", "--oneline", "-1"])+ .current_dir(&feature_wt)+ .run()+ .unwrap();+ String::from_utf8_lossy(&output.stdout).trim().to_string()+ };+ assert!(+ log_output.contains("feat: add feature file"),+ "Commit should appear in feature worktree, got: {log_output}"+ );+}++#[rstest]+fn test_step_commit_branch_flag_nonexistent(repo: TestRepo) {+ // Try to commit on a branch that has no worktree+ assert_cmd_snapshot!({+ let mut cmd = make_snapshot_cmd(&repo, "step", &[], None);+ cmd.arg("commit").args(["--branch", "nonexistent"]);+ cmd+ });+}++#[rstest]+fn test_step_commit_detached_head(mut repo: TestRepo) {+ // Detach HEAD in a worktree, then commit — should work since commit+ // only needs a worktree path, not a branch name.+ let feature_wt = repo.add_worktree("feature");++ // Detach HEAD in the feature worktree+ repo.detach_head_in_worktree("feature");++ // Create a file to commit+ fs::write(feature_wt.join("detached_file.txt"), "detached content")+ .expect("Failed to write file");++ assert_cmd_snapshot!({+ let mut cmd = make_snapshot_cmd(&repo, "step", &[], Some(&feature_wt));+ cmd.arg("commit").args(["--no-verify"]);+ cmd.env(+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",+ "cat >/dev/null && echo 'chore: commit in detached state'",+ );+ cmd+ });++ // Verify the commit actually landed+ let log_output = {+ let output = repo+ .git_command()+ .args(["log", "--oneline", "-1"])+ .current_dir(&feature_wt)+ .run()+ .unwrap();+ String::from_utf8_lossy(&output.stdout).trim().to_string()+ };+ assert!(+ log_output.contains("chore: commit in detached state"),+ "Commit should appear in detached worktree, got: {log_output}"+ );+}+// =============================================================================// Error message snapshot tests// =============================================================================diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snapnew file mode 100644index 000000000..47b27e3d8--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snap@@ -0,0 +1,53 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - step+ - commit+ - "--branch"+ - feature+ - "--no-verify"+ 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: ""+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_COMMIT__GENERATION__COMMAND: "cat >/dev/null && echo 'feat: add feature file'"+ 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_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[33m▲[39m [33mAuto-staging 1 untracked path:[39m+[107m [0m feature_file.txt+[36m◎[39m [36mGenerating commit message and committing changes...[39m+[107m [0m [1mfeat: add feature file[22m+[32m✓[39m [32mCommitted changes @ [2m[HASH][22m[39mdiff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag_nonexistent.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag_nonexistent.snapnew file mode 100644index 000000000..178ff828a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag_nonexistent.snap@@ -0,0 +1,47 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - step+ - commit+ - "--branch"+ - nonexistent+ 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: ""+ 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_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mno worktree for branch 'nonexistent'[39mdiff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_detached_head.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_detached_head.snapnew file mode 100644index 000000000..89a24c79c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_detached_head.snap@@ -0,0 +1,51 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - step+ - commit+ - "--no-verify"+ 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: ""+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_COMMIT__GENERATION__COMMAND: "cat >/dev/null && echo 'chore: commit in detached state'"+ 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_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[33m▲[39m [33mAuto-staging 1 untracked path:[39m+[107m [0m detached_file.txt+[36m◎[39m [36mGenerating commit message and committing changes... [90m(1 file, [32m+1[39m[39m[90m)[39m[39m+[107m [0m [1mchore: commit in detached state[22m+[32m✓[39m [32mCommitted changes @ [2m[HASH][22m[39m