Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add upfront validation for target refs in commands (#639)
Maximilian Roos0d19ad608478
diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 461fa8235..b2d3434a1 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -95,8 +95,8 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// --no-commit implies --no-squashlet squash_enabled = squash && commit;- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;+ // Get and validate target branch (must be a branch since we're updating it)+ let target_branch = repo.require_target_branch(target)?;// Worktree for target is optional: if present we use it for safety checks and as destination.let target_worktree_path = repo.worktree_for_branch(&target_branch)?;diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 32f133946..100a708f5 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -102,8 +102,8 @@ pub fn handle_squash(let ctx = env.context(yes);let generator = CommitGenerator::new(&env.config.commit_generation);- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;+ // Get and validate target ref (any commit-ish for merge-base calculation)+ let target_branch = repo.require_target_ref(target)?;// Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identicallymatch stage_mode {@@ -295,8 +295,8 @@ pub fn step_show_squash_prompt() -> anyhow::Result<()> {let repo = Repository::current()?;- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;+ // Get and validate target ref (any commit-ish for merge-base calculation)+ let target_branch = repo.require_target_ref(target)?;// Get current branchlet current_branch = repo@@ -346,8 +346,8 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {let repo = Repository::current()?;- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;+ // Get and validate target ref (any commit-ish for rebase)+ let target_branch = repo.require_target_ref(target)?;// Check if already up-to-date (linear extension of target, no merge commits)if repo.is_rebased_onto(&target_branch)? {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 23cce3f6e..eaa84f1cc 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -938,8 +938,8 @@ pub fn handle_push() -> anyhow::Result<()> {let repo = Repository::current()?;- // Get target branch (default to default branch if not provided)- let target_branch = repo.resolve_target_branch(target)?;+ // Get and validate target branch (must be a branch since we're updating it)+ let target_branch = repo.require_target_branch(target)?;// A worktree for the target branch is optional for push:// - If present, we use it to check for overlapping dirty files.diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex 6a6f6d526..9183bbf86 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -221,6 +221,9 @@ impl Repository {/// If target is Some, expands special symbols ("@", "-", "^") via `resolve_worktree_name`./// Otherwise, queries the default branch./// This is a common pattern used throughout commands that accept an optional --target flag.+ ///+ /// Note: This does not validate that the target exists. Use `require_target_branch` or+ /// `require_target_ref` for validation before approval prompts.pub fn resolve_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {match target {Some(b) => self.resolve_worktree_name(b),@@ -233,6 +236,30 @@ impl Repository {}}+ /// Resolve and validate a target that must be a branch.+ ///+ /// Use this for commands that update a branch ref (merge, push).+ /// Validates before approval prompts to avoid wasting user time.+ pub fn require_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {+ let branch = self.resolve_target_branch(target)?;+ if !self.branch_exists(&branch)? {+ return Err(GitError::InvalidReference { reference: branch }.into());+ }+ Ok(branch)+ }++ /// Resolve and validate a target that can be any commit-ish.+ ///+ /// Use this for commands that reference a commit (rebase, squash).+ /// Validates before approval prompts to avoid wasting user time.+ pub fn require_target_ref(&self, target: Option<&str>) -> anyhow::Result<String> {+ let reference = self.resolve_target_branch(target)?;+ if !self.ref_exists(&reference)? {+ return Err(GitError::InvalidReference { reference }.into());+ }+ Ok(reference)+ }+/// Infer the default branch locally (without remote).////// Uses local heuristics when no remote is available:diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 409d92160..7c2e9289c 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1960,3 +1960,57 @@ fn test_step_rebase_already_up_to_date(mut repo: TestRepo) {Some(&feature_wt)));}++// =============================================================================+// Target validation tests+// =============================================================================++#[rstest]+fn test_merge_invalid_target(mut repo: TestRepo) {+ // Create a feature worktree+ let feature_wt = repo.add_worktree("feature");++ // Try to merge into nonexistent branch - should fail with clear error+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "merge",+ &["nonexistent-branch"],+ Some(&feature_wt)+ ));+}++#[rstest]+fn test_step_rebase_invalid_target(mut repo: TestRepo) {+ // Create a feature worktree+ let feature_wt = repo.add_worktree("feature");++ // Try to rebase onto nonexistent ref - should fail with clear error+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["rebase", "nonexistent-ref"],+ Some(&feature_wt)+ ));+}++#[rstest]+fn test_step_rebase_accepts_tag(mut repo: TestRepo) {+ // Create a tag on main+ repo.run_git(&["tag", "v1.0"]);++ // Advance main+ fs::write(repo.root_path().join("after-tag.txt"), "content").unwrap();+ repo.run_git(&["add", "after-tag.txt"]);+ repo.run_git(&["commit", "-m", "After tag"]);++ // Create feature from current main+ let feature_wt = repo.add_worktree("feature");++ // Rebase onto the tag - should work (commit-ish accepted)+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["rebase", "v1.0"],+ Some(&feature_wt)+ ));+}diff --git a/tests/snapshots/integration__integration_tests__merge__merge_invalid_target.snap b/tests/snapshots/integration__integration_tests__merge__merge_invalid_target.snapnew file mode 100644index 000000000..515dc2dbd--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_invalid_target.snap@@ -0,0 +1,36 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - nonexistent-branch+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mBranch [1mnonexistent-branch[22m not found[39m+[2m↳[22m [2mTo create a new branch, run [90mwt switch nonexistent-branch --create[39m; to list branches, run [90mwt list --branches --remotes[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__step_rebase_accepts_tag.snap b/tests/snapshots/integration__integration_tests__merge__step_rebase_accepts_tag.snapnew file mode 100644index 000000000..98337548f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__step_rebase_accepts_tag.snap@@ -0,0 +1,36 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - step+ - rebase+ - v1.0+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[2m○[22m Already up to date with [1mv1.0[22mdiff --git a/tests/snapshots/integration__integration_tests__merge__step_rebase_invalid_target.snap b/tests/snapshots/integration__integration_tests__merge__step_rebase_invalid_target.snapnew file mode 100644index 000000000..348368b60--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__step_rebase_invalid_target.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - step+ - rebase+ - nonexistent-ref+ 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+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mBranch [1mnonexistent-ref[22m not found[39m+[2m↳[22m [2mTo create a new branch, run [90mwt switch nonexistent-ref --create[39m; to list branches, run [90mwt list --branches --remotes[39m[22m