Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Add post-merge hook for project automation
Maximilian Roosc7ca3a805336
diff --git a/.config/wt.toml b/.config/wt.tomlindex ea9fd804f..0955688aa 100644--- a/.config/wt.toml+++ b/.config/wt.toml@@ -24,3 +24,8 @@ echo 'β CoW seeded target/'[pre-merge-check]pre-commit = "pre-commit run --all-files"insta = "cargo insta test"++# Post-merge commands+# These run in the main worktree after successful merge and push+# Available template variables: {repo}, {branch}, {worktree}, {repo_root}, {target}+post-merge-command = "cargo install --path ."diff --git a/README.md b/README.mdindex bdb2adf86..6b01b71aa 100644--- a/README.md+++ b/README.md@@ -128,14 +128,26 @@ Projects can define commands that run automatically when creating or switching t[pre-merge-check]"tests" = "npm test""lint" = "npm run lint"++# Run after successful merge in main worktree (blocking)+[post-merge-command]+"install" = "cargo install --path ."+"deploy" = "scripts/deploy.sh"```+**Hook Types:**++- **`post-create-command`**: Runs sequentially after creating a worktree. Use for setup tasks like installing dependencies.+- **`post-start-command`**: Runs in parallel as background processes after switching to a worktree. Use for dev servers and watchers.+- **`pre-merge-check`**: Runs sequentially before merging. All commands must succeed for the merge to proceed. Use for validation (tests, lints).+- **`post-merge-command`**: Runs sequentially in the main worktree after a successful merge and push. Use for deployment, notifications, or updating global state.+Template variables expand at runtime:- `{repo}` - Repository name- `{branch}` - Current branch- `{worktree}` - Absolute path to worktree- `{repo_root}` - Absolute path to repository root-- `{target}` - Target branch (pre-merge-check only)+- `{target}` - Target branch (pre-merge-check and post-merge-command only)### Available Hooksdiff --git a/src/commands/merge.rs b/src/commands/merge.rsindex d80a056c9..cf39128b0 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -107,6 +107,17 @@ pub fn handle_merge(// Fast-forward push to target branch (reuse handle_push logic)handle_push(Some(&target_branch), false)?;+ // Execute post-merge commands in the main worktree+ let main_worktree_path = repo.main_worktree_root()?;+ execute_post_merge_commands(+ &main_worktree_path,+ &repo,+ &config,+ ¤t_branch,+ &target_branch,+ force,+ )?;+// Finish worktree unless --keep was specifiedif !keep {crate::output::progress(format!("π {CYAN}Cleaning up worktree...{CYAN:#}"))@@ -367,3 +378,73 @@ fn run_pre_merge_checks(Ok(())}++/// Load project configuration with proper error conversion+fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {+ let repo_root = repo.worktree_root()?;+ ProjectConfig::load(&repo_root)+ .map_err(|e| GitError::CommandFailed(format!("Failed to load project config: {}", e)))+}++/// Execute post-merge commands sequentially in the main worktree (blocking)+fn execute_post_merge_commands(+ main_worktree_path: &std::path::Path,+ repo: &Repository,+ config: &WorktrunkConfig,+ branch: &str,+ target_branch: &str,+ force: bool,+) -> Result<(), GitError> {+ use worktrunk::styling::WARNING;++ let project_config = match load_project_config(repo)? {+ Some(cfg) => cfg,+ None => return Ok(()),+ };++ let Some(post_merge_config) = &project_config.post_merge_command else {+ return Ok(());+ };++ let ctx = CommandContext::new(repo, config, branch, main_worktree_path, force);+ let commands = prepare_project_commands(+ post_merge_config,+ "cmd",+ &ctx,+ false,+ &[("target", target_branch)],+ "Post-merge commands",+ |_, command| {+ let dim = AnstyleStyle::new().dimmed();+ eprintln!("{dim}Skipping command: {command}{dim:#}");+ },+ )?;++ if commands.is_empty() {+ return Ok(());+ }++ // Execute each command sequentially in the main worktree+ for prepared in commands {+ use std::io::Write;+ eprintln!("π {CYAN}Executing (post-merge):{CYAN:#}");+ eprint!("{}", format_with_gutter(&prepared.expanded, "", None));+ let _ = std::io::stderr().flush();++ if let Err(e) = execute_command_in_worktree(main_worktree_path, &prepared.expanded) {+ use worktrunk::styling::WARNING_EMOJI;+ let warning_bold = WARNING.bold();+ eprintln!(+ "{WARNING_EMOJI} {WARNING}Command {warning_bold}{name}{warning_bold:#} failed: {e}{WARNING:#}",+ name = prepared.name,+ );+ // Continue with other commands even if one fails+ }+ }++ use std::io::Write;+ let _ = std::io::stdout().flush();+ let _ = std::io::stderr().flush();++ Ok(())+}diff --git a/src/config.rs b/src/config.rsindex 4be00e18e..de4293ca8 100644--- a/src/config.rs+++ b/src/config.rs@@ -97,6 +97,14 @@ pub struct ProjectConfig {/// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`#[serde(default, rename = "pre-merge-check")]pub pre_merge_check: Option<CommandConfig>,++ /// Commands to execute after successful merge in the main worktree (blocking)+ /// Supports string (single command), array (sequential), or table (named, sequential)+ /// Runs after push succeeds but before cleanup+ ///+ /// Available template variables: `{repo}`, `{branch}`, `{worktree}`, `{repo_root}`, `{target}`+ #[serde(default, rename = "post-merge-command")]+ pub post_merge_command: Option<CommandConfig>,}/// Configuration for commands - supports multiple formats@@ -522,6 +530,7 @@ mod tests {assert!(config.post_create_command.is_none());assert!(config.post_start_command.is_none());assert!(config.pre_merge_check.is_none());+ assert!(config.post_merge_command.is_none());}#[test]diff --git a/tests/integration_tests/e2e_shell.rs b/tests/integration_tests/e2e_shell.rsindex a235f66ab..7e5c47fac 100644--- a/tests/integration_tests/e2e_shell.rs+++ b/tests/integration_tests/e2e_shell.rs@@ -82,14 +82,18 @@ fn generate_init_code(repo: &TestRepo, shell: &str) -> String {.output().expect("Failed to generate init code");- if !output.status.success() {+ // For shells that don't support completions, the command will exit with code 1+ // but still output the shell integration code to stdout. We can use that output.+ let stdout = String::from_utf8(output.stdout).expect("Invalid UTF-8 in init code");++ if !output.status.success() && stdout.trim().is_empty() {panic!("Failed to generate init code:\nstderr: {}",String::from_utf8_lossy(&output.stderr));}- String::from_utf8(output.stdout).expect("Invalid UTF-8 in init code")+ stdout}/// Generate shell-specific PATH export syntaxdiff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rsindex 8d1524ee1..f322dc90c 100644--- a/tests/integration_tests/e2e_shell_post_start.rs+++ b/tests/integration_tests/e2e_shell_post_start.rs@@ -85,14 +85,18 @@ fn generate_init_code(repo: &TestRepo, shell: &str) -> String {.output().expect("Failed to generate init code");- if !output.status.success() {+ // For shells that don't support completions, the command will exit with code 1+ // but still output the shell integration code to stdout. We can use that output.+ let stdout = String::from_utf8(output.stdout).expect("Invalid UTF-8 in init code");++ if !output.status.success() && stdout.trim().is_empty() {panic!("Failed to generate init code:\nstderr: {}",String::from_utf8_lossy(&output.stderr));}- String::from_utf8(output.stdout).expect("Invalid UTF-8 in init code")+ stdout}/// Generate shell-specific PATH export syntax@@ -119,11 +123,6 @@ fn path_export_syntax(shell: &str, bin_path: &str) -> String {#[cfg_attr(feature = "tier-2-integration-tests", case("oil"))]#[cfg_attr(feature = "tier-2-integration-tests", case("xonsh"))]fn test_e2e_post_start_background_command(#[case] shell: &str) {- if !is_shell_available(shell) {- eprintln!("Skipping test: {} not available", shell);- return;- }-let repo = TestRepo::new();repo.commit("Initial commit");diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex d883c2673..e9fbb9650 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1138,3 +1138,191 @@ second = "echo 'STDOUT-FROM-SECOND' && echo 'STDERR-FROM-SECOND' >&2"insta::assert_snapshot!("merge_pre_merge_check_combined_output", output);});}++#[test]+fn test_merge_post_merge_command_success() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create project config with post-merge command that writes a marker file+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-merge-command = "echo 'merged {branch} to {target}' > post-merge-ran.txt""#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Create a worktree for main+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add worktree");++ // Create a feature worktree and make a commit+ let feature_wt = repo.add_worktree("feature", "feature");+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "feature.txt"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add feature file"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Merge with --force+ snapshot_merge(+ "merge_post_merge_command_success",+ &repo,+ &["main", "--force"],+ Some(&feature_wt),+ );++ // Verify the command ran in the main worktree (not the feature worktree)+ let marker_file = repo.root_path().join("post-merge-ran.txt");+ assert!(+ marker_file.exists(),+ "Post-merge command should have created marker file in main worktree"+ );+ let content = fs::read_to_string(&marker_file).expect("Failed to read marker file");+ assert!(+ content.contains("merged feature to main"),+ "Marker file should contain correct branch and target: {}",+ content+ );+}++#[test]+fn test_merge_post_merge_command_failure() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create project config with failing post-merge command+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"post-merge-command = "exit 1""#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Create a worktree for main+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add worktree");++ // Create a feature worktree and make a commit+ let feature_wt = repo.add_worktree("feature", "feature");+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "feature.txt"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add feature file"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Merge with --force - post-merge command should fail but merge should complete+ snapshot_merge(+ "merge_post_merge_command_failure",+ &repo,+ &["main", "--force"],+ Some(&feature_wt),+ );+}++#[test]+fn test_merge_post_merge_command_named() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create project config with named post-merge commands+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create config dir");+ fs::write(+ config_dir.join("wt.toml"),+ r#"+[post-merge-command]+notify = "echo 'Merge to {target} complete' > notify.txt"+deploy = "echo 'Deploying branch {branch}' > deploy.txt"+"#,+ )+ .expect("Failed to write config");++ repo.commit("Add config");++ // Create a worktree for main+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add worktree");++ // Create a feature worktree and make a commit+ let feature_wt = repo.add_worktree("feature", "feature");+ fs::write(feature_wt.join("feature.txt"), "feature content").expect("Failed to write file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "feature.txt"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add feature file"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Merge with --force+ snapshot_merge(+ "merge_post_merge_command_named",+ &repo,+ &["main", "--force"],+ Some(&feature_wt),+ );++ // Verify both commands ran+ let notify_file = repo.root_path().join("notify.txt");+ let deploy_file = repo.root_path().join("deploy.txt");+ assert!(+ notify_file.exists(),+ "Notify command should have created marker file"+ );+ assert!(+ deploy_file.exists(),+ "Deploy command should have created marker file"+ );+}diff --git a/tests/snapshots/integration__integration_tests__init__init_elvish.snap b/tests/snapshots/integration__integration_tests__init__init_elvish.snapnew file mode 100644index 000000000..cdd846edf--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_elvish.snap@@ -0,0 +1,101 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - elvish+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpXQiYi3/test-config.toml+---+success: false+exit_code: 1+----- stdout -----+# worktrunk shell integration for elvish++# Only initialize if wt is available+if (has-external wt) {+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'+ # This allows testing development builds: set E:WORKTRUNK_BIN = ./target/debug/wt+ var _WORKTRUNK_CMD = wt+ if (has-env WORKTRUNK_BIN) {+ set _WORKTRUNK_CMD = $E:WORKTRUNK_BIN+ }++ # Helper function to parse wt output and handle directives+ # Directives are NUL-terminated to support multi-line commands+ fn _wt_exec {|@args|+ var exit-code = 0+ var output = ""+ var exec-cmd = ""++ # Capture stdout for directives, let stderr pass through to terminal+ # This preserves TTY for color detection+ # TODO: Capture actual exit code from wt command, not just success/failure+ try {+ set output = (e:$_WORKTRUNK_CMD $@args | slurp)+ } catch e {+ set exit-code = 1+ set output = $e[reason][content]+ }++ # Split output on NUL bytes, process each chunk+ var chunks = [(str:split "\x00" $output)]+ for chunk $chunks {+ if (str:has-prefix $chunk "__WORKTRUNK_CD__") {+ # CD directive - extract path and change directory+ var path = (str:trim-prefix $chunk "__WORKTRUNK_CD__")+ cd $path+ } elif (str:has-prefix $chunk "__WORKTRUNK_EXEC__") {+ # EXEC directive - extract command (may contain newlines)+ set exec-cmd = (str:trim-prefix $chunk "__WORKTRUNK_EXEC__")+ } elif (!=s $chunk "") {+ # Regular output - print it (preserving newlines)+ print $chunk+ }+ }++ # Execute command if one was specified+ if (!=s $exec-cmd "") {+ eval $exec-cmd+ }++ # Return exit code (will throw exception if non-zero)+ if (!=s $exit-code 0) {+ fail "command failed with exit code "$exit-code+ }+ }++ # Override wt command to add --internal flag for switch, remove, and merge+ fn wt {|@args|+ if (== (count $args) 0) {+ e:$_WORKTRUNK_CMD+ return+ }++ var subcommand = $args[0]++ if (or (eq $subcommand "switch") (eq $subcommand "remove") (eq $subcommand "merge")) {+ # Commands that need --internal for directory change support+ var rest-args = $args[1..]+ _wt_exec --internal $subcommand $@rest-args+ } else {+ # All other commands pass through directly+ e:$_WORKTRUNK_CMD $@args+ }+ }+}++# Static completions (commands and flags)++----- stderr -----+β [31mCompletion not yet supported for elvish[0mdiff --git a/tests/snapshots/integration__integration_tests__init__init_nushell.snap b/tests/snapshots/integration__integration_tests__init__init_nushell.snapnew file mode 100644index 000000000..7da95172e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_nushell.snap@@ -0,0 +1,87 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - nushell+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp123wq4/test-config.toml+---+success: false+exit_code: 1+----- stdout -----+# worktrunk shell integration for nushell++# Only initialize if wt is available+if (which wt | is-not-empty) {+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'+ # This allows testing development builds: $env.WORKTRUNK_BIN = ./target/debug/wt+ let _WORKTRUNK_CMD = (if ($env.WORKTRUNK_BIN? | is-not-empty) { $env.WORKTRUNK_BIN } else { "wt" })++ # Helper function to parse wt output and handle directives+ # Directives are NUL-terminated to support multi-line commands+ export def --env _wt_exec [...args] {+ let result = (do { ^$_WORKTRUNK_CMD ...$args } | complete)+ mut exec_cmd = ""++ # Split output on NUL bytes, process each chunk+ for chunk in ($result.stdout | split row "\u{0000}") {+ if ($chunk | str starts-with "__WORKTRUNK_CD__") {+ # CD directive - extract path and change directory+ # TODO: Use str replace instead of hard-coded offset (fragile if prefix changes)+ let path = ($chunk | str substring 16..)+ cd $path+ } else if ($chunk | str starts-with "__WORKTRUNK_EXEC__") {+ # EXEC directive - extract command (may contain newlines)+ # TODO: Use str replace instead of hard-coded offset (fragile if prefix changes)+ $exec_cmd = ($chunk | str substring 18..)+ } else if ($chunk | str length) > 0 {+ # Regular output - print it with newline+ print $chunk+ }+ }++ # Execute command if one was specified+ if ($exec_cmd != "") {+ nu -c $exec_cmd+ }++ # Return the exit code+ return $result.exit_code+ }++ # Override wt command to add --internal flag for switch, remove, and merge+ # Use --wrapped to pass through all flags without parsing them+ export def --env --wrapped wt [...rest] {+ let subcommand = ($rest | get 0? | default "")++ match $subcommand {+ "switch" | "remove" | "merge" => {+ # Commands that need --internal for directory change support+ let rest_args = ($rest | skip 1)+ let internal_args = (["--internal", $subcommand] | append $rest_args)+ let exit_code = (_wt_exec ...$internal_args)+ return $exit_code+ }+ _ => {+ # All other commands pass through directly+ ^$_WORKTRUNK_CMD ...$rest+ }+ }+ }+}++# Static completions (commands and flags)++----- stderr -----+β [31mCompletion not yet supported for nushell[0mdiff --git a/tests/snapshots/integration__integration_tests__init__init_oil.snap b/tests/snapshots/integration__integration_tests__init__init_oil.snapnew file mode 100644index 000000000..d7df214fb--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_oil.snap@@ -0,0 +1,399 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - oil+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxLMelz/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+# worktrunk shell integration for oil++# Only initialize if wt is available+if command -v wt >/dev/null 2>&1; then+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'+ # This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt+ _WORKTRUNK_CMD="${WORKTRUNK_BIN:-wt}"++ # Helper function to parse wt output and handle directives+ # Directives are NUL-terminated to support multi-line commands+ _wt_exec() {+ local exec_cmd="" chunk exit_code+ local exit_code_file+ exit_code_file=$(mktemp) || { echo "Failed to create temp file" >&2; return 1; }++ # Parse stdout for directives (NUL-delimited)+ # Let stderr pass through to terminal (preserves TTY for color detection)+ # Write exit code to temp file since it can't be captured from process substitution+ # The || [[ -n "$chunk" ]] handles non-NUL-terminated output (e.g., error messages)+ while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do+ if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then+ # CD directive - extract path and change directory+ local path="${chunk#__WORKTRUNK_CD__}"+ \cd "$path"+ elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then+ # EXEC directive - extract command (may contain newlines)+ exec_cmd="${chunk#__WORKTRUNK_EXEC__}"+ else+ # Regular output - print it with newline+ printf '%s\n' "$chunk"+ fi+ done < <(command "$_WORKTRUNK_CMD" "$@"; echo "$?" > "$exit_code_file")++ # Read exit code from temp file+ exit_code=$(cat "$exit_code_file" 2>/dev/null || echo 0)++ # Cleanup temp file+ \rm -f "$exit_code_file"++ # Execute command if one was specified+ # Security: Command is user-provided from -x flag; eval is intentional.+ # NUL-termination allows multi-line commands.+ # Exit code semantics: Returns wt's exit code, not the executed command's.+ # This allows detecting wt failures (e.g., branch creation errors).+ # The executed command runs for side effects; its failure is logged but doesn't affect exit code.+ if [[ -n "$exec_cmd" ]]; then+ if ! eval "$exec_cmd"; then+ echo "Warning: Command execution failed (exit code $?)" >&2+ fi+ fi++ return $exit_code+ }++ # Override wt command to add --internal flag for switch, remove, and merge+ wt() {+ local subcommand="$1"++ case "$subcommand" in+ switch|remove|merge)+ # Commands that need --internal for directory change support+ shift+ _wt_exec --internal "$subcommand" "$@"+ ;;+ *)+ # All other commands pass through directly+ command "$_WORKTRUNK_CMD" "$@"+ ;;+ esac+ }++ # Dynamic completion function+ _wt_complete() {+ local cur="${COMP_WORDS[COMP_CWORD]}"++ # Call wt complete with current command line+ local completions=$(command "$_WORKTRUNK_CMD" complete "${COMP_WORDS[@]}" 2>/dev/null)+ COMPREPLY=($(compgen -W "$completions" -- "$cur"))+ }++ # Register dynamic completion+ complete -F _wt_complete wt+fi++# Static completions (commands and flags)+_wt() {+ local i cur prev opts cmd+ COMPREPLY=()+ if [[ "${BASH_VERSINFO[0]}" -ge 4 ]]; then+ cur="$2"+ else+ cur="${COMP_WORDS[COMP_CWORD]}"+ fi+ prev="$3"+ cmd=""+ opts=""++ for i in "${COMP_WORDS[@]:0:COMP_CWORD}"+ do+ case "${cmd},${i}" in+ ",$1")+ cmd="wt"+ ;;+ wt,complete)+ cmd="wt__complete"+ ;;+ wt,completion)+ cmd="wt__completion"+ ;;+ wt,config)+ cmd="wt__config"+ ;;+ wt,configure-shell)+ cmd="wt__configure__shell"+ ;;+ wt,init)+ cmd="wt__init"+ ;;+ wt,list)+ cmd="wt__list"+ ;;+ wt,merge)+ cmd="wt__merge"+ ;;+ wt,push)+ cmd="wt__push"+ ;;+ wt,remove)+ cmd="wt__remove"+ ;;+ wt,switch)+ cmd="wt__switch"+ ;;+ wt__config,init)+ cmd="wt__config__init"+ ;;+ wt__config,list)+ cmd="wt__config__list"+ ;;+ *)+ ;;+ esac+ done++ case "${cmd}" in+ wt)+ opts="-v -h -V --verbose --help --version init configure-shell config list switch remove push merge completion complete"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__complete)+ opts="-v -h --verbose --help [ARGS]..."+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__completion)+ opts="-v -h --verbose --help bash elvish fish nushell oil powershell xonsh zsh"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__config)+ opts="-v -h --verbose --help init list"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__config__init)+ opts="-v -h --verbose --help"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__config__list)+ opts="-v -h --verbose --help"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 3 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__configure__shell)+ opts="-y -v -h --shell --cmd --yes --verbose --help"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ --shell)+ COMPREPLY=($(compgen -W "bash elvish fish nushell oil powershell xonsh zsh" -- "${cur}"))+ return 0+ ;;+ --cmd)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__init)+ opts="-v -h --cmd --verbose --help <SHELL>"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ --cmd)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__list)+ opts="-v -h --format --branches --verbose --help"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ --format)+ COMPREPLY=($(compgen -W "table json" -- "${cur}"))+ return 0+ ;;+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__merge)+ opts="-s -k -m -f -v -h --squash --keep --message --no-verify --force --verbose --help [TARGET]"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ --message)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ -m)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__push)+ opts="-v -h --allow-merge-commits --verbose --help [TARGET]"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__remove)+ opts="-v -h --verbose --help [WORKTREE]"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ wt__switch)+ opts="-c -b -x -f -v -h --create --base --execute --force --no-config-commands --verbose --help <BRANCH>"+ if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ fi+ case "${prev}" in+ --base)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ -b)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ --execute)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ -x)+ COMPREPLY=($(compgen -f "${cur}"))+ return 0+ ;;+ *)+ COMPREPLY=()+ ;;+ esac+ COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )+ return 0+ ;;+ esac+}++if [[ "${BASH_VERSINFO[0]}" -eq 4 && "${BASH_VERSINFO[1]}" -ge 4 || "${BASH_VERSINFO[0]}" -gt 4 ]]; then+ complete -F _wt -o nosort -o bashdefault -o default wt+else+ complete -F _wt -o bashdefault -o default wt+fi++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__init__init_powershell.snap b/tests/snapshots/integration__integration_tests__init__init_powershell.snapnew file mode 100644index 000000000..2f42f1a2d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_powershell.snap@@ -0,0 +1,103 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - powershell+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpIbF0a6/test-config.toml+---+success: false+exit_code: 1+----- stdout -----+# worktrunk shell integration for PowerShell++# Only initialize if wt is available+if (Get-Command wt -ErrorAction SilentlyContinue) {+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'+ # This allows testing development builds: $env:WORKTRUNK_BIN = "./target/debug/wt"+ $script:_WORKTRUNK_CMD = if ($env:WORKTRUNK_BIN) { $env:WORKTRUNK_BIN } else { "wt" }++ # Helper function to parse wt output and handle directives+ # Directives are NUL-terminated to support multi-line commands+ function _wt_exec {+ param(+ [Parameter(ValueFromRemainingArguments=$true)]+ [string[]]$Arguments+ )++ # Capture stdout for directives, let stderr pass through to terminal+ # This preserves TTY for color detection+ $output = & $script:_WORKTRUNK_CMD @Arguments | Out-String+ $exitCode = $LASTEXITCODE+ $execCmd = ""++ # Split output on NUL bytes, process each chunk+ foreach ($chunk in ($output -split "`0")) {+ if ($chunk -match '^__WORKTRUNK_CD__') {+ # CD directive - extract path and change directory+ $path = $chunk -replace '^__WORKTRUNK_CD__', ''+ Set-Location $path+ } elseif ($chunk -match '^__WORKTRUNK_EXEC__') {+ # EXEC directive - extract command (may contain newlines)+ $execCmd = $chunk -replace '^__WORKTRUNK_EXEC__', ''+ } elseif ($chunk) {+ # Regular output - write it with newline+ # TODO: Use Write-Output instead of Write-Host for redirectable output+ Write-Host $chunk+ }+ }++ # Execute command if one was specified+ if ($execCmd) {+ Invoke-Expression $execCmd+ }++ # Return the exit code+ return $exitCode+ }++ # Override wt command to add --internal flag for switch, remove, and merge+ function wt {+ param(+ [Parameter(ValueFromRemainingArguments=$true)]+ [string[]]$Arguments+ )++ if ($Arguments.Count -eq 0) {+ & $script:_WORKTRUNK_CMD+ return $LASTEXITCODE+ }++ $subcommand = $Arguments[0]++ switch ($subcommand) {+ { $_ -in @("switch", "remove", "merge") } {+ # Commands that need --internal for directory change support+ $restArgs = $Arguments[1..($Arguments.Count-1)]+ $exitCode = _wt_exec --internal $subcommand @restArgs+ return $exitCode+ }+ default {+ # All other commands pass through directly+ & $script:_WORKTRUNK_CMD @Arguments+ return $LASTEXITCODE+ }+ }+ }+}++# Static completions (commands and flags)++----- stderr -----+β [31mCompletion not yet supported for powershell[0mdiff --git a/tests/snapshots/integration__integration_tests__init__init_xonsh.snap b/tests/snapshots/integration__integration_tests__init__init_xonsh.snapnew file mode 100644index 000000000..b5647ac07--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_xonsh.snap@@ -0,0 +1,88 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - xonsh+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnTeEBT/test-config.toml+---+success: false+exit_code: 1+----- stdout -----+# worktrunk shell integration for xonsh++# Only initialize if wt is available+import shutil+import os+if shutil.which("wt") is not None:+ # Use WORKTRUNK_BIN if set, otherwise default to 'wt'+ # This allows testing development builds: $WORKTRUNK_BIN = ./target/debug/wt+ _WORKTRUNK_CMD = os.environ.get('WORKTRUNK_BIN', 'wt')++ def _wt_exec(args):+ """Helper function to parse wt output and handle directives+ Directives are NUL-terminated to support multi-line commands"""+ # Capture full output including return code+ result = ![@(_WORKTRUNK_CMD) @(args)]+ exec_cmd = ""++ # Split output on NUL bytes, process each chunk+ if result.out:+ for chunk in result.out.split("\0"):+ if chunk.startswith("__WORKTRUNK_CD__"):+ # CD directive - extract path and change directory+ # TODO: Use str.replace instead of hard-coded offset (fragile if prefix changes)+ path = chunk[16:] # Remove prefix+ cd @(path)+ elif chunk.startswith("__WORKTRUNK_EXEC__"):+ # EXEC directive - extract command (may contain newlines)+ # TODO: Use str.replace instead of hard-coded offset (fragile if prefix changes)+ exec_cmd = chunk[18:] # Remove prefix+ elif chunk:+ # Regular output - print it with newline+ print(chunk)++ # Execute command if one was specified+ if exec_cmd:+ execx(exec_cmd)++ # Return the exit code+ # TODO: Add fallback for None: return result.returncode or 0+ return result.returncode++ def _wt_wrapper(args):+ """Override wt command to add --internal flag for switch, remove, and merge"""+ if not args:+ # No arguments, just run wt+ ![@(_WORKTRUNK_CMD)]+ return++ subcommand = args[0]++ if subcommand in ["switch", "remove", "merge"]:+ # Commands that need --internal for directory change support+ rest_args = args[1:]+ return _wt_exec(["--internal", subcommand] + rest_args)+ else:+ # All other commands pass through directly+ result = ![@(_WORKTRUNK_CMD) @(args)]+ return result.returncode++ # Register the alias+ aliases['wt'] = _wt_wrapper++# Static completions (commands and flags)++----- stderr -----+β [31mCompletion not yet supported for xonsh[0mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snapnew file mode 100644index 000000000..12a952d97--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap@@ -0,0 +1,41 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--force"+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmptfDC49/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mValidating merge...[0m+π [36mRebasing onto [1m[36mmain[0m...[0m+π [36mPushing 1 commit to [1m[36mmain[0m @ [SHA][0m++* [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add feature file++ feature.txt | 1 [32m+[m+ 1 file changed, 1 insertion(+)++β [32mPushed to [1m[32mmain[0m (1 commit, 1 file, [32m+1[0m) [0m+π [36mCleaning up worktree...[0m++β [32mReturned to primary at [REPO][0m++----- stderr -----+π [36mExecuting (post-merge):[0m+[40m [0m exit 1+π‘ [33mCommand [1m[33mcmd[0m failed: Command failed with exit code: exit status: 1[0mdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snapnew file mode 100644index 000000000..59abe40e0--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_named.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--force"+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpAoqM3d/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mValidating merge...[0m+π [36mRebasing onto [1m[36mmain[0m...[0m+π [36mPushing 1 commit to [1m[36mmain[0m @ [SHA][0m++* [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add feature file++ feature.txt | 1 [32m+[m+ 1 file changed, 1 insertion(+)++β [32mPushed to [1m[32mmain[0m (1 commit, 1 file, [32m+1[0m) [0m+π [36mCleaning up worktree...[0m++β [32mReturned to primary at [REPO][0m++----- stderr -----+π [36mExecuting (post-merge):[0m+[40m [0m echo 'Deploying branch feature' > deploy.txt+π [36mExecuting (post-merge):[0m+[40m [0m echo 'Merge to main complete' > notify.txtdiff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_success.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_success.snapnew file mode 100644index 000000000..737be50a3--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_success.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--force"+ 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: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp1YR6XY/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mValidating merge...[0m+π [36mRebasing onto [1m[36mmain[0m...[0m+π [36mPushing 1 commit to [1m[36mmain[0m @ [SHA][0m++* [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature[m[33m)[m Add feature file++ feature.txt | 1 [32m+[m+ 1 file changed, 1 insertion(+)++β [32mPushed to [1m[32mmain[0m (1 commit, 1 file, [32m+1[0m) [0m+π [36mCleaning up worktree...[0m++β [32mReturned to primary at [REPO][0m++----- stderr -----+π [36mExecuting (post-merge):[0m+[40m [0m echo 'merged feature to main' > post-merge-ran.txt