Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Wrap gutter formatted text to terminal width
Maximilian Roos370285e21dc0
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 8be23c170..289c6b9b2 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -118,7 +118,7 @@ fn prompt_for_batch_approval(} else {format!("{name}: {command}")};- eprint!("{}", format_with_gutter(&label, ""));+ eprint!("{}", format_with_gutter(&label, "", None));}eprintln!();diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 3403d3c51..2183d96bb 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -360,7 +360,7 @@ fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String>);// Show the config line that will be added with gutter- eprint!("{}", format_with_gutter(&result.config_line, ""));+ eprint!("{}", format_with_gutter(&result.config_line, "", None));}eprintln!();diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 0fb962af2..60981db7c 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -239,7 +239,7 @@ fn handle_commit_changes(// Display the generated commit messagelet formatted_message = format_commit_message_for_display(&commit_message);- print!("{}", format_with_gutter(&formatted_message, ""));+ print!("{}", format_with_gutter(&formatted_message, "", None));// Commitrepo.run_command(&["commit", "-m", &commit_message])@@ -317,7 +317,7 @@ fn handle_squash(target_branch: &str) -> Result<Option<usize>, GitError> {// Display the generated commit messagelet formatted_message = format_commit_message_for_display(&commit_message);- print!("{}", format_with_gutter(&formatted_message, ""));+ print!("{}", format_with_gutter(&formatted_message, "", None));// Reset to merge base (soft reset stages all changes)repo.run_command(&["reset", "--soft", &merge_base])@@ -367,7 +367,7 @@ fn run_pre_merge_checks("π {CYAN}Running pre-merge check '{name}':{CYAN:#}",name = prepared.name);- eprint!("{}", format_with_gutter(&prepared.expanded, "")); // Gutter at column 0+ eprint!("{}", format_with_gutter(&prepared.expanded, "", None)); // Gutter at column 0let _ = std::io::stderr().flush();if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 63cda4039..4b9b6fe3f 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -453,7 +453,7 @@ fn execute_post_create_commands(for prepared in commands {use std::io::Write;eprintln!("π {CYAN}Executing (post-create):{CYAN:#}");- eprint!("{}", format_with_gutter(&prepared.expanded, "")); // Gutter at column 0+ eprint!("{}", format_with_gutter(&prepared.expanded, "", None)); // Gutter at column 0let _ = std::io::stderr().flush();if let Err(e) = execute_command_in_worktree(worktree_path, &prepared.expanded) {@@ -512,7 +512,7 @@ fn spawn_post_start_commands(for prepared in commands {use std::io::Write;eprintln!("π {CYAN}Starting (background):{CYAN:#}");- eprint!("{}", format_with_gutter(&prepared.expanded, ""));+ eprint!("{}", format_with_gutter(&prepared.expanded, "", None));let _ = std::io::stderr().flush();match spawn_detached(worktree_path, &prepared.expanded, &prepared.name) {diff --git a/src/main.rs b/src/main.rsindex c5fa210aa..9c41dcda0 100644--- a/src/main.rs+++ b/src/main.rs@@ -281,7 +281,7 @@ fn main() {result.action.description(),);// Show config line with gutter- print!("{}", format_with_gutter(&result.config_line, ""));+ print!("{}", format_with_gutter(&result.config_line, "", None));}// Success summarydiff --git a/src/styling.rs b/src/styling.rsindex 470e75196..f236a83ac 100644--- a/src/styling.rs+++ b/src/styling.rs@@ -182,28 +182,113 @@ impl StyledLine {// Gutter Formatting// ============================================================================+/// Default terminal width fallback if detection fails+const DEFAULT_TERMINAL_WIDTH: usize = 80;++/// Wraps text at word boundaries to fit within the specified width+///+/// # Arguments+/// * `text` - The text to wrap+/// * `max_width` - Maximum width for each line+///+/// # Returns+/// A vector of wrapped lines+fn wrap_text_at_width(text: &str, max_width: usize) -> Vec<String> {+ if max_width == 0 {+ return vec![text.to_string()];+ }++ let text_width = text.width();++ // If the line fits, return it as-is+ if text_width <= max_width {+ return vec![text.to_string()];+ }++ let mut lines = Vec::new();+ let mut current_line = String::new();+ let mut current_width = 0;++ for word in text.split_whitespace() {+ let word_width = word.width();++ // If this is the first word in the line+ if current_line.is_empty() {+ // If a single word is longer than max_width, we have to include it anyway+ current_line = word.to_string();+ current_width = word_width;+ } else {+ // Calculate width with space before the word+ let new_width = current_width + 1 + word_width;++ if new_width <= max_width {+ // Word fits on current line+ current_line.push(' ');+ current_line.push_str(word);+ current_width = new_width;+ } else {+ // Word doesn't fit, start a new line+ lines.push(current_line);+ current_line = word.to_string();+ current_width = word_width;+ }+ }+ }++ // Add the last line if there's content+ if !current_line.is_empty() {+ lines.push(current_line);+ }++ // Handle empty input+ if lines.is_empty() {+ lines.push(String::new());+ }++ lines+}+/// Formats text with a gutter (single-space with background color) on each line////// This creates a subtle visual separator for quoted content like commands or configuration.+/// Text is automatically word-wrapped at terminal width to prevent overflow.////// # Arguments/// * `content` - The text to format (preserves internal structure for multi-line)/// * `left_margin` - Should always be "" (gutter provides all visual separation)+/// * `max_width` - Optional maximum width (for testing). If None, auto-detects terminal width.////// The gutter appears at column 0, followed by 1 space, then the content at column 1.////// # Example/// ```ignore-/// // All contexts use empty left margin-/// print!("{}", format_with_gutter(&config, ""));-/// print!("{}", format_with_gutter(&command, ""));+/// // All contexts use empty left margin and auto-detect width+/// print!("{}", format_with_gutter(&config, "", None));/// ```-pub fn format_with_gutter(content: &str, left_margin: &str) -> String {+pub fn format_with_gutter(content: &str, left_margin: &str, max_width: Option<usize>) -> String {let gutter = Style::new().bg_color(Some(Color::Ansi(AnsiColor::Black)));let mut output = String::new();+ // Use provided width or detect terminal width+ let term_width = max_width.unwrap_or_else(|| {+ terminal_size::terminal_size()+ .map(|(w, _)| w.0 as usize)+ .unwrap_or(DEFAULT_TERMINAL_WIDTH)+ });++ // Account for gutter (1) + space (1) + left_margin+ let left_margin_width = left_margin.width();+ let available_width = term_width.saturating_sub(2 + left_margin_width);+for line in content.lines() {- output.push_str(&format!("{left_margin}{gutter} {gutter:#} {line}\n"));+ // Wrap the line at word boundaries+ let wrapped_lines = wrap_text_at_width(line, available_width);++ for wrapped_line in wrapped_lines {+ output.push_str(&format!(+ "{left_margin}{gutter} {gutter:#} {wrapped_line}\n"+ ));+ }}output@@ -434,4 +519,121 @@ command = "npm install""Rows with and without sparse column data should have same width");}++ // Word-wrapping tests+ #[test]+ fn test_wrap_text_no_wrapping_needed() {+ let result = super::wrap_text_at_width("short line", 50);+ assert_eq!(result, vec!["short line"]);+ }++ #[test]+ fn test_wrap_text_at_word_boundary() {+ let text = "This is a very long line that needs to be wrapped at word boundaries";+ let result = super::wrap_text_at_width(text, 30);++ // Should wrap at word boundaries+ assert!(result.len() > 1, "Should wrap into multiple lines");++ // Each line should be within the width limit (or be a single long word)+ for line in &result {+ assert!(+ line.width() <= 30 || !line.contains(' '),+ "Line '{}' has width {} which exceeds 30 and contains spaces",+ line,+ line.width()+ );+ }++ // Joining should recover most of the original text (whitespace may differ)+ let rejoined = result.join(" ");+ assert_eq!(+ rejoined.split_whitespace().collect::<Vec<_>>(),+ text.split_whitespace().collect::<Vec<_>>()+ );+ }++ #[test]+ fn test_wrap_text_single_long_word() {+ // A single word longer than max_width should still be included+ let result = super::wrap_text_at_width("verylongwordthatcannotbewrapped", 10);+ assert_eq!(result.len(), 1);+ assert_eq!(result[0], "verylongwordthatcannotbewrapped");+ }++ #[test]+ fn test_wrap_text_empty_input() {+ let result = super::wrap_text_at_width("", 50);+ assert_eq!(result, vec![""]);+ }++ #[test]+ fn test_wrap_text_unicode() {+ // Unicode characters should be handled correctly by width+ let text = "This line has emoji π and should wrap correctly when needed";+ let result = super::wrap_text_at_width(text, 30);++ // Should wrap+ assert!(result.len() > 1);++ // Should preserve the emoji+ let rejoined = result.join(" ");+ assert!(rejoined.contains("π"));+ }++ #[test]+ fn test_format_with_gutter_wrapping() {+ // Create a very long line that would overflow a narrow terminal+ let long_text = "This is a very long commit message that would normally overflow the terminal width and break the gutter formatting, but now it should wrap nicely at word boundaries.";++ // Use fixed width for consistent testing (80 columns)+ let result = format_with_gutter(long_text, "", Some(80));++ // Should contain multiple lines (wrapped)+ let line_count = result.lines().count();+ assert!(+ line_count > 1,+ "Long text should wrap to multiple lines, got {} lines",+ line_count+ );++ // Each line should have the gutter+ for line in result.lines() {+ assert!(+ line.contains("\x1b[40m"),+ "Each line should contain gutter (Black background = 40)"+ );+ }+ }++ #[test]+ fn test_format_with_gutter_preserves_newlines() {+ let multi_line = "Line 1\nLine 2\nLine 3";+ let result = format_with_gutter(multi_line, "", None);++ // Should have at least 3 lines (one for each input line)+ assert!(result.lines().count() >= 3);++ // Each original line should be present+ assert!(result.contains("Line 1"));+ assert!(result.contains("Line 2"));+ assert!(result.contains("Line 3"));+ }++ #[test]+ fn test_format_with_gutter_long_paragraph() {+ // Realistic commit message scenario - a long unbroken paragraph+ let commit_msg = "This commit refactors the authentication system to use a more secure token-based approach instead of the previous session-based system which had several security vulnerabilities that were identified during the security audit last month. The new implementation follows industry best practices and includes proper token rotation and expiration handling.";++ // Use fixed width for consistent testing (80 columns)+ let result = format_with_gutter(commit_msg, "", Some(80));++ insta::assert_snapshot!(result, @r"+ [40m [0m This commit refactors the authentication system to use a more secure+ [40m [0m token-based approach instead of the previous session-based system which had+ [40m [0m several security vulnerabilities that were identified during the security+ [40m [0m audit last month. The new implementation follows industry best practices and+ [40m [0m includes proper token rotation and expiration handling.+ ");+ }}diff --git a/tests/snapshots/integration__integration_tests__init__init_elvish.snap b/tests/snapshots/integration__integration_tests__init__init_elvish.snapdeleted file mode 100644index d037dd8b1..000000000--- a/tests/snapshots/integration__integration_tests__init__init_elvish.snap+++ /dev/null@@ -1,101 +0,0 @@-----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/.tmpTW5uxh/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.snapdeleted file mode 100644index 77e8918d2..000000000--- a/tests/snapshots/integration__integration_tests__init__init_nushell.snap+++ /dev/null@@ -1,87 +0,0 @@-----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/.tmpjuyHeR/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 (preserving newlines)- print -n $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.snapdeleted file mode 100644index 3183f0fe5..000000000--- a/tests/snapshots/integration__integration_tests__init__init_oil.snap+++ /dev/null@@ -1,399 +0,0 @@-----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/.tmpXkP8kf/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 (preserving newlines)- printf '%s' "$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.snapdeleted file mode 100644index 5c4ac489d..000000000--- a/tests/snapshots/integration__integration_tests__init__init_powershell.snap+++ /dev/null@@ -1,103 +0,0 @@-----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/.tmpTIMEEZ/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 (preserving newlines)- # TODO: Use Write-Output instead of Write-Host for redirectable output- Write-Host -NoNewline $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.snapdeleted file mode 100644index dbe9c8382..000000000--- a/tests/snapshots/integration__integration_tests__init__init_xonsh.snap+++ /dev/null@@ -1,88 +0,0 @@-----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/.tmpFvD04H/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 (preserving newlines)- print(chunk, end='')-- # 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__post_start_commands__post_create_template_expansion.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snapindex 71648bb4c..57b4cb971 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_template_expansion.snap@@ -1,6 +1,5 @@---source: tests/integration_tests/post_start_commands.rs-assertion_line: 30info:program: wtargs:@@ -14,10 +13,10 @@ info:GIT_CONFIG_GLOBAL: /dev/nullGIT_CONFIG_SYSTEM: /dev/nullGIT_EDITOR: ""- HOME: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpvq8LHjLANG: CLC_ALL: C- SOURCE_DATE_EPOCH: "1704067200"+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpvoDDAg/test-config.toml---success: trueexit_code: 0@@ -32,6 +31,10 @@ To enable automatic cd, run: wt configure-shellπ [36mExecuting (post-create):[0m[40m [0m echo 'Branch: feature-test' >> info.txtπ [36mExecuting (post-create):[0m-[40m [0m echo 'Worktree: [REPO].feature-test' >> info.txt+[40m [0m echo 'Worktree:+[40m [0m [REPO].feature-test'+[40m [0m >> info.txtπ [36mExecuting (post-create):[0m-[40m [0m echo 'Root: [REPO]' >> info.txt+[40m [0m echo 'Root:+[40m [0m [REPO]'+[40m [0m >> info.txt