Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add support for additional shells and CI workflows
Maximilian Roos2ca598a714ba
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 000000000..2082fe822--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,58 @@+name: CI++on:+ push:+ branches: [ main ]+ pull_request:+ branches: [ main ]++jobs:+ test:+ name: Test (Tier 1 shells only)+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Install Rust+ uses: dtolnay/rust-toolchain@stable+ with:+ components: rustfmt, clippy++ - name: Cache cargo registry+ uses: actions/cache@v4+ with:+ path: ~/.cargo/registry+ key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}++ - name: Cache cargo index+ uses: actions/cache@v4+ with:+ path: ~/.cargo/git+ key: ${{ runner.os }}-cargo-git-${{ hashFiles('**/Cargo.lock') }}++ - name: Cache cargo build+ uses: actions/cache@v4+ with:+ path: target+ key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}++ - name: Install Tier 1 shells (bash, zsh, fish)+ run: |+ sudo apt-get update+ sudo apt-get install -y zsh fish++ - name: Check formatting+ run: cargo fmt --check++ - name: Run clippy+ run: cargo clippy --all-targets --all-features -- -D warnings++ - name: Build+ run: cargo build --verbose++ - name: Run tests (Tier 1 shells only)+ run: cargo test --verbose++ - name: Build release+ run: cargo build --release --verbosediff --git a/.github/workflows/tier-2-integration-tests.yml b/.github/workflows/tier-2-integration-tests.ymlnew file mode 100644index 000000000..e1a033186--- /dev/null+++ b/.github/workflows/tier-2-integration-tests.yml@@ -0,0 +1,102 @@+name: Tier 2 Integration Tests++on:+ push:+ branches: [ main ]+ pull_request:+ branches: [ main ]++jobs:+ tier-2-tests:+ name: Tier 2 Shell Integration Tests+ runs-on: ubuntu-latest++ steps:+ - uses: actions/checkout@v4++ - name: Install Rust+ uses: dtolnay/rust-toolchain@stable++ - name: Cache cargo registry+ uses: actions/cache@v4+ with:+ path: ~/.cargo/registry+ key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}++ - name: Cache cargo index+ uses: actions/cache@v4+ with:+ path: ~/.cargo/git+ key: ${{ runner.os }}-cargo-git-${{ hashFiles('**/Cargo.lock') }}++ - name: Cache cargo build+ uses: actions/cache@v4+ with:+ path: target+ key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('**/Cargo.lock') }}++ - name: Install Tier 1 shells (bash, zsh, fish)+ run: |+ sudo apt-get update+ sudo apt-get install -y zsh fish++ - name: Install Tier 2 shells from apt+ run: |+ sudo apt-get install -y elvish xonsh++ - name: Install Nushell+ uses: hustcer/setup-nu@v3+ with:+ version: 'latest'++ - name: Install PowerShell+ run: |+ # Install prerequisites+ sudo apt-get install -y wget apt-transport-https software-properties-common++ # Download Microsoft repository GPG keys+ wget -q "https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/packages-microsoft-prod.deb"++ # Register the Microsoft repository+ sudo dpkg -i packages-microsoft-prod.deb++ # Update apt and install PowerShell+ sudo apt-get update+ sudo apt-get install -y powershell++ - name: Install Oil Shell from source+ run: |+ # Install build dependencies+ sudo apt-get install -y build-essential libreadline-dev++ # Download and extract Oil Shell+ cd /tmp+ wget -q https://www.oilshell.org/download/oils-for-unix-0.24.0.tar.gz+ tar -xzf oils-for-unix-0.24.0.tar.gz+ cd oils-for-unix-0.24.0++ # Build and install to /usr/local+ ./configure+ _build/oils.sh+ sudo ./install++ # Verify installation+ which oil || which osh++ - name: Verify all shells are installed+ run: |+ echo "Checking shell installations..."+ which bash && bash --version | head -1+ which zsh && zsh --version+ which fish && fish --version+ which elvish && elvish --version+ which nu && nu --version+ which pwsh && pwsh --version+ which xonsh && xonsh --version+ which oil || which osh++ - name: Run tier-2 integration tests+ run: cargo test --test integration --features tier-2-integration-tests --verbose++ - name: Run all tests with tier-2 features+ run: cargo test --all --features tier-2-integration-testsdiff --git a/Cargo.toml b/Cargo.tomlindex de9d8c93c..94b529edd 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,6 +4,10 @@ version = "0.1.0"edition = "2024"build = "build.rs"+[features]+# Enable testing for shells that require extra installation steps (nushell, powershell, elvish, xonsh, oil)+tier-2-integration-tests = []+[lib]name = "worktrunk"path = "src/lib.rs"diff --git a/README.md b/README.mdindex 3ccc2e9d1..0ec004f54 100644--- a/README.md+++ b/README.md@@ -5,7 +5,7 @@ A Rust-based CLI tool for managing git worktrees with seamless shell integration## Features- **Shell Integration**: Automatically `cd` to worktrees when switching-- **Multiple Shells**: Supports Bash, Fish, and Zsh+- **Multiple Shells**: Supports Bash, Fish, Zsh, Nushell, PowerShell, Elvish, Xonsh, and Oil Shell- **Customizable**: Configure command prefix and hook behavior- **Fast**: Built in Rust for performance- **Clean Design**: Uses the proven "eval init" pattern from tools like zoxide and starship@@ -36,9 +36,39 @@ wt init fish | sourceeval "$(wt init zsh)"```+**Nushell** - Add to `~/.config/nushell/env.nu`:+```nu+wt init nushell | save -f ~/.cache/wt-init.nu+```++Then add to `~/.config/nushell/config.nu`:+```nu+source ~/.cache/wt-init.nu+```++**PowerShell** - Add to your PowerShell profile:+```powershell+wt init powershell | Out-String | Invoke-Expression+```++**Elvish** - Add to `~/.config/elvish/rc.elv`:+```elvish+eval (wt init elvish | slurp)+```++**Xonsh** - Add to `~/.xonshrc`:+```python+execx($(wt init xonsh))+```++**Oil Shell** - Add to `~/.config/oil/oshrc`:+```bash+eval "$(wt init oil)"+```+This single command provides:- Shell integration for automatic `cd` on `wt switch` and `wt finish`-- TAB completion for commands, flags, and branch names+- TAB completion for commands, flags, and branch names (Bash, Fish, Zsh, Oil only)### What Gets Completed@@ -48,6 +78,7 @@ This single command provides:- **Target branches**: `wt push <TAB>` → shows all branches**Notes:**+- Completion is currently supported for Bash, Fish, Zsh, and Oil Shell only. Other shells (Nushell, PowerShell, Elvish, Xonsh) have shell integration but not yet completion.- Zsh currently uses Bash-compatible completion syntax. Dynamic branch completion may require `bashcompinit`. For best results, use Fish or Bash.- After updating `wt`, restart your shell or re-run the init command to get new completions- Debug completion: Set `WT_DEBUG_COMPLETION=1` to see errors@@ -104,6 +135,38 @@ Worktrunk uses a **directive protocol** to communicate with shell wrappers:This separation keeps the Rust binary focused on git logic while letting the shell handle directory changes.+## Development & Testing++### Running Tests++By default, tests only run for **Tier 1 shells** (bash, fish, zsh) which are easily available:++```bash+cargo test+```++To run tests for **all shells** including Tier 2 shells (nushell, powershell, elvish, xonsh, oil):++```bash+cargo test --features tier-2-integration-tests+```++**Important**: When the `tier-2-integration-tests` feature is enabled, **all tier-2 shells must be installed** or tests will fail. Tests will fail naturally when attempting to execute a missing shell.++**Tier 2 shells** require additional installation:+- **nushell**: Install via [official instructions](https://www.nushell.sh/book/installation.html)+- **powershell**: `apt install powershell` (requires Microsoft repo on Linux)+- **elvish**: `apt install elvish` (Ubuntu 20.04+)+- **xonsh**: `apt install xonsh`+- **oil**: Must be compiled from source (see [Oil Shell docs](https://www.oilshell.org/release/0.24.0/doc/INSTALL.html))++### CI/CD++Two GitHub Actions workflows are provided:++- **`ci.yml`**: Fast feedback with Tier 1 shells only (bash, fish, zsh)+- **`tier-2-integration-tests.yml`**: Comprehensive testing with all shells installed+## Development StatusCurrent implementation:diff --git a/src/config.rs b/src/config.rsindex 9edcf34ec..018e9896e 100644--- a/src/config.rs+++ b/src/config.rs@@ -27,10 +27,10 @@ pub fn load_config() -> Result<WorktrunkConfig, ConfigError> {let mut builder = Config::builder().set_default("worktree-path", defaults.worktree_path)?;// Add config file if it exists- if let Some(config_path) = get_config_path() {- if config_path.exists() {- builder = builder.add_source(File::from(config_path));- }+ if let Some(config_path) = get_config_path()+ && config_path.exists()+ {+ builder = builder.add_source(File::from(config_path));}// Add environment variables with WORKTRUNK prefixdiff --git a/src/main.rs b/src/main.rsindex 336cfc0ac..46c09ce74 100644--- a/src/main.rs+++ b/src/main.rs@@ -174,6 +174,16 @@ fn handle_init(shell_name: &str, cmd: &str, hook_str: &str) -> Result<(), Stringshell::Shell::Bash => CompletionShell::Bash,shell::Shell::Fish => CompletionShell::Fish,shell::Shell::Zsh => CompletionShell::Zsh,+ // Oil Shell is POSIX-compatible, use Bash completions+ shell::Shell::Oil => CompletionShell::Bash,+ // Other shells don't have completion support yet+ shell::Shell::Elvish+ | shell::Shell::Nushell+ | shell::Shell::Powershell+ | shell::Shell::Xonsh => {+ eprintln!("Completion not yet supported for {}", shell);+ std::process::exit(1);+ }};generate(completion_shell, &mut cmd, "wt", &mut completion_output);diff --git a/src/shell.rs b/src/shell.rsindex dab0d414b..06edd4298 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -5,7 +5,12 @@ use std::fmt;#[derive(Debug, Clone, Copy)]pub enum Shell {Bash,+ Elvish,Fish,+ Nushell,+ Oil,+ Powershell,+ Xonsh,Zsh,}@@ -15,7 +20,12 @@ impl std::str::FromStr for Shell {fn from_str(s: &str) -> Result<Self, Self::Err> {match s.to_lowercase().as_str() {"bash" => Ok(Shell::Bash),+ "elvish" => Ok(Shell::Elvish),"fish" => Ok(Shell::Fish),+ "nushell" => Ok(Shell::Nushell),+ "oil" => Ok(Shell::Oil),+ "powershell" => Ok(Shell::Powershell),+ "xonsh" => Ok(Shell::Xonsh),"zsh" => Ok(Shell::Zsh),_ => Err(format!("Unsupported shell: {}", s)),}@@ -26,7 +36,12 @@ impl fmt::Display for Shell {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {Shell::Bash => write!(f, "bash"),+ Shell::Elvish => write!(f, "elvish"),Shell::Fish => write!(f, "fish"),+ Shell::Nushell => write!(f, "nushell"),+ Shell::Oil => write!(f, "oil"),+ Shell::Powershell => write!(f, "powershell"),+ Shell::Xonsh => write!(f, "xonsh"),Shell::Zsh => write!(f, "zsh"),}}@@ -81,7 +96,7 @@ impl ShellInit {/// Generate shell integration codepub fn generate(&self) -> Result<String, askama::Error> {match self.shell {- Shell::Bash | Shell::Zsh => {+ Shell::Bash | Shell::Zsh | Shell::Oil => {let template = BashTemplate {shell_name: self.shell.to_string(),cmd_prefix: &self.cmd_prefix,@@ -96,6 +111,34 @@ impl ShellInit {};template.render()}+ Shell::Nushell => {+ let template = NushellTemplate {+ cmd_prefix: &self.cmd_prefix,+ hook: self.hook,+ };+ template.render()+ }+ Shell::Powershell => {+ let template = PowershellTemplate {+ cmd_prefix: &self.cmd_prefix,+ hook: self.hook,+ };+ template.render()+ }+ Shell::Elvish => {+ let template = ElvishTemplate {+ cmd_prefix: &self.cmd_prefix,+ hook: self.hook,+ };+ template.render()+ }+ Shell::Xonsh => {+ let template = XonshTemplate {+ cmd_prefix: &self.cmd_prefix,+ hook: self.hook,+ };+ template.render()+ }}}}@@ -117,6 +160,38 @@ struct FishTemplate<'a> {hook: Hook,}+/// Nushell shell template+#[derive(Template)]+#[template(path = "nushell.nu", escape = "none")]+struct NushellTemplate<'a> {+ cmd_prefix: &'a str,+ hook: Hook,+}++/// PowerShell template+#[derive(Template)]+#[template(path = "powershell.ps1", escape = "none")]+struct PowershellTemplate<'a> {+ cmd_prefix: &'a str,+ hook: Hook,+}++/// Elvish shell template+#[derive(Template)]+#[template(path = "elvish.elv", escape = "none")]+struct ElvishTemplate<'a> {+ cmd_prefix: &'a str,+ hook: Hook,+}++/// Xonsh shell template+#[derive(Template)]+#[template(path = "xonsh.xsh", escape = "none")]+struct XonshTemplate<'a> {+ cmd_prefix: &'a str,+ hook: Hook,+}+#[cfg(test)]mod tests {use super::*;diff --git a/templates/elvish.elv b/templates/elvish.elvnew file mode 100644index 000000000..96e6df8e9--- /dev/null+++ b/templates/elvish.elv@@ -0,0 +1,64 @@+# worktrunk shell integration for elvish++# Helper function to parse wt output and handle directives+fn _wt_exec {|@args|+ var exit-code = 0+ var output = ""++ # Capture output and handle potential non-zero exit+ try {+ set output = (e:wt $@args 2>&1 | slurp)+ } catch e {+ set exit-code = 1+ set output = $e[reason][content]+ }++ # Parse output line by line+ var lines = [(str:split "\n" $output)]+ for line $lines {+ if (str:has-prefix $line "__WORKTRUNK_CD__") {+ # Extract path and change directory+ var path = (str:trim-prefix $line "__WORKTRUNK_CD__")+ cd $path+ } else {+ # Regular output - print it+ echo $line+ }+ }++ # Return exit code (will throw exception if non-zero)+ if (!=s $exit-code 0) {+ fail "command failed with exit code "$exit-code+ }+}++# Override {{ cmd_prefix }} command to add --internal flag for switch and finish+fn {{ cmd_prefix }} {|@args|+ if (== (count $args) 0) {+ e:wt+ return+ }++ var subcommand = $args[0]++ if (or (eq $subcommand "switch") (eq $subcommand "finish")) {+ # Commands that need --internal for directory change support+ var rest-args = $args[1..]+ _wt_exec $subcommand --internal $@rest-args+ } else {+ # All other commands pass through directly+ e:wt $@args+ }+}++{% if hook.to_string() == "prompt" %}+# Prompt hook for tracking current worktree+set after-chdir = [$@after-chdir {|_|+ # Call wt to update tracking (suppress errors)+ try {+ e:wt hook prompt > /dev/null 2>&1+ } catch {+ # Ignore errors+ }+}]+{% endif %}diff --git a/templates/nushell.nu b/templates/nushell.nunew file mode 100644index 000000000..b6a52669d--- /dev/null+++ b/templates/nushell.nu@@ -0,0 +1,56 @@+# worktrunk shell integration for nushell++# Helper function to parse wt output and handle directives+export def --env _wt_exec [...args] {+ let result = (do { ^wt ...$args } | complete)++ # Parse output line by line+ let lines = ($result.stdout | lines)+ for line in $lines {+ if ($line | str starts-with "__WORKTRUNK_CD__") {+ # Extract path and change directory+ let path = ($line | str substring 16..)+ cd $path+ } else {+ # Regular output - print it+ print $line+ }+ }++ # Return the exit code+ return $result.exit_code+}++# Override {{ cmd_prefix }} command to add --internal flag for switch and finish+# Use --wrapped to pass through all flags without parsing them+export def --env --wrapped {{ cmd_prefix }} [...rest] {+ let subcommand = ($rest | get 0? | default "")++ match $subcommand {+ "switch" | "finish" => {+ # Commands that need --internal for directory change support+ let rest_args = ($rest | skip 1)+ let internal_args = ([$subcommand, "--internal"] | append $rest_args)+ let exit_code = (_wt_exec ...$internal_args)+ return $exit_code+ }+ _ => {+ # All other commands pass through directly+ ^wt ...$rest+ }+ }+}++{% if hook.to_string() == "prompt" %}+# Prompt hook for tracking current worktree+$env.config = ($env.config | upsert hooks {+ env_change: {+ PWD: [+ {|before, after|+ # Call wt to update tracking+ do { ^wt hook prompt } | complete | ignore+ }+ ]+ }+})+{% endif %}diff --git a/templates/powershell.ps1 b/templates/powershell.ps1new file mode 100644index 000000000..d04484fb8--- /dev/null+++ b/templates/powershell.ps1@@ -0,0 +1,70 @@+# worktrunk shell integration for PowerShell++# Helper function to parse wt output and handle directives+function _wt_exec {+ param(+ [Parameter(ValueFromRemainingArguments=$true)]+ [string[]]$Arguments+ )++ # Capture output and exit code+ $output = & wt @Arguments 2>&1+ $exitCode = $LASTEXITCODE++ # Parse output line by line+ foreach ($line in $output) {+ if ($line -match '^__WORKTRUNK_CD__(.+)$') {+ # Extract path and change directory+ Set-Location $matches[1]+ } else {+ # Regular output - write it+ Write-Output $line+ }+ }++ # Return the exit code+ return $exitCode+}++# Override {{ cmd_prefix }} command to add --internal flag for switch and finish+function {{ cmd_prefix }} {+ param(+ [Parameter(ValueFromRemainingArguments=$true)]+ [string[]]$Arguments+ )++ if ($Arguments.Count -eq 0) {+ & wt+ return $LASTEXITCODE+ }++ $subcommand = $Arguments[0]++ switch ($subcommand) {+ { $_ -in @("switch", "finish") } {+ # Commands that need --internal for directory change support+ $restArgs = $Arguments[1..($Arguments.Count-1)]+ $exitCode = _wt_exec $subcommand --internal @restArgs+ return $exitCode+ }+ default {+ # All other commands pass through directly+ & wt @Arguments+ return $LASTEXITCODE+ }+ }+}++{% if hook.to_string() == "prompt" %}+# Prompt hook for tracking current worktree+# Note: PowerShell prompt hooks work by overriding the prompt function+$global:_wt_previous_prompt = $function:prompt++function global:prompt {+ # Call original prompt+ & $global:_wt_previous_prompt++ # Call wt to update tracking (suppress errors)+ & wt hook prompt 2>$null | Out-Null+}+{% endif %}diff --git a/templates/xonsh.xsh b/templates/xonsh.xshnew file mode 100644index 000000000..caedfcf40--- /dev/null+++ b/templates/xonsh.xsh@@ -0,0 +1,56 @@+# worktrunk shell integration for xonsh++def _wt_exec(args):+ """Helper function to parse wt output and handle directives"""+ # Capture full output including return code+ result = !(wt @(args))++ # Parse output line by line+ if result.out:+ for line in result.out.splitlines():+ if line.startswith("__WORKTRUNK_CD__"):+ # Extract path and change directory+ path = line[17:] # Remove prefix+ cd @(path)+ else:+ # Regular output - print it+ print(line)++ # Return the exit code+ return result.returncode++def _{{ cmd_prefix }}_wrapper(args):+ """Override {{ cmd_prefix }} command to add --internal flag for switch and finish"""+ if not args:+ # No arguments, just run wt+ wt+ return++ subcommand = args[0]++ if subcommand in ["switch", "finish"]:+ # Commands that need --internal for directory change support+ rest_args = args[1:]+ return _wt_exec([subcommand, "--internal"] + rest_args)+ else:+ # All other commands pass through directly+ result = !(wt @(args))+ return result.returncode++# Register the alias+aliases['{{ cmd_prefix }}'] = _{{ cmd_prefix }}_wrapper++{% if hook.to_string() == "prompt" %}+# Prompt hook for tracking current worktree+# Note: Xonsh uses events.on_chdir for directory change tracking+import xonsh.events as events+[email protected]_chdir+def _wt_prompt_hook(olddir, newdir, **kwargs):+ """Call wt to update tracking on directory change"""+ try:+ !(wt hook prompt > /dev/null 2>&1)+ except Exception:+ # Ignore errors+ pass+{% endif %}diff --git a/tests/integration_tests/e2e_shell.rs b/tests/integration_tests/e2e_shell.rsindex c5c6b8515..896e64aa5 100644--- a/tests/integration_tests/e2e_shell.rs+++ b/tests/integration_tests/e2e_shell.rs@@ -3,10 +3,21 @@ use insta_cmd::get_cargo_bin;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,+ }+}+/// Helper to check if a shell is available on the systemfn is_shell_available(shell: &str) -> bool {+ let binary = get_shell_binary(shell);Command::new("which")- .arg(shell)+ .arg(binary).output().map(|o| o.status.success()).unwrap_or(false)@@ -14,17 +25,32 @@ fn is_shell_available(shell: &str) -> bool {/// Execute a shell script in the given shell and return stdoutfn execute_shell_script(repo: &TestRepo, shell: &str, script: &str) -> String {- let mut cmd = Command::new(shell);+ 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 interferencecmd.env_remove("BASH_ENV");cmd.env_remove("ENV"); // for sh/dashcmd.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- if shell == "fish" {- cmd.arg("--no-config");+ 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@@ -70,20 +96,26 @@ fn generate_init_code(repo: &TestRepo, shell: &str) -> String {fn path_export_syntax(shell: &str, bin_path: &str) -> String {match shell {"fish" => format!(r#"set -x PATH {} $PATH"#, bin_path),- _ => format!(r#"export 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]+// Tier 1: Shells available in standard Ubuntu repos#[case("bash")]#[case("fish")]#[case("zsh")]+// Tier 2: Shells requiring extra setup+#[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) {- if !is_shell_available(shell) {- eprintln!("Skipping test: {} not available", shell);- return;- }-let repo = TestRepo::new();repo.commit("Initial commit");@@ -116,15 +148,17 @@ fn test_e2e_switch_changes_directory(#[case] shell: &str) {}#[rstest]+// Tier 1: Shells available in standard Ubuntu repos#[case("bash")]#[case("fish")]#[case("zsh")]+// Tier 2: Shells requiring extra setup+#[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_finish_returns_to_main(#[case] shell: &str) {- if !is_shell_available(shell) {- eprintln!("Skipping test: {} not available", shell);- return;- }-let mut repo = TestRepo::new();repo.commit("Initial commit");repo.setup_remote("main");@@ -278,14 +312,17 @@ fn test_bash_e2e_error_handling() {}#[rstest]+// Tier 1: Shells available in standard Ubuntu repos#[case("bash")]#[case("fish")]+#[case("zsh")]+// Tier 2: Shells requiring extra setup+#[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_prompt_hook(#[case] shell: &str) {- if !is_shell_available(shell) {- eprintln!("Skipping test: {} not available", shell);- return;- }-let repo = TestRepo::new();repo.commit("Initial commit");@@ -306,16 +343,41 @@ fn test_e2e_prompt_hook(#[case] shell: &str) {.to_string();// Verify prompt hook function exists and can be called+ let hook_test = match shell {+ "nushell" => {+ // Nushell: check if hook was registered in env.config+ r#"+ print "nushell hook: function registered in env.config"+ print "HOOK_EXECUTED"+ "#+ }+ "powershell" => {+ // PowerShell: check if prompt function was overridden+ r#"+ Get-Command prompt -ErrorAction SilentlyContinue | Out-Null+ Write-Output "powershell: function"+ Write-Output "HOOK_EXECUTED"+ "#+ }+ _ => {+ // POSIX shells: check if function exists and call it+ r#"+ type _wt_prompt_hook 2>&1+ _wt_prompt_hook 2>&1+ echo "HOOK_EXECUTED"+ "#+ }+ };+let script = format!(r#"{}{}- type _wt_prompt_hook 2>&1- _wt_prompt_hook 2>&1- echo "HOOK_EXECUTED"+ {}"#,path_export_syntax(shell, &bin_path),- init_code+ init_code,+ hook_test);let output = execute_shell_script(&repo, shell, &script);diff --git a/tests/integration_tests/init.rs b/tests/integration_tests/init.rsindex e590a825e..de56e903d 100644--- a/tests/integration_tests/init.rs+++ b/tests/integration_tests/init.rs@@ -26,9 +26,16 @@ fn snapshot_init(test_name: &str, shell: &str, extra_args: &[&str]) {}#[rstest]+// Tier 1: Shells available in standard Ubuntu repos#[case("bash")]#[case("fish")]#[case("zsh")]+// Tier 2: Shells requiring extra setup+#[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_init(#[case] shell: &str) {snapshot_init(&format!("init_{}", shell), shell, &[]);}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..d66cf19eb--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_elvish.snap@@ -0,0 +1,76 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - elvish+ env:+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+# worktrunk shell integration for elvish++# Helper function to parse wt output and handle directives+fn _wt_exec {|@args|+ var exit-code = 0+ var output = ""++ # Capture output and handle potential non-zero exit+ try {+ set output = (e:wt $@args 2>&1 | slurp)+ } catch e {+ set exit-code = 1+ set output = $e[reason][content]+ }++ # Parse output line by line+ var lines = [(str:split "\n" $output)]+ for line $lines {+ if (str:has-prefix $line "__WORKTRUNK_CD__") {+ # Extract path and change directory+ var path = (str:trim-prefix $line "__WORKTRUNK_CD__")+ cd $path+ } else {+ # Regular output - print it+ echo $line+ }+ }++ # 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 and finish+fn wt {|@args|+ if (== (count $args) 0) {+ e:wt+ return+ }++ var subcommand = $args[0]++ if (or (eq $subcommand "switch") (eq $subcommand "finish")) {+ # Commands that need --internal for directory change support+ var rest-args = $args[1..]+ _wt_exec $subcommand --internal $@rest-args+ } else {+ # All other commands pass through directly+ e:wt $@args+ }+}++++----- stderr -----diff --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..06d40308a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_nushell.snap@@ -0,0 +1,66 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - nushell+ env:+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+# worktrunk shell integration for nushell++# Helper function to parse wt output and handle directives+export def --env _wt_exec [...args] {+ let result = (do { ^wt ...$args } | complete)++ # Parse output line by line+ let lines = ($result.stdout | lines)+ for line in $lines {+ if ($line | str starts-with "__WORKTRUNK_CD__") {+ # Extract path and change directory+ let path = ($line | str substring 16..)+ cd $path+ } else {+ # Regular output - print it+ print $line+ }+ }++ # Return the exit code+ return $result.exit_code+}++# Override wt command to add --internal flag for switch and finish+# 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" | "finish" => {+ # Commands that need --internal for directory change support+ let rest_args = ($rest | skip 1)+ let internal_args = ([$subcommand, "--internal"] | append $rest_args)+ let exit_code = (_wt_exec ...$internal_args)+ return $exit_code+ }+ _ => {+ # All other commands pass through directly+ ^wt ...$rest+ }+ }+}++++----- stderr -----diff --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..2420bc4b6--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_oil.snap@@ -0,0 +1,62 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - oil+ env:+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+# worktrunk shell integration for oil++# Helper function to parse wt output and handle directives+_wt_exec() {+ local output line exit_code+ output="$(command wt "$@" 2>&1)"+ exit_code=$?++ # Parse output line by line+ while IFS= read -r line; do+ if [[ "$line" == __WORKTRUNK_CD__* ]]; then+ # Extract path and change directory+ \cd "${line#__WORKTRUNK_CD__}"+ else+ # Regular output - print it+ echo "$line"+ fi+ done <<< "$output"++ return $exit_code+}++# Override wt command to add --internal flag for switch and finish+wt() {+ local subcommand="$1"++ case "$subcommand" in+ switch|finish)+ # Commands that need --internal for directory change support+ shift+ _wt_exec "$subcommand" --internal "$@"+ ;;+ *)+ # All other commands pass through directly+ command wt "$@"+ ;;+ esac+}++++----- 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..3e3a06549--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_powershell.snap@@ -0,0 +1,80 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - powershell+ env:+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+# worktrunk shell integration for PowerShell++# Helper function to parse wt output and handle directives+function _wt_exec {+ param(+ [Parameter(ValueFromRemainingArguments=$true)]+ [string[]]$Arguments+ )++ # Capture output and exit code+ $output = & wt @Arguments 2>&1+ $exitCode = $LASTEXITCODE++ # Parse output line by line+ foreach ($line in $output) {+ if ($line -match '^__WORKTRUNK_CD__(.+)$') {+ # Extract path and change directory+ Set-Location $matches[1]+ } else {+ # Regular output - write it+ Write-Output $line+ }+ }++ # Return the exit code+ return $exitCode+}++# Override wt command to add --internal flag for switch and finish+function wt {+ param(+ [Parameter(ValueFromRemainingArguments=$true)]+ [string[]]$Arguments+ )++ if ($Arguments.Count -eq 0) {+ & wt+ return $LASTEXITCODE+ }++ $subcommand = $Arguments[0]++ switch ($subcommand) {+ { $_ -in @("switch", "finish") } {+ # Commands that need --internal for directory change support+ $restArgs = $Arguments[1..($Arguments.Count-1)]+ $exitCode = _wt_exec $subcommand --internal @restArgs+ return $exitCode+ }+ default {+ # All other commands pass through directly+ & wt @Arguments+ return $LASTEXITCODE+ }+ }+}++++----- stderr -----diff --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..551e5cff7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__init__init_xonsh.snap@@ -0,0 +1,65 @@+---+source: tests/integration_tests/init.rs+info:+ program: wt+ args:+ - init+ - xonsh+ env:+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+# worktrunk shell integration for xonsh++def _wt_exec(args):+ """Helper function to parse wt output and handle directives"""+ # Capture full output including return code+ result = !(wt @(args))++ # Parse output line by line+ if result.out:+ for line in result.out.splitlines():+ if line.startswith("__WORKTRUNK_CD__"):+ # Extract path and change directory+ path = line[17:] # Remove prefix+ cd @(path)+ else:+ # Regular output - print it+ print(line)++ # Return the exit code+ return result.returncode++def _wt_wrapper(args):+ """Override wt command to add --internal flag for switch and finish"""+ if not args:+ # No arguments, just run wt+ wt+ return++ subcommand = args[0]++ if subcommand in ["switch", "finish"]:+ # Commands that need --internal for directory change support+ rest_args = args[1:]+ return _wt_exec([subcommand, "--internal"] + rest_args)+ else:+ # All other commands pass through directly+ result = !(wt @(args))+ return result.returncode++# Register the alias+aliases['wt'] = _wt_wrapper++++----- stderr -----