Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Refactor: Extract common shell and list snapshot utilities

Maximilian Roos1185adacb529
diff --git a/tests/common/list_snapshots.rs b/tests/common/list_snapshots.rs
new file mode 100644
index 000000000..a4630573c
--- /dev/null
+++ b/tests/common/list_snapshots.rs
@@ -0,0 +1,65 @@
+use super::{TestRepo, wt_command};
+use insta::Settings;
+use std::path::Path;
+use std::process::Command;
+
+fn base_settings(repo: &TestRepo) -> Settings {
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+ normalize_worktree_paths(&mut settings, repo);
+ settings.add_filter(r"\\", "/");
+ settings
+}
+
+pub fn standard_settings(repo: &TestRepo) -> Settings {
+ let mut settings = base_settings(repo);
+ settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA] ");
+ settings
+}
+
+pub fn json_settings(repo: &TestRepo) -> Settings {
+ let mut settings = base_settings(repo);
+ settings.add_filter(r#""head": "[0-9a-f]{40}""#, r#""head": "[SHA]""#);
+ settings.add_filter(r#""timestamp": \d+"#, r#""timestamp": 0"#);
+ settings.add_filter(r"\\u001b\[32m", "[GREEN]");
+ settings.add_filter(r"\\u001b\[31m", "[RED]");
+ settings.add_filter(r"\\u001b\[2m", "[DIM]");
+ settings.add_filter(r"\\u001b\[0m", "[RESET]");
+ settings.add_filter(r"\\\\", "/");
+ settings
+}
+
+pub fn command(repo: &TestRepo, cwd: &Path) -> Command {
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("list").current_dir(cwd);
+ cmd
+}
+
+pub fn command_json(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.arg("--format=json");
+ cmd
+}
+
+pub fn command_branches(repo: &TestRepo) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.arg("--branches");
+ cmd
+}
+
+pub fn command_with_width(repo: &TestRepo, width: usize) -> Command {
+ let mut cmd = command(repo, repo.root_path());
+ cmd.env("COLUMNS", width.to_string());
+ cmd
+}
+
+fn normalize_worktree_paths(settings: &mut Settings, repo: &TestRepo) {
+ settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
+ for (name, path) in &repo.worktrees {
+ settings.add_filter(
+ path.to_str().unwrap(),
+ format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
+ );
+ }
+}
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 18d499cc9..5c3c0bce7 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -25,6 +25,9 @@
// Test utilities are Unix-only since integration tests are Unix-only
#![cfg(unix)]
+pub mod list_snapshots;
+pub mod shell;
+
use insta_cmd::get_cargo_bin;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
diff --git a/tests/common/shell.rs b/tests/common/shell.rs
new file mode 100644
index 000000000..1c818d580
--- /dev/null
+++ b/tests/common/shell.rs
@@ -0,0 +1,104 @@
+use super::{TestRepo, wt_command};
+use insta_cmd::get_cargo_bin;
+use std::process::Command;
+
+/// Map shell display names to actual binaries.
+pub fn get_shell_binary(shell: &str) -> &str {
+ match shell {
+ "nushell" => "nu",
+ "powershell" => "pwsh",
+ "oil" => "osh",
+ _ => shell,
+ }
+}
+
+/// Execute a script in the given shell with the repo's isolated environment.
+pub fn execute_shell_script(repo: &TestRepo, shell: &str, script: &str) -> String {
+ let binary = get_shell_binary(shell);
+ let mut cmd = Command::new(binary);
+ repo.clean_cli_env(&mut cmd);
+
+ // Prevent user shell config from leaking into tests.
+ cmd.env_remove("BASH_ENV");
+ cmd.env_remove("ENV");
+ cmd.env_remove("ZDOTDIR");
+ cmd.env_remove("XONSHRC");
+ cmd.env_remove("XDG_CONFIG_HOME");
+
+ match shell {
+ "fish" => {
+ cmd.arg("--no-config");
+ }
+ "powershell" | "pwsh" => {
+ cmd.arg("-NoProfile");
+ }
+ "xonsh" => {
+ cmd.arg("--no-rc");
+ }
+ "nushell" | "nu" => {
+ cmd.arg("--no-config-file");
+ }
+ _ => {}
+ }
+
+ let output = cmd
+ .arg("-c")
+ .arg(script)
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap_or_else(|e| panic!("Failed to execute {} script: {}", shell, e));
+
+ if !output.status.success() {
+ panic!(
+ "Shell script failed:\nstdout: {}\nstderr: {}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ }
+
+ String::from_utf8(output.stdout).expect("Invalid UTF-8 in output")
+}
+
+/// Generate `wt init <shell>` output for the repo.
+pub fn generate_init_code(repo: &TestRepo, shell: &str) -> String {
+ let mut cmd = wt_command();
+ repo.clean_cli_env(&mut cmd);
+
+ let output = cmd
+ .args(["init", shell])
+ .current_dir(repo.root_path())
+ .output()
+ .expect("Failed to generate init code");
+
+ 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)
+ );
+ }
+
+ stdout
+}
+
+/// Format PATH mutation per shell.
+pub fn path_export_syntax(shell: &str, bin_path: &str) -> String {
+ match shell {
+ "fish" => format!(r#"set -x PATH {} $PATH"#, bin_path),
+ "nushell" => format!(r#"$env.PATH = ($env.PATH | prepend "{}")"#, bin_path),
+ "powershell" => format!(r#"$env:PATH = "{}:$env:PATH""#, bin_path),
+ "elvish" => format!(r#"set E:PATH = {}:$E:PATH"#, bin_path),
+ "xonsh" => format!(r#"$PATH.insert(0, "{}")"#, bin_path),
+ _ => format!(r#"export PATH="{}:$PATH""#, bin_path),
+ }
+}
+
+/// Helper that returns the `wt` binary directory for PATH injection.
+pub fn wt_bin_dir() -> String {
+ get_cargo_bin("wt")
+ .parent()
+ .unwrap()
+ .to_string_lossy()
+ .to_string()
+}
diff --git a/tests/integration_tests/e2e_shell.rs b/tests/integration_tests/e2e_shell.rs
index 7e7d953f4..472d72cad 100644
--- a/tests/integration_tests/e2e_shell.rs
+++ b/tests/integration_tests/e2e_shell.rs
@@ -1,185 +1,31 @@
-use crate::common::{TestRepo, wt_command};
-use insta_cmd::get_cargo_bin;
+use crate::common::{
+ TestRepo,
+ shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},
+};
use rstest::rstest;
-use std::process::Command;
-
-/// Map shell display names to actual binary names
-fn get_shell_binary(shell: &str) -> &str {
- match shell {
- "nushell" => "nu",
- "powershell" => "pwsh",
- "oil" => "osh", // oil shell binary is typically named 'osh'
- _ => shell,
- }
-}
-
-/// Execute a shell script in the given shell and return stdout
-fn execute_shell_script(repo: &TestRepo, shell: &str, script: &str) -> String {
- let binary = get_shell_binary(shell);
- let mut cmd = Command::new(binary);
- repo.clean_cli_env(&mut cmd);
-
- // Additional shell-specific isolation to prevent user config interference
- cmd.env_remove("BASH_ENV");
- cmd.env_remove("ENV"); // for sh/dash
- cmd.env_remove("ZDOTDIR"); // for zsh
- cmd.env_remove("XONSHRC"); // for xonsh
- cmd.env_remove("XDG_CONFIG_HOME"); // for elvish and others
-
- // Prevent loading user config files
- match shell {
- "fish" => {
- cmd.arg("--no-config");
- }
- "powershell" | "pwsh" => {
- cmd.arg("-NoProfile");
- }
- "xonsh" => {
- cmd.arg("--no-rc");
- }
- "nushell" | "nu" => {
- cmd.arg("--no-config-file");
- }
- _ => {}
- }
-
- let output = cmd
- .arg("-c")
- .arg(script)
- .current_dir(repo.root_path())
- .output()
- .unwrap_or_else(|e| panic!("Failed to execute {} script: {}", shell, e));
-
- if !output.status.success() {
- panic!(
- "Shell script failed:\nstdout: {}\nstderr: {}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- );
- }
-
- String::from_utf8(output.stdout).expect("Invalid UTF-8 in output")
-}
-
-/// Generate shell integration code for the given shell
-fn generate_init_code(repo: &TestRepo, shell: &str) -> String {
- let mut cmd = wt_command();
- repo.clean_cli_env(&mut cmd);
-
- let output = cmd
- .args(["init", shell])
- .current_dir(repo.root_path())
- .output()
- .expect("Failed to generate init code");
-
- // 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)
- );
- }
-
- stdout
-}
-
-/// Generate shell-specific PATH export syntax
-fn path_export_syntax(shell: &str, bin_path: &str) -> String {
- match shell {
- "fish" => format!(r#"set -x PATH {} $PATH"#, bin_path),
- "nushell" => format!(r#"$env.PATH = ($env.PATH | prepend "{}")"#, bin_path),
- "powershell" => format!(r#"$env:PATH = "{}:$env:PATH""#, bin_path),
- "elvish" => format!(r#"set E:PATH = {}:$E:PATH"#, bin_path),
- "xonsh" => format!(r#"$PATH.insert(0, "{}")"#, bin_path),
- _ => format!(r#"export PATH="{}:$PATH""#, bin_path), // bash, zsh, oil
- }
-}
-
-#[rstest]
-// Test with bash (POSIX baseline) and fish (different syntax)
-// zsh removed - too similar to bash
-#[case("bash")]
-#[case("fish")]
-// Tier 2: Shells requiring extra setup
-// TODO: Fix non-core shells - elvish/nushell fail with "Parse error: unexpected rune '\x1b'"
-// when parsing ANSI escape codes. Powershell and xonsh fail with syntax errors when they
-// encounter emoji characters in the output. Need to investigate if we need to disable colors
-// and emojis for these shells or if they need special handling.
-// #[cfg_attr(feature = "tier-2-integration-tests", case("elvish"))]
-// #[cfg_attr(feature = "tier-2-integration-tests", case("nushell"))]
-#[cfg_attr(feature = "tier-2-integration-tests", case("oil"))]
-// #[cfg_attr(feature = "tier-2-integration-tests", case("powershell"))]
-// #[cfg_attr(feature = "tier-2-integration-tests", case("xonsh"))]
-fn test_e2e_switch_changes_directory(#[case] shell: &str) {
- let repo = TestRepo::new();
- repo.commit("Initial commit");
-
- let init_code = generate_init_code(&repo, shell);
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
-
- let script = format!(
- r#"
- {}
- {}
- wt switch --create my-feature
- pwd
- "#,
- path_export_syntax(shell, &bin_path),
- init_code
- );
-
- let output = execute_shell_script(&repo, shell, &script);
-
- // Verify that pwd shows we're in a worktree directory containing "my-feature"
- assert!(
- output.contains("my-feature"),
- "Expected pwd to show my-feature worktree, got: {}",
- output
- );
-}
#[rstest]
-// Test with bash (POSIX baseline) and fish (different syntax)
-// zsh removed - too similar to bash
+// bash is baseline, fish exercises alternate syntax
#[case("bash")]
#[case("fish")]
-// Tier 2: Shells requiring extra setup
-// TODO: Fix non-core shells - elvish/nushell fail with "Parse error: unexpected rune '\x1b'"
-// when parsing ANSI escape codes. Powershell and xonsh fail with syntax errors when they
-// encounter emoji characters in the output. Need to investigate if we need to disable colors
-// and emojis for these shells or if they need special handling.
-// #[cfg_attr(feature = "tier-2-integration-tests", case("elvish"))]
-// #[cfg_attr(feature = "tier-2-integration-tests", case("nushell"))]
+// Oil remains optional until tier-2 feature flag is enabled
#[cfg_attr(feature = "tier-2-integration-tests", case("oil"))]
-// #[cfg_attr(feature = "tier-2-integration-tests", case("powershell"))]
-// #[cfg_attr(feature = "tier-2-integration-tests", case("xonsh"))]
-fn test_e2e_remove_returns_to_main(#[case] shell: &str) {
+fn test_e2e_switch_and_remove_roundtrip(#[case] shell: &str) {
let mut repo = TestRepo::new();
repo.commit("Initial commit");
repo.setup_remote("main");
let init_code = generate_init_code(&repo, shell);
- let repo_path = repo.root_path().to_string_lossy().to_string();
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
+ let bin_path = wt_bin_dir();
let script = format!(
r#"
{}
{}
- wt switch --create my-feature
+ wt switch --create combo-branch
+ echo "__PWD_AFTER_SWITCH__ $PWD"
wt remove
- pwd
+ echo "__PWD_AFTER_REMOVE__ $PWD"
"#,
path_export_syntax(shell, &bin_path),
init_code
@@ -187,180 +33,127 @@ fn test_e2e_remove_returns_to_main(#[case] shell: &str) {
let output = execute_shell_script(&repo, shell, &script);
- // Verify that pwd shows we're back in the main repo directory
+ // Ensure human output is still visible (not just directives)
assert!(
- output.trim().ends_with(&repo_path),
- "Expected pwd to show main repo at {}, got: {}",
- repo_path,
+ output.contains("combo-branch"),
+ "Combined e2e run should mention combo-branch, got:\n{}",
output
);
-}
-
-#[test]
-fn test_bash_e2e_switch_preserves_output() {
- let repo = TestRepo::new();
- repo.commit("Initial commit");
-
- let init_code = generate_init_code(&repo, "bash");
-
- let script = format!(
- r#"
- export PATH="{}:$PATH"
- {}
- wt switch --create test-branch 2>&1
- "#,
- get_cargo_bin("wt").parent().unwrap().to_string_lossy(),
- init_code
- );
- let output = execute_shell_script(&repo, "bash", &script);
-
- // Verify that user-facing output is preserved (not just directives)
+ // Directives must remain hidden from the user.
assert!(
- output.contains("test-branch") || output.contains("Created") || output.contains("Switched"),
- "Expected informative output, got: {}",
+ !output.contains("__WORKTRUNK"),
+ "Directive leakage detected in shell output:\n{}",
output
);
- // Verify directives are NOT shown to user
- assert!(
- !output.contains("__WORKTRUNK_CD__"),
- "Directives should not be visible to user, got: {}",
- output
- );
-}
-
-#[test]
-fn test_bash_e2e_error_handling() {
- let repo = TestRepo::new();
- repo.commit("Initial commit");
- let init_code = generate_init_code(&repo, "bash");
+ let after_switch =
+ extract_pwd_marker(&output, "__PWD_AFTER_SWITCH__").expect("Missing switch marker");
+ let after_remove =
+ extract_pwd_marker(&output, "__PWD_AFTER_REMOVE__").expect("Missing remove marker");
- // Try to switch to a branch twice (should error on second attempt)
- let script = format!(
- r#"
- export PATH="{}:$PATH"
- {}
- wt switch --create test-feature
- wt switch --create test-feature 2>&1 || echo "ERROR_CAUGHT"
- "#,
- get_cargo_bin("wt").parent().unwrap().to_string_lossy(),
- init_code
+ assert!(
+ after_switch.contains("combo-branch"),
+ "Shell should cd into combo-branch worktree, saw: {}",
+ after_switch
);
- let output = execute_shell_script(&repo, "bash", &script);
-
- // Verify that error is caught and handled
+ let repo_root = repo.root_path().to_string_lossy();
assert!(
- output.contains("ERROR_CAUGHT")
- || output.contains("already exists")
- || output.contains("error"),
- "Expected error output when switching to same branch twice, got: {}",
- output
+ after_remove.ends_with(repo_root.as_ref()),
+ "Shell should cd back to repo root {} after remove, got: {}",
+ repo_root,
+ after_remove
);
}
#[test]
-fn test_bash_e2e_switch_to_existing_worktree() {
+fn test_bash_e2e_error_handling() {
let repo = TestRepo::new();
repo.commit("Initial commit");
let init_code = generate_init_code(&repo, "bash");
+ let bin_path = wt_bin_dir();
- // Create worktree, move away, then switch back to it (without --create)
let script = format!(
r#"
- export PATH="{}:$PATH"
{}
- wt switch --create existing-branch
- pwd
- cd /tmp
- wt switch existing-branch
- pwd
+ {}
+ wt switch --create dup-branch
+ if wt switch --create dup-branch 2>&1; then
+ echo "__UNEXPECTED_SUCCESS__"
+ else
+ echo "__DUPLICATE_ERROR__"
+ fi
"#,
- get_cargo_bin("wt").parent().unwrap().to_string_lossy(),
+ path_export_syntax("bash", &bin_path),
init_code
);
let output = execute_shell_script(&repo, "bash", &script);
-
- // Should show the existing-branch path twice (once after creation, once after switching back)
- let count = output.matches("existing-branch").count();
assert!(
- count >= 2,
- "Expected to see existing-branch path at least twice, got: {}",
+ output.contains("__DUPLICATE_ERROR__"),
+ "Second switch should have failed, output: {}",
output
);
-}
-
-#[test]
-fn test_bash_e2e_multiple_switches() {
- let mut repo = TestRepo::new();
- repo.commit("Initial commit");
- repo.setup_remote("main");
-
- let init_code = generate_init_code(&repo, "bash");
-
- // Test that multiple switches work
- let script = format!(
- r#"
- export PATH="{}:$PATH"
- {}
- wt switch --create test-branch
- pwd
- wt remove
- pwd
- "#,
- get_cargo_bin("wt").parent().unwrap().to_string_lossy(),
- init_code
- );
-
- let output = execute_shell_script(&repo, "bash", &script);
-
- // Should have switched to test-branch
assert!(
- output.contains("test-branch"),
- "Expected wt switch to work, got: {}",
+ output.contains("already exists") || output.contains("Branch \"dup-branch\""),
+ "User-facing error details missing: {}",
output
);
-
- // Should have returned to test-repo (wt remove should work)
assert!(
- output.contains("test-repo"),
- "Expected wt remove to work, got: {}",
+ !output.contains("__WORKTRUNK"),
+ "Directive leakage detected in error flow: {}",
output
);
}
#[test]
-fn test_bash_e2e_switch_linebreaks() {
+fn test_bash_e2e_switch_existing_worktree() {
let repo = TestRepo::new();
repo.commit("Initial commit");
let init_code = generate_init_code(&repo, "bash");
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
+ let bin_path = wt_bin_dir();
+ let repo_root = repo.root_path().display();
- // Script that switches and immediately echoes a marker to count linebreaks
let script = format!(
r#"
{}
{}
- wt switch --create test-branch 2>&1
- echo "MARKER"
+ wt switch --create existing-branch
+ echo "__AFTER_CREATE__ $PWD"
+ REPO_ROOT="{}"
+ cd "$REPO_ROOT"
+ wt switch existing-branch
+ echo "__AFTER_EXISTING__ $PWD"
"#,
path_export_syntax("bash", &bin_path),
- init_code
+ init_code,
+ repo_root
);
let output = execute_shell_script(&repo, "bash", &script);
+ let after_create =
+ extract_pwd_marker(&output, "__AFTER_CREATE__").expect("missing create marker");
+ let after_existing =
+ extract_pwd_marker(&output, "__AFTER_EXISTING__").expect("missing existing marker");
+
+ assert!(
+ after_create.contains("existing-branch"),
+ "First switch should cd into worktree, saw: {}",
+ after_create
+ );
+ assert!(
+ after_existing.contains("existing-branch"),
+ "Switching to existing worktree should cd there again, saw: {}",
+ after_existing
+ );
+}
- // Setup insta settings to normalize paths
- let settings = crate::common::setup_snapshot_settings(&repo);
- settings.bind(|| {
- insta::assert_snapshot!("bash_e2e_switch_linebreaks", output);
- });
+fn extract_pwd_marker(output: &str, marker: &str) -> Option<String> {
+ output
+ .lines()
+ .find(|line| line.contains(marker))
+ .map(|line| line.split(marker).nth(1).unwrap_or("").trim().to_string())
}
diff --git a/tests/integration_tests/e2e_shell_post_start.rs b/tests/integration_tests/e2e_shell_post_start.rs
index 487d4fadb..3b87b4dd2 100644
--- a/tests/integration_tests/e2e_shell_post_start.rs
+++ b/tests/integration_tests/e2e_shell_post_start.rs
@@ -1,106 +1,12 @@
-use crate::common::{TestRepo, wt_command};
-use insta_cmd::get_cargo_bin;
+use crate::common::{
+ TestRepo,
+ shell::{execute_shell_script, generate_init_code, path_export_syntax, wt_bin_dir},
+};
use rstest::rstest;
use std::fs;
-use std::process::Command;
use std::thread;
use std::time::Duration;
-/// Map shell display names to actual binary names
-fn get_shell_binary(shell: &str) -> &str {
- match shell {
- "nushell" => "nu",
- "powershell" => "pwsh",
- "oil" => "osh",
- _ => shell,
- }
-}
-
-/// Execute a shell script in the given shell and return stdout
-fn execute_shell_script(repo: &TestRepo, shell: &str, script: &str) -> String {
- let binary = get_shell_binary(shell);
- let mut cmd = Command::new(binary);
- repo.clean_cli_env(&mut cmd);
-
- // Additional shell-specific isolation to prevent user config interference
- cmd.env_remove("BASH_ENV");
- cmd.env_remove("ENV"); // for sh/dash
- cmd.env_remove("ZDOTDIR"); // for zsh
- cmd.env_remove("XONSHRC"); // for xonsh
- cmd.env_remove("XDG_CONFIG_HOME"); // for elvish and others
-
- // Prevent loading user config files
- match shell {
- "fish" => {
- cmd.arg("--no-config");
- }
- "powershell" | "pwsh" => {
- cmd.arg("-NoProfile");
- }
- "xonsh" => {
- cmd.arg("--no-rc");
- }
- "nushell" | "nu" => {
- cmd.arg("--no-config-file");
- }
- _ => {}
- }
-
- let output = cmd
- .arg("-c")
- .arg(script)
- .current_dir(repo.root_path())
- .output()
- .unwrap_or_else(|e| panic!("Failed to execute {} script: {}", shell, e));
-
- if !output.status.success() {
- panic!(
- "Shell script failed:\nstdout: {}\nstderr: {}",
- String::from_utf8_lossy(&output.stdout),
- String::from_utf8_lossy(&output.stderr)
- );
- }
-
- String::from_utf8(output.stdout).expect("Invalid UTF-8 in output")
-}
-
-/// Generate shell integration code for the given shell
-fn generate_init_code(repo: &TestRepo, shell: &str) -> String {
- let mut cmd = wt_command();
- repo.clean_cli_env(&mut cmd);
-
- let output = cmd
- .args(["init", shell])
- .current_dir(repo.root_path())
- .output()
- .expect("Failed to generate init code");
-
- // 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)
- );
- }
-
- stdout
-}
-
-/// Generate shell-specific PATH export syntax
-fn path_export_syntax(shell: &str, bin_path: &str) -> String {
- match shell {
- "fish" => format!(r#"set -x PATH {} $PATH"#, bin_path),
- "nushell" => format!(r#"$env.PATH = ($env.PATH | prepend "{}")"#, bin_path),
- "powershell" => format!(r#"$env:PATH = "{}:$env:PATH""#, bin_path),
- "elvish" => format!(r#"set E:PATH = {}:$E:PATH"#, bin_path),
- "xonsh" => format!(r#"$PATH.insert(0, "{}")"#, bin_path),
- _ => format!(r#"export PATH="{}:$PATH""#, bin_path), // bash, zsh, oil
- }
-}
-
/// Test that post-start background commands work with shell integration
#[rstest]
// Test with bash (POSIX baseline) and fish (different syntax)
@@ -140,11 +46,7 @@ approved-commands = ["sleep 0.5 && echo 'Background task done' > bg_marker.txt"]
.expect("Failed to write user config");
let init_code = generate_init_code(&repo, shell);
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
+ let bin_path = wt_bin_dir();
let script = format!(
r#"
@@ -264,11 +166,7 @@ approved-commands = [
.expect("Failed to write test config");
let init_code = generate_init_code(&repo, "bash");
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
+ let bin_path = wt_bin_dir();
let script = format!(
r#"
@@ -337,11 +235,7 @@ approved-commands = ["echo 'Setup done' > setup.txt"]
.expect("Failed to write test config");
let init_code = generate_init_code(&repo, "bash");
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
+ let bin_path = wt_bin_dir();
let worktree_path = repo
.root_path()
@@ -415,11 +309,7 @@ approved-commands = ["sleep 0.5 && echo 'Fish background done' > fish_bg.txt"]
.expect("Failed to write test config");
let init_code = generate_init_code(&repo, "fish");
- let bin_path = get_cargo_bin("wt")
- .parent()
- .unwrap()
- .to_string_lossy()
- .to_string();
+ let bin_path = wt_bin_dir();
let script = format!(
r#"
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index fcb02d57a..50a7c3c56 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -1,112 +1,43 @@
-use crate::common::{TestRepo, wt_command};
+use crate::common::{TestRepo, list_snapshots, wt_command};
use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
+use std::path::Path;
use std::process::Command;
-/// Helper to create snapshot with normalized paths and SHAs
fn snapshot_list(test_name: &str, repo: &TestRepo) {
- snapshot_list_from_dir(test_name, repo, repo.root_path());
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command(repo, repo.root_path()),
+ );
}
-/// Helper to create snapshot with normalized paths and SHAs from a specific directory
-fn snapshot_list_from_dir(test_name: &str, repo: &TestRepo, cwd: &std::path::Path) {
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
-
- // Normalize paths - replace absolute paths with semantic names
- settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
- for (name, path) in &repo.worktrees {
- settings.add_filter(
- path.to_str().unwrap(),
- format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
- );
- }
-
- // Normalize git SHAs (7-40 hex chars) to [SHA] padded to 8 chars
- settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA] ");
-
- // Normalize Windows paths to Unix style
- settings.add_filter(r"\\", "/");
-
- settings.bind(|| {
- let mut cmd = wt_command();
- // Clean environment to avoid interference from global git config
- repo.clean_cli_env(&mut cmd);
- cmd.arg("list").current_dir(cwd);
-
- assert_cmd_snapshot!(test_name, cmd);
- });
+fn snapshot_list_from_dir(test_name: &str, repo: &TestRepo, cwd: &Path) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command(repo, cwd),
+ );
}
-/// Helper to create snapshot for JSON output with normalized paths, SHAs, and timestamps
fn snapshot_list_json(test_name: &str, repo: &TestRepo) {
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
-
- // Normalize paths - replace absolute paths with semantic names
- settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
- for (name, path) in &repo.worktrees {
- settings.add_filter(
- path.to_str().unwrap(),
- format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
- );
- }
-
- // Normalize git SHAs (40 hex chars in JSON)
- settings.add_filter(r#""head": "[0-9a-f]{40}""#, r#""head": "[SHA]""#);
-
- // Normalize timestamps to fixed value
- settings.add_filter(r#""timestamp": \d+"#, r#""timestamp": 0"#);
-
- // Normalize ANSI escape codes to readable placeholders
- settings.add_filter(r"\\u001b\[32m", "[GREEN]"); // ADDITION color
- settings.add_filter(r"\\u001b\[31m", "[RED]"); // DELETION color
- settings.add_filter(r"\\u001b\[2m", "[DIM]"); // Dimming
- settings.add_filter(r"\\u001b\[0m", "[RESET]"); // Style reset
-
- // Normalize Windows paths to Unix style
- settings.add_filter(r"\\\\", "/");
-
- settings.bind(|| {
- let mut cmd = wt_command();
- // Clean environment to avoid interference from global git config
- repo.clean_cli_env(&mut cmd);
- cmd.arg("list")
- .arg("--format=json")
- .current_dir(repo.root_path());
-
- assert_cmd_snapshot!(test_name, cmd);
- });
+ run_snapshot(
+ list_snapshots::json_settings(repo),
+ test_name,
+ list_snapshots::command_json(repo),
+ );
}
-/// Helper to create snapshot with --branches flag
fn snapshot_list_with_branches(test_name: &str, repo: &TestRepo) {
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
-
- // Normalize paths - replace absolute paths with semantic names
- settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
- for (name, path) in &repo.worktrees {
- settings.add_filter(
- path.to_str().unwrap(),
- format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
- );
- }
-
- // Normalize git SHAs (7-40 hex chars) to [SHA] padded to 8 chars
- settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA] ");
-
- // Normalize Windows paths to Unix style
- settings.add_filter(r"\\", "/");
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_branches(repo),
+ );
+}
+fn run_snapshot(settings: Settings, test_name: &str, mut cmd: Command) {
settings.bind(|| {
- let mut cmd = wt_command();
- // Clean environment to avoid interference from global git config
- repo.clean_cli_env(&mut cmd);
- cmd.arg("list")
- .arg("--branches")
- .current_dir(repo.root_path());
-
assert_cmd_snapshot!(test_name, cmd);
});
}
diff --git a/tests/integration_tests/spacing_edge_cases.rs b/tests/integration_tests/spacing_edge_cases.rs
index aa7228774..646274b3e 100644
--- a/tests/integration_tests/spacing_edge_cases.rs
+++ b/tests/integration_tests/spacing_edge_cases.rs
@@ -1,29 +1,26 @@
-use crate::common::{TestRepo, wt_command};
+use crate::common::{TestRepo, list_snapshots};
use insta::Settings;
use insta_cmd::assert_cmd_snapshot;
+use std::process::Command;
-/// Helper to create snapshot with normalized paths and SHAs
fn snapshot_list(test_name: &str, repo: &TestRepo) {
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
-
- // Normalize paths
- settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
- for (name, path) in &repo.worktrees {
- settings.add_filter(
- path.to_str().unwrap(),
- format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
- );
- }
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command(repo, repo.root_path()),
+ );
+}
- // Normalize git SHAs
- settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA] ");
- settings.add_filter(r"\\", "/");
+fn snapshot_list_with_width(test_name: &str, repo: &TestRepo, width: usize) {
+ run_snapshot(
+ list_snapshots::standard_settings(repo),
+ test_name,
+ list_snapshots::command_with_width(repo, width),
+ );
+}
+fn run_snapshot(settings: Settings, test_name: &str, mut cmd: Command) {
settings.bind(|| {
- let mut cmd = wt_command();
- repo.clean_cli_env(&mut cmd);
- cmd.arg("list").current_dir(repo.root_path());
assert_cmd_snapshot!(test_name, cmd);
});
}
@@ -90,67 +87,6 @@ fn test_mixed_length_branch_names() {
snapshot_list("mixed_length_branch_names", &repo);
}
-/// Helper for testing with specific terminal width
-fn snapshot_list_with_width(test_name: &str, repo: &TestRepo, width: usize) {
- let mut settings = Settings::clone_current();
- settings.set_snapshot_path("../snapshots");
-
- // Normalize paths
- settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
- for (name, path) in &repo.worktrees {
- settings.add_filter(
- path.to_str().unwrap(),
- format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
- );
- }
-
- // Normalize git SHAs
- settings.add_filter(r"\b[0-9a-f]{7,40}\b", "[SHA] ");
- settings.add_filter(r"\\", "/");
-
- settings.bind(|| {
- let mut cmd = wt_command();
- repo.clean_cli_env(&mut cmd);
- cmd.arg("list")
- .current_dir(repo.root_path())
- .env("COLUMNS", width.to_string());
- assert_cmd_snapshot!(test_name, cmd);
- });
-}
-
-#[test]
-fn test_terminal_width_80_drops_message() {
- let mut repo = TestRepo::new();
- repo.commit("Initial commit with a reasonably long message");
-
- repo.add_worktree("feature-a", "feature-a");
- repo.add_worktree("feature-b", "feature-b");
-
- snapshot_list_with_width("terminal_width_80", &repo, 80);
-}
-
-#[test]
-fn test_terminal_width_120_shows_message() {
- let mut repo = TestRepo::new();
- repo.commit("Initial commit with a reasonably long message");
-
- repo.add_worktree("feature-a", "feature-a");
- repo.add_worktree("feature-b", "feature-b");
-
- snapshot_list_with_width("terminal_width_120", &repo, 120);
-}
-
-#[test]
-fn test_terminal_width_150_shows_all_columns() {
- let mut repo = TestRepo::new();
- repo.commit("Initial commit with a reasonably long message");
-
- repo.add_worktree("feature-a", "feature-a");
- repo.add_worktree("feature-b", "feature-b");
-
- snapshot_list_with_width("terminal_width_150", &repo, 150);
-}
-
// Column alignment tests with varying diff sizes
// (Merged from column_alignment.rs)
diff --git a/tests/snapshots/integration__integration_tests__e2e_shell__bash_e2e_switch_linebreaks.snap b/tests/snapshots/integration__integration_tests__e2e_shell__bash_e2e_switch_linebreaks.snap
deleted file mode 100644
index b9f416587..000000000
--- a/tests/snapshots/integration__integration_tests__e2e_shell__bash_e2e_switch_linebreaks.snap
+++ /dev/null
@@ -1,6 +0,0 @@
----
-source: tests/integration_tests/e2e_shell.rs
-expression: output
----
-✅ Created new worktree for test-branch from main: [REPO].test-branch
-MARKER
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap
index 912b91260..77e95c682 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_display_fields.snap
@@ -1,5 +1,6 @@
---
source: tests/integration_tests/list.rs
+assertion_line: 41
info:
program: wt
args:
@@ -12,11 +13,10 @@ info:
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/.tmpPNsmM7/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpCCQixx/test-config.toml
---
success: true
exit_code: 0
@@ -105,10 +105,10 @@ exit_code: 0
"upstream_divergence": "",
"working_tree": "?!"
},
- "commits_display": "[GREEN]↑2[RESET] [DIM][RED]↓2[RESET]",
- "branch_diff_display": "[GREEN]+1[RESET]",
+ "commits_display": "/u001b[32m↑2/u001b[0m /u001b[2m/u001b[31m↓2/u001b[0m",
+ "branch_diff_display": "/u001b[32m+1/u001b[0m",
"status_display": " ↕ ?!",
- "working_diff_display": "[GREEN]+1[RESET] [RED]-1[RESET]"
+ "working_diff_display": "/u001b[32m+1/u001b[0m /u001b[31m-1/u001b[0m"
},
{
"type": "worktree",
@@ -149,7 +149,7 @@ exit_code: 0
"upstream_divergence": "",
"working_tree": ""
},
- "commits_display": "[DIM][RED]↓2[RESET]",
+ "commits_display": "/u001b[2m/u001b[31m↓2/u001b[0m",
"status_display": " ∅ ↓"
}
]
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
index a0ec78c9e..daa923fec 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
@@ -1,5 +1,6 @@
---
source: tests/integration_tests/list.rs
+assertion_line: 41
info:
program: wt
args:
@@ -12,11 +13,10 @@ info:
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/.tmppUorei/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp0q8xIc/test-config.toml
---
success: true
exit_code: 0
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap
index a67e5dc7f..7626a5796 100644
--- a/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap
+++ b/tests/snapshots/integration__integration_tests__list__json_with_user_status.snap
@@ -1,5 +1,6 @@
---
source: tests/integration_tests/list.rs
+assertion_line: 41
info:
program: wt
args:
@@ -12,11 +13,10 @@ info:
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/.tmpEC1bKF/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmptkJhnO/test-config.toml
---
success: true
exit_code: 0
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_120.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_120.snap
deleted file mode 100644
index fa16532a1..000000000
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_120.snap
+++ /dev/null
@@ -1,30 +0,0 @@
----
-source: tests/integration_tests/spacing_edge_cases.rs
-info:
- program: wt
- args:
- - list
- env:
- CLICOLOR_FORCE: "1"
- COLUMNS: "120"
- 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/.tmpRQfY4R/test-config.toml
----
-success: true
-exit_code: 0
------ stdout -----
-Branch  Status HEAD± main↕ Path  Commit  Age  Message
-main  ./test-repo a7bc47ca 10 months ago Initial commit with a reasonably long message
-feature-a ≡ ./feature-a a7bc47ca 10 months ago Initial commit with a reasonably long message
-feature-b ≡ ./feature-b a7bc47ca 10 months ago Initial commit with a reasonably long message
-
-⚪ Showing 3 worktrees
-
------ stderr -----
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_150.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_150.snap
deleted file mode 100644
index cd0d01e90..000000000
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_150.snap
+++ /dev/null
@@ -1,30 +0,0 @@
----
-source: tests/integration_tests/spacing_edge_cases.rs
-info:
- program: wt
- args:
- - list
- env:
- CLICOLOR_FORCE: "1"
- COLUMNS: "150"
- 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/.tmp8g8Jim/test-config.toml
----
-success: true
-exit_code: 0
------ stdout -----
-Branch  Status HEAD± main↕ Path  Remote↕ Commit  Age  Message
-main  ./test-repo a7bc47ca 10 months ago Initial commit with a reasonably long message
-feature-a ≡ ./feature-a a7bc47ca 10 months ago Initial commit with a reasonably long message
-feature-b ≡ ./feature-b a7bc47ca 10 months ago Initial commit with a reasonably long message
-
-⚪ Showing 3 worktrees
-
------ stderr -----
diff --git a/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_80.snap b/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_80.snap
deleted file mode 100644
index 52b6f2f1f..000000000
--- a/tests/snapshots/integration__integration_tests__spacing_edge_cases__terminal_width_80.snap
+++ /dev/null
@@ -1,30 +0,0 @@
----
-source: tests/integration_tests/spacing_edge_cases.rs
-info:
- program: wt
- args:
- - list
- env:
- CLICOLOR_FORCE: "1"
- COLUMNS: "80"
- 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/.tmpgF58RE/test-config.toml
----
-success: true
-exit_code: 0
------ stdout -----
-Branch  Status Path  Commit  Age  Message
-main  ./test-repo a7bc47ca 10 months ago Initial commit with...
-feature-a ≡ ./feature-a a7bc47ca 10 months ago Initial commit with...
-feature-b ≡ ./feature-b a7bc47ca 10 months ago Initial commit with...
-
-⚪ Showing 3 worktrees
-
------ stderr -----