worktrunk 0.39.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Git output parsing functions

use std::path::PathBuf;

use super::{GitError, WorktreeInfo, finalize_worktree};

impl WorktreeInfo {
    pub(crate) fn parse_porcelain_list(output: &str) -> anyhow::Result<Vec<Self>> {
        let mut worktrees = Vec::new();
        let mut current: Option<WorktreeInfo> = None;

        for line in output.lines() {
            if line.is_empty() {
                if let Some(wt) = current.take() {
                    worktrees.push(finalize_worktree(wt));
                }
                continue;
            }

            let (key, value) = match line.split_once(' ') {
                Some((k, v)) => (k, Some(v)),
                None => (line, None),
            };

            match key {
                "worktree" => {
                    let Some(path) = value else {
                        return Err(GitError::ParseError {
                            message: "worktree line missing path".into(),
                        }
                        .into());
                    };
                    current = Some(WorktreeInfo {
                        path: PathBuf::from(path),
                        head: String::new(),
                        branch: None,
                        bare: false,
                        detached: false,
                        locked: None,
                        prunable: None,
                    });
                }
                key => match (key, current.as_mut()) {
                    ("HEAD", Some(wt)) => {
                        let Some(sha) = value else {
                            return Err(GitError::ParseError {
                                message: "HEAD line missing SHA".into(),
                            }
                            .into());
                        };
                        wt.head = sha.to_string();
                    }
                    ("branch", Some(wt)) => {
                        // Strip refs/heads/ prefix if present
                        let Some(branch_ref) = value else {
                            return Err(GitError::ParseError {
                                message: "branch line missing ref".into(),
                            }
                            .into());
                        };
                        let branch = branch_ref
                            .strip_prefix("refs/heads/")
                            .unwrap_or(branch_ref)
                            .to_string();
                        wt.branch = Some(branch);
                    }
                    ("bare", Some(wt)) => {
                        wt.bare = true;
                    }
                    ("detached", Some(wt)) => {
                        wt.detached = true;
                    }
                    ("locked", Some(wt)) => {
                        wt.locked = Some(value.unwrap_or_default().to_string());
                    }
                    ("prunable", Some(wt)) => {
                        wt.prunable = Some(value.unwrap_or_default().to_string());
                    }
                    _ => {
                        // Ignore unknown attributes or attributes before first worktree
                    }
                },
            }
        }

        // Push the last worktree if the output doesn't end with a blank line
        if let Some(wt) = current {
            worktrees.push(finalize_worktree(wt));
        }

        Ok(worktrees)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DefaultBranchName(String);

impl DefaultBranchName {
    pub(crate) fn from_local(remote: &str, output: &str) -> anyhow::Result<Self> {
        let trimmed = output.trim();

        // Strip "remote/" prefix if present
        let prefix = format!("{}/", remote);
        let branch = trimmed.strip_prefix(&prefix).unwrap_or(trimmed);

        if branch.is_empty() {
            return Err(GitError::ParseError {
                message: format!("Empty branch name from {}/HEAD", remote),
            }
            .into());
        }

        Ok(Self(branch.to_string()))
    }

    pub(crate) fn from_remote(output: &str) -> anyhow::Result<Self> {
        output
            .lines()
            .find_map(|line| {
                line.strip_prefix("ref: ")
                    .and_then(|symref| symref.split_once('\t'))
                    .map(|(ref_path, _)| ref_path)
                    .and_then(|ref_path| ref_path.strip_prefix("refs/heads/"))
                    .map(|branch| branch.to_string())
            })
            .map(Self)
            .ok_or_else(|| {
                GitError::ParseError {
                    message: "Could not find symbolic ref in ls-remote output".into(),
                }
                .into()
            })
    }

    pub(crate) fn into_string(self) -> String {
        self.0
    }
}

/// Parse `git status --porcelain -z` output into a list of affected filenames.
///
/// The -z format uses NUL separators and handles renames specially:
/// - Normal entries: `XY path\0`
/// - Renames/copies: `XY new_path\0old_path\0`
///
/// This correctly handles filenames with spaces and ensures both old and new
/// paths are included for renames/copies (important for overlap detection).
pub fn parse_porcelain_z(output: &str) -> Vec<String> {
    let mut files = Vec::new();
    let mut entries = output.split('\0').filter(|s| !s.is_empty());

    while let Some(entry) = entries.next() {
        // Each entry is "XY path" where XY is exactly 2 status chars
        if entry.len() < 3 {
            continue;
        }

        let status = &entry[0..2];
        let path = &entry[3..];
        files.push(path.to_string());

        // For renames (R) and copies (C), the next NUL-separated field is the old path
        if (status.starts_with('R') || status.starts_with('C'))
            && let Some(old_path) = entries.next()
        {
            files.push(old_path.to_string());
        }
    }

    files
}

/// Parse untracked files from `git status --porcelain -z` output.
///
/// Format: "XY path\0" where XY is the status code and path follows a space.
/// Untracked files have status "??".
pub fn parse_untracked_files(status_output: &str) -> Vec<String> {
    let mut files = Vec::new();
    let mut entries = status_output.split('\0').filter(|s| !s.is_empty());

    while let Some(entry) = entries.next() {
        // Format: "XY PATH" where XY is 2 status chars, space, then path
        if entry.len() < 3 {
            continue;
        }

        let status = &entry[0..2];
        let path = &entry[3..];

        // Only collect untracked files
        if status == "??" {
            files.push(path.to_string());
        }

        // Skip old path for renames/copies (we don't care about them here)
        if status.starts_with('R') || status.starts_with('C') {
            entries.next();
        }
    }

    files
}

#[cfg(test)]
mod tests {
    use super::*;

    // ============================================================================
    // DefaultBranchName::from_local Tests
    // ============================================================================

    #[test]
    fn test_from_local_simple() {
        let result = DefaultBranchName::from_local("origin", "main");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "main");
    }

    #[test]
    fn test_from_local_with_remote_prefix() {
        let result = DefaultBranchName::from_local("origin", "origin/main");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "main");
    }

    #[test]
    fn test_from_local_with_whitespace() {
        let result = DefaultBranchName::from_local("origin", "  main  \n");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "main");
    }

    #[test]
    fn test_from_local_empty() {
        let result = DefaultBranchName::from_local("origin", "");
        assert!(result.is_err());
    }

    #[test]
    fn test_from_local_only_whitespace() {
        let result = DefaultBranchName::from_local("origin", "   \n  ");
        assert!(result.is_err());
    }

    #[test]
    fn test_from_local_different_remote() {
        let result = DefaultBranchName::from_local("upstream", "upstream/develop");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "develop");
    }

    // ============================================================================
    // DefaultBranchName::from_remote Tests
    // ============================================================================

    #[test]
    fn test_from_remote_standard() {
        let output = "ref: refs/heads/main\tHEAD\n";
        let result = DefaultBranchName::from_remote(output);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "main");
    }

    #[test]
    fn test_from_remote_master() {
        let output = "ref: refs/heads/master\tHEAD\n";
        let result = DefaultBranchName::from_remote(output);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "master");
    }

    #[test]
    fn test_from_remote_with_other_lines() {
        let output = "abc123\tHEAD\nref: refs/heads/develop\tHEAD\ndef456\trefs/heads/main\n";
        let result = DefaultBranchName::from_remote(output);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().into_string(), "develop");
    }

    #[test]
    fn test_from_remote_no_ref() {
        let output = "abc123\tHEAD\n";
        let result = DefaultBranchName::from_remote(output);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_remote_empty() {
        let result = DefaultBranchName::from_remote("");
        assert!(result.is_err());
    }

    // ============================================================================
    // WorktreeInfo::parse_porcelain_list Tests
    // ============================================================================

    #[test]
    fn test_parse_porcelain_list_single_worktree() {
        let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
        assert_eq!(wt.path.to_str().unwrap(), "/path/to/repo");
        assert_eq!(wt.head, "abc123");
        assert_eq!(wt.branch, Some("main".to_string()));
    }

    #[test]
    fn test_parse_porcelain_list_multiple_worktrees() {
        let output = "worktree /path/main\nHEAD aaa\nbranch refs/heads/main\n\nworktree /path/feature\nHEAD bbb\nbranch refs/heads/feature\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();
        assert_eq!(main_wt.branch, Some("main".to_string()));
        assert_eq!(feature_wt.branch, Some("feature".to_string()));
    }

    #[test]
    fn test_parse_porcelain_list_bare_repo() {
        let output = "worktree /path/to/repo.git\nHEAD abc123\nbare\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
        assert!(wt.bare);
    }

    #[test]
    fn test_parse_porcelain_list_detached() {
        let output = "worktree /path/to/repo\nHEAD abc123\ndetached\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
        assert!(wt.detached);
        assert!(wt.branch.is_none());
    }

    #[test]
    fn test_parse_porcelain_list_locked() {
        let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nlocked reason for lock\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
        assert_eq!(wt.locked, Some("reason for lock".to_string()));
    }

    #[test]
    fn test_parse_porcelain_list_prunable() {
        let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main\nprunable gitdir file missing\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
        assert_eq!(wt.prunable, Some("gitdir file missing".to_string()));
    }

    #[test]
    fn test_parse_porcelain_list_empty() {
        let result = WorktreeInfo::parse_porcelain_list("");
        assert!(result.is_ok());
        let worktrees = result.unwrap();
        assert!(worktrees.is_empty());
    }

    #[test]
    fn test_parse_porcelain_list_no_trailing_blank() {
        // Git output may not always end with a blank line
        let output = "worktree /path/to/repo\nHEAD abc123\nbranch refs/heads/main";
        let result = WorktreeInfo::parse_porcelain_list(output);
        assert!(result.is_ok());
        let worktrees = result.unwrap();
        assert_eq!(worktrees.len(), 1);
    }

    #[test]
    fn test_parse_porcelain_list_missing_worktree_path() {
        let output = "worktree\nHEAD abc123\n\n";
        let result = WorktreeInfo::parse_porcelain_list(output);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_porcelain_list_missing_head_sha() {
        let output = "worktree /path\nHEAD\n\n";
        let result = WorktreeInfo::parse_porcelain_list(output);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_porcelain_list_branch_without_refs_prefix() {
        // This can happen in some edge cases
        let output = "worktree /path/to/repo\nHEAD abc123\nbranch main\n\n";
        let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
        let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
        // Should use the branch name as-is when no refs/heads/ prefix
        assert_eq!(wt.branch, Some("main".to_string()));
    }

    // ============================================================================
    // parse_porcelain_z Tests
    // ============================================================================

    #[test]
    fn test_parse_porcelain_z_empty() {
        assert!(parse_porcelain_z("").is_empty());
    }

    #[test]
    fn test_parse_porcelain_z_modified_file() {
        // "M  src/main.rs\0"
        let output = " M src/main.rs\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["src/main.rs"]);
    }

    #[test]
    fn test_parse_porcelain_z_multiple_files() {
        let output = " M src/main.rs\0?? new_file.txt\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["src/main.rs", "new_file.txt"]);
    }

    #[test]
    fn test_parse_porcelain_z_rename() {
        // Renames: "R  new_name\0old_name\0"
        let output = "R  new_name.rs\0old_name.rs\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["new_name.rs", "old_name.rs"]);
    }

    #[test]
    fn test_parse_porcelain_z_copy() {
        let output = "C  copy.rs\0original.rs\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["copy.rs", "original.rs"]);
    }

    #[test]
    fn test_parse_porcelain_z_rename_among_others() {
        let output = " M keep.rs\0R  new.rs\0old.rs\0?? untracked.txt\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["keep.rs", "new.rs", "old.rs", "untracked.txt"]);
    }

    #[test]
    fn test_parse_porcelain_z_spaces_in_path() {
        let output = " M path with spaces/file name.rs\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["path with spaces/file name.rs"]);
    }

    #[test]
    fn test_parse_porcelain_z_skips_short_entries() {
        // Entries shorter than 3 chars (status + space + path) are skipped
        let output = " M valid.rs\0ab\0";
        let files = parse_porcelain_z(output);
        assert_eq!(files, vec!["valid.rs"]);
    }

    // ============================================================================
    // parse_untracked_files Tests
    // ============================================================================

    #[test]
    fn test_parse_untracked_files_empty() {
        assert!(parse_untracked_files("").is_empty());
    }

    #[test]
    fn test_parse_untracked_files_only_untracked() {
        let output = "?? new_file.txt\0?? another.rs\0";
        let files = parse_untracked_files(output);
        assert_eq!(files, vec!["new_file.txt", "another.rs"]);
    }

    #[test]
    fn test_parse_untracked_files_filters_tracked() {
        let output = " M modified.rs\0?? untracked.txt\0A  added.rs\0";
        let files = parse_untracked_files(output);
        assert_eq!(files, vec!["untracked.txt"]);
    }

    #[test]
    fn test_parse_untracked_files_skips_rename_old_path() {
        // Rename entry has an extra NUL-separated old path that must be skipped
        let output = "R  new.rs\0old.rs\0?? untracked.txt\0";
        let files = parse_untracked_files(output);
        assert_eq!(files, vec!["untracked.txt"]);
    }

    #[test]
    fn test_parse_untracked_files_no_untracked() {
        let output = " M modified.rs\0A  added.rs\0";
        let files = parse_untracked_files(output);
        assert!(files.is_empty());
    }

    #[test]
    fn test_parse_untracked_files_spaces_in_path() {
        let output = "?? path with spaces/new file.txt\0";
        let files = parse_untracked_files(output);
        assert_eq!(files, vec!["path with spaces/new file.txt"]);
    }
}