Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Add `--execute/-x` flag to `switch` command
Maximilian Roos665855c89add
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 2ee67fc9b..c032c0443 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -110,6 +110,7 @@ pub fn handle_switch(branch: &str,create: bool,base: Option<&str>,+ execute: Option<&str>,config: &WorktrunkConfig,) -> Result<SwitchResult, GitError> {let repo = Repository::current();@@ -134,6 +135,9 @@ pub fn handle_switch(// Check if worktree already exists for this branchmatch repo.worktree_for_branch(branch)? {Some(existing_path) if existing_path.exists() => {+ if let Some(cmd) = execute {+ execute_command_in_worktree(&existing_path, cmd)?;+ }// Canonicalize the path for cleaner displaylet canonical_existing_path = existing_path.canonicalize().unwrap_or(existing_path);return Ok(SwitchResult::ExistingWorktree(canonical_existing_path));@@ -175,6 +179,10 @@ pub fn handle_switch(repo.run_command(&args).map_err(|e| GitError::CommandFailed(format!("Failed to create worktree: {}", e)))?;+ if let Some(cmd) = execute {+ execute_command_in_worktree(&worktree_path, cmd)?;+ }+// Canonicalize the path for cleaner displaylet canonical_path = worktree_path.canonicalize().unwrap_or(worktree_path);@@ -184,6 +192,42 @@ pub fn handle_switch(})}+/// Execute a command in the specified worktree directory+fn execute_command_in_worktree(+ worktree_path: &std::path::Path,+ command: &str,+) -> Result<(), GitError> {+ use std::io::Write;+ use std::process::Command;++ // Use platform-specific shell+ #[cfg(target_os = "windows")]+ let (shell, shell_arg) = ("cmd", "/C");+ #[cfg(not(target_os = "windows"))]+ let (shell, shell_arg) = ("sh", "-c");++ let output = Command::new(shell)+ .arg(shell_arg)+ .arg(command)+ .current_dir(worktree_path)+ .output()+ .map_err(|e| GitError::CommandFailed(format!("Failed to execute command: {}", e)))?;++ // Forward stdout/stderr to user+ std::io::stdout().write_all(&output.stdout).ok();+ std::io::stderr().write_all(&output.stderr).ok();++ if !output.status.success() {+ return Err(GitError::CommandFailed(format!(+ "Command '{}' exited with status: {}",+ command,+ output.status.code().unwrap_or(-1)+ )));+ }++ Ok(())+}+pub fn handle_remove() -> Result<RemoveResult, GitError> {let repo = Repository::current();diff --git a/src/main.rs b/src/main.rsindex ddb705113..2bac7d853 100644--- a/src/main.rs+++ b/src/main.rs@@ -81,6 +81,10 @@ enum Commands {#[arg(short = 'b', long)]base: Option<String>,+ /// Execute command after switching+ #[arg(short = 'x', long)]+ execute: Option<String>,+/// Use internal mode (outputs directives for shell wrapper)#[arg(long, hide = true)]internal: bool,@@ -163,20 +167,37 @@ fn main() {branch,create,base,+ execute,internal,- } => WorktrunkConfig::load()- .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))- .and_then(|config| {- handle_switch(&branch, create, base.as_deref(), &config).map(|result| {- if internal {- if let Some(output) = result.format_internal_output(&branch) {- println!("{}", output);- }- } else if let Some(output) = result.format_user_output(&branch) {- println!("{}", output);- }- })- }),+ } => {+ // Validate that --execute is not used with --internal+ if execute.is_some() && internal {+ Err(GitError::CommandFailed(+ "--execute flag cannot be used with --internal mode".to_string(),+ ))+ } else {+ WorktrunkConfig::load()+ .map_err(|e| GitError::CommandFailed(format!("Failed to load config: {}", e)))+ .and_then(|config| {+ handle_switch(+ &branch,+ create,+ base.as_deref(),+ execute.as_deref(),+ &config,+ )+ .map(|result| {+ if internal {+ if let Some(output) = result.format_internal_output(&branch) {+ println!("{}", output);+ }+ } else if let Some(output) = result.format_user_output(&branch) {+ println!("{}", output);+ }+ })+ })+ }+ }Commands::Remove { internal } => handle_remove().map(|result| {if internal {if let Some(output) = result.format_internal_output() {diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex e041ade53..904c47a76 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -110,3 +110,84 @@ fn test_switch_error_missing_worktree_directory() {// Try to switch to the missing worktree (should fail)snapshot_switch("switch_error_missing_directory", &repo, &["missing-wt"]);}++#[test]+fn test_switch_execute_success() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ snapshot_switch(+ "switch_execute_success",+ &repo,+ &["--create", "exec-test", "--execute", "echo 'test output'"],+ );+}++#[test]+fn test_switch_execute_creates_file() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Use platform-specific command+ #[cfg(target_os = "windows")]+ let create_file_cmd = "echo test > test.txt";+ #[cfg(not(target_os = "windows"))]+ let create_file_cmd = "echo 'test content' > test.txt";++ snapshot_switch(+ "switch_execute_creates_file",+ &repo,+ &["--create", "file-test", "--execute", create_file_cmd],+ );+}++#[test]+fn test_switch_execute_failure() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ snapshot_switch(+ "switch_execute_failure",+ &repo,+ &["--create", "fail-test", "--execute", "exit 1"],+ );+}++#[test]+fn test_switch_execute_with_existing_worktree() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create a worktree first+ repo.add_worktree("existing-exec", "existing-exec");++ // Use platform-specific command+ #[cfg(target_os = "windows")]+ let create_file_cmd = "echo existing > existing.txt";+ #[cfg(not(target_os = "windows"))]+ let create_file_cmd = "echo 'existing worktree' > existing.txt";++ snapshot_switch(+ "switch_execute_existing",+ &repo,+ &["existing-exec", "--execute", create_file_cmd],+ );+}++#[test]+fn test_switch_execute_with_internal_error() {+ let repo = TestRepo::new();+ repo.commit("Initial commit");++ snapshot_switch(+ "switch_execute_internal_error",+ &repo,+ &[+ "--create",+ "internal-test",+ "--execute",+ "echo test",+ "--internal",+ ],+ );+}diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 0ef1c31a9..8302b8877 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -265,7 +265,7 @@ _wt() {return 0;;wt__switch)- opts="-c -b -h --create --base --help <BRANCH>"+ opts="-c -b -x -h --create --base --execute --help <BRANCH>"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0@@ -279,6 +279,14 @@ _wt() {COMPREPLY=($(compgen -f "${cur}"))return 0;;+ --execute)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ -x)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;*)COMPREPLY=();;diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snapindex cfb6d42cd..09ed225b7 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap@@ -267,7 +267,7 @@ _wt() {return 0;;wt__switch)- opts="-c -b -h --create --base --help <BRANCH>"+ opts="-c -b -x -h --create --base --execute --help <BRANCH>"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0@@ -281,6 +281,14 @@ _wt() {COMPREPLY=($(compgen -f "${cur}"))return 0;;+ --execute)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ -x)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;*)COMPREPLY=();;diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 08f446f1a..a0cea1644 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -120,6 +120,7 @@ json\t'JSON format'"complete -c wt -n "__fish_wt_using_subcommand list" -l branches -d 'Also display branches that don\'t have worktrees'complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help (see more with \'--help\')'complete -c wt -n "__fish_wt_using_subcommand switch" -s b -l base -d 'Base branch to create from (only with --create)' -r+complete -c wt -n "__fish_wt_using_subcommand switch" -s x -l execute -d 'Execute command after switching' -rcomplete -c wt -n "__fish_wt_using_subcommand switch" -s c -l create -d 'Create a new branch'complete -c wt -n "__fish_wt_using_subcommand switch" -s h -l help -d 'Print help'complete -c wt -n "__fish_wt_using_subcommand remove" -s h -l help -d 'Print help'diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex eaa2fbb7b..3bb2bd70a 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -131,6 +131,8 @@ json\:"JSON format"))' \_arguments "${_arguments_options[@]}" : \'-b+[Base branch to create from (only with --create)]:BASE:_default' \'--base=[Base branch to create from (only with --create)]:BASE:_default' \+'-x+[Execute command after switching]:EXECUTE:_default' \+'--execute=[Execute command after switching]:EXECUTE:_default' \'-c[Create a new branch]' \'--create[Create a new branch]' \'-h[Print help]' \diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snapnew file mode 100644index 000000000..b523e0a53--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_creates_file.snap@@ -0,0 +1,28 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - file-test+ - "--execute"+ - "echo 'test content' > test.txt"+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+Created new branch and worktree for 'file-test' at [REPO].file-test+Note: Use 'wt switch' (with shell integration) for automatic cd++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snapnew file mode 100644index 000000000..c1f855829--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_existing.snap@@ -0,0 +1,25 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - existing-exec+ - "--execute"+ - "echo 'existing worktree' > existing.txt"+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snapnew file mode 100644index 000000000..a2ed7228e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_failure.snap@@ -0,0 +1,27 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - fail-test+ - "--execute"+ - exit 1+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+Command 'exit 1' exited with status: 1diff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_internal_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_internal_error.snapnew file mode 100644index 000000000..ff9ac1f8a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_internal_error.snap@@ -0,0 +1,28 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - internal-test+ - "--execute"+ - echo test+ - "--internal"+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+--execute flag cannot be used with --internal modediff --git a/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snap b/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snapnew file mode 100644index 000000000..9e5767d8b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_execute_success.snap@@ -0,0 +1,29 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - exec-test+ - "--execute"+ - "echo 'test output'"+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+test output+Created new branch and worktree for 'exec-test' at [REPO].exec-test+Note: Use 'wt switch' (with shell integration) for automatic cd++----- stderr -----