Skip to content

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

Read the cd directive file as-is in every shell wrapper (#4608)

Maximilian Roos882e7be57477
diff --git a/src/output/global.rs b/src/output/global.rs
index c9f2a7a5f..726bad7bf 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -19,7 +19,6 @@
//! sets only `WORKTRUNK_DIRECTIVE_FILE`, switch output diagnoses the outdated
//! wrapper and tells the user to reinstall shell integration.
-use std::fs::OpenOptions;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
@@ -259,8 +258,9 @@ pub(crate) fn print_outdated_execute_wrapper_warning() {
}
}
-/// Truncate-write the given path to the CD directive file. The file holds one
-/// line: the absolute path the shell wrapper should `cd` to. Truncate-then-
+/// Truncate-write the given path to the CD directive file. The file holds the
+/// absolute path the shell wrapper should `cd` to, and nothing else: no
+/// trailing newline, so every reader can take the contents as-is. Truncate-then-
/// write semantics mean the last writer wins, which matches how overlapping
/// `change_directory()` calls should resolve (hook emits a cd after switch
/// emits its own → hook wins).
@@ -268,21 +268,10 @@ pub(crate) fn print_outdated_execute_wrapper_warning() {
/// A failure names the file because the operation has already completed by the
/// time the directive write runs.
fn write_cd_path(file: &Path, path: &Path) -> anyhow::Result<()> {
- write_cd_path_io(file, path)
- .with_context(|| format!("Failed to write the cd directive file {}", file.display()))
-}
-
-fn write_cd_path_io(file: &Path, path: &Path) -> io::Result<()> {
- let mut f = OpenOptions::new()
- .write(true)
- .create(true)
- .truncate(true)
- .open(file)?;
// Lossy for non-UTF-8 paths (extremely rare in practice; worktrunk-
// managed paths are always valid UTF-8).
- f.write_all(path.as_os_str().to_string_lossy().as_bytes())?;
- f.write_all(b"\n")?;
- f.flush()
+ std::fs::write(file, path.as_os_str().to_string_lossy().as_bytes())
+ .with_context(|| format!("Failed to write the cd directive file {}", file.display()))
}
/// Request directory change (for shell integration).
@@ -329,9 +318,7 @@ pub fn withdraw_missing_cd_target() {
let Ok(target) = std::fs::read_to_string(&cd_file) else {
return;
};
- // Strip only the line terminator: a directory name can end in spaces.
- let target = target.trim_end_matches(['\n', '\r']);
- if !target.is_empty() && !Path::new(target).is_dir() {
+ if !target.is_empty() && !Path::new(&target).is_dir() {
let _ = std::fs::File::create(&cd_file);
}
}
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
index 435d9b0e3..1debf1464 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_fish.snap
@@ -37,7 +37,7 @@ function wt
# cd file holds a raw path — read with fish builtin (no cat subprocess,
# safe even if CWD was removed by worktree removal).
if test -s "$cd_file"
- set -l target (string trim < "$cd_file")
+ set -l target (string collect < "$cd_file")
# `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish
# plugin replaces `cd` with a query function that mishandles the `--`
# separator). Matches the bash/zsh wrappers. (#3159)
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
index 9e4fd70cc..97373f323 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_nu.snap
@@ -139,8 +139,8 @@ export def --env --wrapped wt [...args] {
} finally {
try {
# cd file holds a raw path — no shell parsing needed
- if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {
- let target_dir = open $cd_file --raw | str trim
+ if ($cd_file | path exists) and (open $cd_file --raw | is-not-empty) {
+ let target_dir = open $cd_file --raw
cd $target_dir
}
} finally {
diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
index 45572d75c..15babfc22 100644
--- a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
+++ b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap
@@ -45,7 +45,7 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {
try {
# cd file holds a raw path (no shell escaping needed)
if ((Test-Path $cdFile) -and (Get-Item $cdFile).Length -gt 0) {
- $target = (Get-Content -Path $cdFile -Raw).Trim()
+ $target = Get-Content -Path $cdFile -Raw
if ($target) {
Set-Location -LiteralPath $target
if ($exitCode -eq 0) {
diff --git a/templates/fish.fish b/templates/fish.fish
index 0148ee5ed..e384ed874 100644
--- a/templates/fish.fish
+++ b/templates/fish.fish
@@ -33,7 +33,7 @@ function {{ cmd }}
# cd file holds a raw path — read with fish builtin (no cat subprocess,
# safe even if CWD was removed by worktree removal).
if test -s "$cd_file"
- set -l target (string trim < "$cd_file")
+ set -l target (string collect < "$cd_file")
# `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish
# plugin replaces `cd` with a query function that mishandles the `--`
# separator). Matches the bash/zsh wrappers. (#3159)
diff --git a/templates/nushell.nu b/templates/nushell.nu
index e4dd0b34e..8969c6558 100644
--- a/templates/nushell.nu
+++ b/templates/nushell.nu
@@ -135,8 +135,8 @@ export def --env --wrapped {{ cmd }} [...args] {
} finally {
try {
# cd file holds a raw path — no shell parsing needed
- if ($cd_file | path exists) and (open $cd_file --raw | str trim | is-not-empty) {
- let target_dir = open $cd_file --raw | str trim
+ if ($cd_file | path exists) and (open $cd_file --raw | is-not-empty) {
+ let target_dir = open $cd_file --raw
cd $target_dir
}
} finally {
diff --git a/templates/powershell.ps1 b/templates/powershell.ps1
index 7d322fd89..459a1257f 100644
--- a/templates/powershell.ps1
+++ b/templates/powershell.ps1
@@ -41,7 +41,7 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN
try {
# cd file holds a raw path (no shell escaping needed)
if ((Test-Path $cdFile) -and (Get-Item $cdFile).Length -gt 0) {
- $target = (Get-Content -Path $cdFile -Raw).Trim()
+ $target = Get-Content -Path $cdFile -Raw
if ($target) {
Set-Location -LiteralPath $target
if ($exitCode -eq 0) {
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 25b993ee0..3b4545ddc 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -5073,7 +5073,7 @@ fn test_directive_to_directory_ending_in_space_is_kept(repo: TestRepo) {
let target = target.to_string_lossy().to_string();
repo.write_project_config(&format!(
r#"[pre-start]
-cd = '''printf '%s\n' '{target}' > "$WORKTRUNK_DIRECTIVE_CD_FILE"'''
+cd = "printf %s '{target}' > \"$WORKTRUNK_DIRECTIVE_CD_FILE\""
"#,
));
let cd_file = repo.home_path().join("cd-directive");
@@ -5084,7 +5084,7 @@ cd = '''printf '%s\n' '{target}' > "$WORKTRUNK_DIRECTIVE_CD_FILE"'''
.output()
.unwrap();
assert!(output.status.success(), "{output:?}");
- assert_eq!(fs::read_to_string(cd_file).unwrap(), format!("{target}\n"));
+ assert_eq!(fs::read_to_string(cd_file).unwrap(), target);
}
// ============================================================================
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 6c7bad1a8..0f0a9e2e6 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -94,7 +94,7 @@ function wt
# cd file holds a raw path — read with fish builtin (no cat subprocess,
# safe even if CWD was removed by worktree removal).
if test -s "$cd_file"
- set -l target (string trim < "$cd_file")
+ set -l target (string collect < "$cd_file")
# `builtin cd` bypasses any user `cd` override (e.g. the zoxide.fish
# plugin replaces `cd` with a query function that mishandles the `--`
# separator). Matches the bash/zsh wrappers. (#3159)