worktrunk 0.37.0

A CLI for Git worktree management, designed for parallel AI agent workflows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use path_slash::PathExt as _;
use shell_escape::unix::escape;
use std::borrow::Cow;
use std::path::Path;

use sanitize_filename::{Options as SanitizeOptions, sanitize_with_options};

use crate::config::short_hash;
#[cfg(windows)]
use crate::shell_exec::{Cmd, ShellConfig};
#[cfg(windows)]
use std::path::PathBuf;

/// Convert a path to POSIX format for Git Bash compatibility.
///
/// On Windows, uses `cygpath -u` from Git for Windows to convert paths like
/// `C:\Users\test` to `/c/Users/test`. This handles all edge cases including
/// UNC paths (`\\server\share`) and verbatim paths (`\\?\C:\...`).
///
/// If cygpath is not available, returns the path unchanged.
///
/// On Unix, returns the path unchanged.
///
/// # Examples
/// - `C:\Users\test\repo` → `/c/Users/test/repo`
/// - `D:\a\worktrunk` → `/d/a/worktrunk`
/// - `\\?\C:\repo` → `/c/repo` (verbatim prefix stripped)
/// - `/tmp/test/repo` → `/tmp/test/repo` (unchanged on Unix)
#[cfg(windows)]
pub fn to_posix_path(path: &str) -> String {
    let Ok(shell) = ShellConfig::get() else {
        return path.to_string();
    };
    let Some(cygpath) = find_cygpath_from_shell(shell) else {
        return path.to_string();
    };

    let Ok(output) = Cmd::new(cygpath.to_string_lossy()).args(["-u", path]).run() else {
        return path.to_string();
    };

    if output.status.success() {
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    } else {
        path.to_string()
    }
}

#[cfg(not(windows))]
pub fn to_posix_path(path: &str) -> String {
    path.to_string()
}

/// Find cygpath.exe relative to the shell executable.
///
/// cygpath is always at `usr/bin/cygpath.exe` in a Git for Windows installation.
/// bash.exe can be at `bin/bash.exe` or `usr/bin/bash.exe`, so we check both
/// relative paths.
#[cfg(windows)]
fn find_cygpath_from_shell(shell: &crate::shell_exec::ShellConfig) -> Option<PathBuf> {
    // Only Git Bash has cygpath
    if !shell.is_posix {
        return None;
    }

    let shell_dir = shell.executable.parent()?;

    // If bash is at usr/bin/bash.exe, cygpath is in the same directory
    let cygpath = shell_dir.join("cygpath.exe");
    if cygpath.exists() {
        return Some(cygpath);
    }

    // If bash is at bin/bash.exe, cygpath is at ../usr/bin/cygpath.exe
    let cygpath = shell_dir
        .parent()?
        .join("usr")
        .join("bin")
        .join("cygpath.exe");
    if cygpath.exists() {
        return Some(cygpath);
    }

    None
}

/// Get the user's home directory.
///
/// Uses the `home` crate which handles platform-specific detection:
/// - Unix: `$HOME` environment variable
/// - Windows: `USERPROFILE` or `HOMEDRIVE`/`HOMEPATH`
pub use home::home_dir;

/// Check if a string needs shell escaping (contains characters outside the safe set).
fn needs_shell_escaping(s: &str) -> bool {
    !matches!(escape(Cow::Borrowed(s)), Cow::Borrowed(_))
}

/// Format a filesystem path for user-facing output.
///
/// Replaces home directory prefix with `~` when safe for shell use. Falls back to
/// quoted absolute path when escaping is needed (to avoid tilde-in-quotes issues).
///
/// Uses POSIX shell escaping since all our hints target POSIX-compatible shells
/// (bash, zsh, fish, and Git Bash on Windows).
///
/// # Examples
/// - `/Users/alex/repo` → `~/repo` (no escaping needed)
/// - `/Users/alex/my repo` → `'/Users/alex/my repo'` (needs quoting, use original)
/// - `/tmp/repo` → `/tmp/repo` (no escaping needed)
/// - `/tmp/my repo` → `'/tmp/my repo'` (needs quoting)
pub fn format_path_for_display(path: &Path) -> String {
    // Try to use tilde for home directory paths
    if let Some(home) = home_dir()
        && let Ok(stripped) = path.strip_prefix(&home)
    {
        if stripped.as_os_str().is_empty() {
            return "~".to_string();
        }

        // Build tilde path with forward slash (POSIX style, works everywhere)
        let rest = stripped.to_slash_lossy();

        // Only use tilde form if the rest doesn't need escaping
        // (tilde doesn't expand inside quotes)
        if !needs_shell_escaping(&rest) {
            return format!("~/{rest}");
        }
    }

    // Non-home path or escaping needed - use POSIX quoting
    // Use to_slash_lossy for Windows compatibility (forward slashes in shell hints)
    let original = path.to_slash_lossy();
    match escape(Cow::Borrowed(&original)) {
        Cow::Borrowed(_) => original.into_owned(),
        Cow::Owned(escaped) => escaped,
    }
}

/// Sanitize a string for use as a filename on all platforms.
///
/// Uses `sanitize-filename` crate to handle invalid characters, control characters,
/// Windows reserved names (CON, PRN, etc.), and trailing dots/spaces.
///
/// If the input is already a safe filename, it is returned unchanged. Otherwise
/// a 3-character hash suffix (computed from the original input) is appended so
/// that inputs which would otherwise collide produce distinct outputs (e.g.,
/// `origin/feature` → `origin-feature-<hash>` does not collide with the
/// already-safe `origin-feature`).
pub fn sanitize_for_filename(value: &str) -> String {
    let sanitized = sanitize_with_options(
        value,
        SanitizeOptions {
            windows: true,
            truncate: false,
            replacement: "-",
        },
    );

    if sanitized == value && !value.is_empty() {
        return sanitized;
    }

    let mut result = if sanitized.is_empty() {
        "_empty".to_string()
    } else {
        sanitized
    };
    if !result.ends_with('-') {
        result.push('-');
    }
    result.push_str(&short_hash(value));
    result
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::{format_path_for_display, home_dir, sanitize_for_filename, to_posix_path};

    #[test]
    fn shortens_path_under_home() {
        let Some(home) = home_dir() else {
            // Skip if HOME/USERPROFILE is not set in the environment
            return;
        };

        let path = home.join("projects").join("wt");
        let formatted = format_path_for_display(&path);

        assert!(
            formatted.starts_with("~"),
            "Expected tilde prefix, got {formatted}"
        );
        assert!(
            formatted.contains("projects"),
            "Expected child components to remain in output"
        );
        assert!(
            formatted.ends_with("wt"),
            "Expected leaf component to remain in output"
        );
    }

    #[test]
    fn shows_home_as_tilde() {
        let Some(home) = home_dir() else {
            return;
        };

        let formatted = format_path_for_display(&home);
        assert_eq!(formatted, "~");
    }

    #[test]
    fn leaves_non_home_paths_unchanged() {
        let path = PathBuf::from("/tmp/worktrunk-non-home-path");
        let formatted = format_path_for_display(&path);
        assert_eq!(formatted, path.display().to_string());
    }

    // Tests for to_posix_path behavior (results depend on platform)
    #[test]
    fn to_posix_path_leaves_unix_paths_unchanged() {
        // Unix-style paths should pass through unchanged on all platforms
        assert_eq!(to_posix_path("/tmp/test/repo"), "/tmp/test/repo");
        assert_eq!(to_posix_path("relative/path"), "relative/path");
    }

    #[test]
    #[cfg(windows)]
    fn to_posix_path_converts_windows_drive_letter() {
        // On Windows, drive letters should be converted to /x/ format
        let result = to_posix_path(r"C:\Users\test");
        assert!(
            result.starts_with("/c/"),
            "Expected /c/ prefix, got: {result}"
        );
        assert!(
            result.contains("Users"),
            "Expected Users in path, got: {result}"
        );
    }

    #[test]
    #[cfg(windows)]
    fn to_posix_path_handles_verbatim_paths() {
        // cygpath should handle verbatim paths (\\?\C:\...)
        let result = to_posix_path(r"\\?\C:\Users\test");
        // Should either strip \\?\ prefix or handle it correctly
        assert!(
            result.contains("/c/") || result.contains("Users"),
            "Expected converted path, got: {result}"
        );
    }

    #[test]
    fn test_home_dir_returns_valid_path() {
        // home_dir should return a valid path on most systems
        if let Some(home) = home_dir() {
            assert!(home.is_absolute(), "Home directory should be absolute");
            // The home directory itself might not exist in some CI environments,
            // but the path should at least have components
            assert!(home.components().count() > 0, "Home should have components");
        }
    }

    #[test]
    fn test_format_path_outside_home() {
        // A path that definitely won't be under home
        let path = PathBuf::from("/definitely/not/under/home/dir");
        let result = format_path_for_display(&path);
        // Should return unchanged
        assert_eq!(result, "/definitely/not/under/home/dir");
    }

    #[test]
    #[cfg(not(windows))]
    fn test_to_posix_path_on_unix() {
        // On Unix, to_posix_path is a no-op
        assert_eq!(to_posix_path("/some/path"), "/some/path");
        assert_eq!(to_posix_path("relative"), "relative");
        assert_eq!(to_posix_path(""), "");
    }

    #[test]
    fn test_sanitize_for_filename_replaces_invalid_chars() {
        assert!(sanitize_for_filename("foo/bar").starts_with("foo-bar-"));
        assert!(sanitize_for_filename("name:with?chars").starts_with("name-with-chars-"));
    }

    #[test]
    fn test_sanitize_for_filename_trims_trailing_dots_and_spaces() {
        assert!(sanitize_for_filename("file. ").starts_with("file-"));
        assert!(sanitize_for_filename("file...").starts_with("file-"));
    }

    #[test]
    fn test_sanitize_for_filename_handles_reserved_names() {
        // Reserved names are replaced (not preserved) - the hash ensures uniqueness
        let con = sanitize_for_filename("CON");
        let com1 = sanitize_for_filename("com1");
        assert!(
            !con.is_empty() && con.len() > 3,
            "CON should produce valid filename: {con}"
        );
        assert!(
            !com1.is_empty() && com1.len() > 3,
            "com1 should produce valid filename: {com1}"
        );
    }

    #[test]
    fn test_sanitize_for_filename_handles_empty() {
        assert!(sanitize_for_filename("").starts_with("_empty-"));
    }

    #[test]
    fn test_sanitize_for_filename_avoids_collisions() {
        // Already-safe names pass through unchanged; only sanitized inputs get
        // a hash suffix. This still avoids collisions because the suffix makes
        // the sanitized form distinct from any plausible already-safe name.
        let a = sanitize_for_filename("origin/feature");
        let b = sanitize_for_filename("origin-feature");

        assert_ne!(a, b, "collision: {a} == {b}");
        assert!(a.starts_with("origin-feature-"));
        assert_eq!(b, "origin-feature");
    }

    #[test]
    fn test_sanitize_for_filename_passes_through_safe_names() {
        assert_eq!(sanitize_for_filename("main"), "main");
        assert_eq!(sanitize_for_filename("feature-x"), "feature-x");
        assert_eq!(
            sanitize_for_filename("rust-doc-comments"),
            "rust-doc-comments"
        );
        assert_eq!(sanitize_for_filename("post-merge"), "post-merge");
    }

    #[test]
    #[cfg(unix)]
    fn format_path_for_display_escaping() {
        use insta::assert_snapshot;

        let Some(home) = home_dir() else {
            return;
        };

        // Build test cases: (input_path, expected_pattern)
        // For home paths, we normalize output by replacing actual result with description
        let mut lines = Vec::new();

        // Non-home paths - predictable across machines
        for path_str in [
            "/tmp/repo",
            "/tmp/my repo",
            "/tmp/file;rm -rf",
            "/tmp/test'quote",
        ] {
            let path = PathBuf::from(path_str);
            lines.push(format!(
                "{} => {}",
                path_str,
                format_path_for_display(&path)
            ));
        }

        // Home-relative paths - normalize by showing ~/... pattern
        let home_cases = [
            "workspace/repo",    // simple -> ~/workspace/repo
            "my workspace/repo", // spaces -> quoted absolute
            "project's/repo",    // quote -> quoted absolute
        ];

        for suffix in home_cases {
            let path = home.join(suffix);
            let result = format_path_for_display(&path);

            let display = if result.starts_with('\'') {
                // Quoted absolute path - normalize for snapshot
                "QUOTED_ABSOLUTE".to_string()
            } else {
                result
            };
            lines.push(format!("$HOME/{} => {}", suffix, display));
        }

        // Home directory itself
        lines.push(format!("$HOME => {}", format_path_for_display(&home)));

        assert_snapshot!(lines.join("\n"), @r"
        /tmp/repo => /tmp/repo
        /tmp/my repo => '/tmp/my repo'
        /tmp/file;rm -rf => '/tmp/file;rm -rf'
        /tmp/test'quote => '/tmp/test'\''quote'
        $HOME/workspace/repo => ~/workspace/repo
        $HOME/my workspace/repo => QUOTED_ABSOLUTE
        $HOME/project's/repo => QUOTED_ABSOLUTE
        $HOME => ~
        ");
    }
}