worktrunk 0.42.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
use std::path::PathBuf;

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

#[test]
fn test_parse_worktree_list() {
    let output = "worktree /path/to/main
HEAD abcd1234
branch refs/heads/main

worktree /path/to/feature
HEAD efgh5678
branch refs/heads/feature

";

    let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
    let [main_wt, feature_wt]: [WorktreeInfo; 2] = worktrees.try_into().unwrap();

    assert_eq!(main_wt.path, PathBuf::from("/path/to/main"));
    assert_eq!(main_wt.head, "abcd1234");
    assert_eq!(main_wt.branch, Some("main".to_string()));
    assert!(!main_wt.bare);
    assert!(!main_wt.detached);

    assert_eq!(feature_wt.path, PathBuf::from("/path/to/feature"));
    assert_eq!(feature_wt.head, "efgh5678");
    assert_eq!(feature_wt.branch, Some("feature".to_string()));
}

#[test]
fn test_parse_detached_worktree() {
    let output = "worktree /path/to/detached
HEAD abcd1234
detached

";

    let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
    let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
    assert!(wt.detached);
    assert_eq!(wt.branch, None);
}

#[test]
fn test_finalize_worktree_with_branch() {
    // Worktree with a branch should not be modified
    let wt = WorktreeInfo {
        path: PathBuf::from("/path/to/worktree"),
        head: "abcd1234".to_string(),
        branch: Some("feature".to_string()),
        bare: false,
        detached: false,
        locked: None,
        prunable: None,
    };

    let finalized = finalize_worktree(wt.clone());
    assert_eq!(finalized.branch, Some("feature".to_string()));
}

#[test]
fn test_finalize_worktree_detached_with_branch() {
    // Detached worktree with a branch (unusual but possible) should keep the branch
    let wt = WorktreeInfo {
        path: PathBuf::from("/path/to/worktree"),
        head: "abcd1234".to_string(),
        branch: Some("feature".to_string()),
        bare: false,
        detached: true,
        locked: None,
        prunable: None,
    };

    let finalized = finalize_worktree(wt.clone());
    assert_eq!(finalized.branch, Some("feature".to_string()));
}

#[test]
fn test_finalize_worktree_detached_no_branch() {
    // Detached worktree with no branch should attempt rebase detection
    // Note: This test validates the logic flow but doesn't test actual file reading
    // since that would require setting up git rebase state files.
    // Actual rebase detection has been manually verified.
    let wt = WorktreeInfo {
        path: PathBuf::from("/nonexistent/path"),
        head: "abcd1234".to_string(),
        branch: None,
        bare: false,
        detached: true,
        locked: None,
        prunable: None,
    };

    let finalized = finalize_worktree(wt);
    // With a nonexistent path, rebase detection should fail gracefully
    // and branch should remain None
    assert_eq!(finalized.branch, None);
}

#[test]
fn test_parse_locked_worktree() {
    let output = "worktree /path/to/locked
HEAD abcd1234
branch refs/heads/main
locked reason for lock

";

    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_bare_worktree() {
    let output = "worktree /path/to/bare
HEAD abcd1234
bare

";

    let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
    let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
    assert!(wt.bare);
}

#[test]
fn test_parse_local_default_branch_with_prefix() {
    let output = "origin/main\n";
    let branch = DefaultBranchName::from_local("origin", output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "main");
}

#[test]
fn test_parse_local_default_branch_without_prefix() {
    let output = "main\n";
    let branch = DefaultBranchName::from_local("origin", output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "main");
}

#[test]
fn test_parse_local_default_branch_master() {
    let output = "origin/master\n";
    let branch = DefaultBranchName::from_local("origin", output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "master");
}

#[test]
fn test_parse_local_default_branch_custom_name() {
    let output = "origin/develop\n";
    let branch = DefaultBranchName::from_local("origin", output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "develop");
}

#[test]
fn test_parse_local_default_branch_custom_remote() {
    let output = "upstream/main\n";
    let branch = DefaultBranchName::from_local("upstream", output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "main");
}

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

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

#[test]
fn test_parse_remote_default_branch_main() {
    let output = "ref: refs/heads/main\tHEAD
85a1ce7c7182540f9c02453441cb3e8bf0ced214\tHEAD
";
    let branch = DefaultBranchName::from_remote(output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "main");
}

#[test]
fn test_parse_remote_default_branch_master() {
    let output = "ref: refs/heads/master\tHEAD
abcd1234567890abcd1234567890abcd12345678\tHEAD
";
    let branch = DefaultBranchName::from_remote(output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "master");
}

#[test]
fn test_parse_remote_default_branch_custom() {
    let output = "ref: refs/heads/develop\tHEAD
1234567890abcdef1234567890abcdef12345678\tHEAD
";
    let branch = DefaultBranchName::from_remote(output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "develop");
}

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

#[test]
fn test_parse_remote_default_branch_missing_symref() {
    let output = "85a1ce7c7182540f9c02453441cb3e8bf0ced214\tHEAD\n";
    let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);
    assert!(result.is_err());
}

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

#[test]
fn test_parse_remote_default_branch_malformed_ref() {
    // Missing refs/heads/ prefix
    let output = "ref: main\tHEAD\n";
    let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);
    assert!(result.is_err());
}

#[test]
fn test_parse_remote_default_branch_with_spaces() {
    // Space instead of tab - should be rejected as malformed input
    let output = "ref: refs/heads/main HEAD\n";
    let result = DefaultBranchName::from_remote(output).map(DefaultBranchName::into_string);
    // Using split_once correctly rejects malformed input with spaces instead of tabs
    assert!(result.is_err());
}

#[test]
fn test_parse_remote_default_branch_branch_with_slash() {
    let output = "ref: refs/heads/feature/new-ui\tHEAD\n";
    let branch = DefaultBranchName::from_remote(output)
        .map(DefaultBranchName::into_string)
        .unwrap();
    assert_eq!(branch, "feature/new-ui");
}

use super::ResolvedWorktree;

#[test]
fn test_resolved_worktree_clone() {
    let wt = ResolvedWorktree::Worktree {
        path: PathBuf::from("/path/to/worktree"),
        branch: Some("feature".to_string()),
    };
    let cloned = wt.clone();
    if let ResolvedWorktree::Worktree { path, branch } = cloned {
        assert_eq!(path, PathBuf::from("/path/to/worktree"));
        assert_eq!(branch, Some("feature".to_string()));
    } else {
        panic!("Expected Worktree variant");
    }
}

#[test]
fn test_resolved_worktree_none_branch() {
    // Worktree with detached HEAD (no branch)
    let wt = ResolvedWorktree::Worktree {
        path: PathBuf::from("/path/to/worktree"),
        branch: None,
    };
    if let ResolvedWorktree::Worktree { path, branch } = wt {
        assert_eq!(path, PathBuf::from("/path/to/worktree"));
        assert!(branch.is_none());
    } else {
        panic!("Expected Worktree variant");
    }
}

#[test]
fn test_worktree_locked_empty_reason() {
    let output = "worktree /path/to/locked
HEAD abcd1234
branch refs/heads/main
locked

";

    let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
    let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
    // Empty lock reason should still be recorded
    assert_eq!(wt.locked, Some(String::new()));
}

#[test]
fn test_worktree_prunable() {
    let output = "worktree /path/to/prunable
HEAD abcd1234
detached
prunable gitdir file points to non-existent location

";

    let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
    let [wt]: [WorktreeInfo; 1] = worktrees.try_into().unwrap();
    assert!(wt.prunable.is_some());
    assert!(wt.prunable.as_ref().unwrap().contains("non-existent"));
}

#[test]
fn test_parse_multiple_worktrees() {
    let output = "worktree /main
HEAD 1111111111111111111111111111111111111111
branch refs/heads/main

worktree /feature-a
HEAD 2222222222222222222222222222222222222222
branch refs/heads/feature-a

worktree /feature-b
HEAD 3333333333333333333333333333333333333333
branch refs/heads/feature-b

worktree /detached
HEAD 4444444444444444444444444444444444444444
detached

";

    let worktrees = WorktreeInfo::parse_porcelain_list(output).unwrap();
    let [main_wt, feature_a, feature_b, detached_wt]: [WorktreeInfo; 4] =
        worktrees.try_into().unwrap();
    assert_eq!(main_wt.branch, Some("main".to_string()));
    assert_eq!(feature_a.branch, Some("feature-a".to_string()));
    assert_eq!(feature_b.branch, Some("feature-b".to_string()));
    assert!(detached_wt.detached);
    assert_eq!(detached_wt.branch, None);
}

#[test]
fn test_default_branch_name_display() {
    // Test that DefaultBranchName properly extracts branch names
    let cases = [
        ("origin/main\n", "main"),
        ("upstream/develop\n", "develop"),
        ("origin/master\n", "master"),
    ];

    for (input, expected) in cases {
        let remote = input.split('/').next().unwrap();
        let branch = DefaultBranchName::from_local(remote, input)
            .map(DefaultBranchName::into_string)
            .unwrap();
        assert_eq!(branch, expected);
    }
}

#[test]
fn repo_path_error_when_is_bare_fails() {
    use super::RepoCache;
    use std::sync::Arc;

    // Create a Repository with a non-existent git_common_dir.
    // This makes --show-toplevel fail (reaching the is_bare branch),
    // and then is_bare() also fails because the bulk config read
    // can't run in a missing dir.
    let repo = super::Repository {
        discovery_path: PathBuf::from("/nonexistent/repo"),
        git_common_dir: PathBuf::from("/nonexistent/.git"),
        cache: Arc::new(RepoCache::default()),
    };

    let err = repo.repo_path().unwrap_err();
    let msg = format!("{err:#}");
    // The OS error text is platform-specific (e.g., "No such file or directory" on Unix,
    // "The directory name is invalid." on Windows), so only assert the stable prefix.
    assert!(
        msg.starts_with("failed to read git config: "),
        "unexpected error message: {msg}"
    );
}

#[test]
fn parse_config_list_z_basic() {
    let input = b"core.bare\nfalse\0remote.origin.url\nhttps://example.com/a.git\0";
    let map = super::parse_config_list_z(input);
    assert_eq!(map["core.bare"], vec!["false"]);
    assert_eq!(map["remote.origin.url"], vec!["https://example.com/a.git"]);
}

#[test]
fn parse_config_list_z_multivar() {
    let input =
        b"remote.origin.fetch\n+refs/heads/*:refs/remotes/origin/*\0remote.origin.fetch\n+refs/tags/*:refs/tags/*\0";
    let map = super::parse_config_list_z(input);
    assert_eq!(
        map["remote.origin.fetch"],
        vec![
            "+refs/heads/*:refs/remotes/origin/*",
            "+refs/tags/*:refs/tags/*"
        ]
    );
}

#[test]
fn parse_config_list_z_newline_in_value() {
    // A value with embedded newlines is preserved verbatim because -z uses
    // NUL as the record separator. The split_once('\n') only splits on the
    // first newline (which separates key from value).
    let input = b"commit.template\nline1\nline2\0core.bare\nfalse\0";
    let map = super::parse_config_list_z(input);
    assert_eq!(map["commit.template"], vec!["line1\nline2"]);
    assert_eq!(map["core.bare"], vec!["false"]);
}

#[test]
fn parse_config_list_z_equals_in_value() {
    // Values containing `=` are preserved — no splitting on `=` because
    // the key/value separator under `-z` is `\n`.
    let input = b"user.email\nme=you@example.com\0";
    let map = super::parse_config_list_z(input);
    assert_eq!(map["user.email"], vec!["me=you@example.com"]);
}

#[test]
fn parse_config_list_z_empty() {
    let map = super::parse_config_list_z(b"");
    assert!(map.is_empty());
}

#[test]
fn parse_config_list_z_entry_without_newline_tolerates_key_only() {
    // `git config --list -z` always emits `key\nvalue\0`, but the parser
    // tolerates bare `key\0` by mapping it to `key -> ""` rather than
    // dropping the entry. Lets a future git oddity be diagnosed at the
    // use-site instead of silently missing.
    let input = b"core.bare\0other.key\nfalse\0";
    let map = super::parse_config_list_z(input);
    assert_eq!(map["core.bare"], vec![""]);
    assert_eq!(map["other.key"], vec!["false"]);
}

#[test]
fn canonical_config_key_cases() {
    // section + variable: both lowercased
    assert_eq!(
        super::canonical_config_key("init.defaultBranch"),
        "init.defaultbranch"
    );
    assert_eq!(
        super::canonical_config_key("checkout.defaultRemote"),
        "checkout.defaultremote"
    );
    assert_eq!(super::canonical_config_key("core.Bare"), "core.bare");
    // 3+ parts: section + variable lowercased, subsection preserved
    assert_eq!(
        super::canonical_config_key("remote.MyFork.url"),
        "remote.MyFork.url"
    );
    assert_eq!(
        super::canonical_config_key("branch.MyBranch.pushRemote"),
        "branch.MyBranch.pushremote"
    );
    // 4+ parts: subsection is the middle (spanning dots); only first and last lowercase
    assert_eq!(
        super::canonical_config_key("worktrunk.state.MyBranch.marker"),
        "worktrunk.state.MyBranch.marker"
    );
}

#[test]
fn parse_git_bool_variants() {
    for truthy in ["true", "TRUE", "True", "1", "yes", "YES", "on", "ON"] {
        assert!(super::parse_git_bool(truthy), "{truthy} should be true");
    }
    for falsy in ["false", "0", "no", "off", "", "anything-else"] {
        assert!(!super::parse_git_bool(falsy), "{falsy} should be false");
    }
}

#[test]
fn extract_failed_command_from_stream_error() {
    use super::StreamCommandError;

    let err: anyhow::Error = StreamCommandError {
        output: "fatal: ref exists".into(),
        command: "git worktree add /path".into(),
        exit_info: "exit code 128".into(),
    }
    .into();

    let (output, cmd) = super::Repository::extract_failed_command(&err);
    assert_eq!(output, "fatal: ref exists");
    let cmd = cmd.unwrap();
    assert_eq!(cmd.command, "git worktree add /path");
    assert_eq!(cmd.exit_info, "exit code 128");
}

#[test]
fn extract_failed_command_from_other_error() {
    let err = anyhow::anyhow!("some other error");

    let (output, cmd) = super::Repository::extract_failed_command(&err);
    assert_eq!(output, "some other error");
    assert!(cmd.is_none());
}

#[test]
fn is_builtin_fsmonitor_enabled_variants() {
    use super::RepoCache;
    use indexmap::IndexMap;
    use std::sync::{Arc, RwLock};

    fn repo_with_fsmonitor(value: Option<&str>) -> super::Repository {
        let cache = RepoCache::default();
        let mut map: IndexMap<String, Vec<String>> = IndexMap::new();
        if let Some(v) = value {
            map.insert("core.fsmonitor".to_string(), vec![v.to_string()]);
        }
        cache.all_config.set(RwLock::new(map)).unwrap();
        super::Repository {
            discovery_path: PathBuf::from("/nonexistent/repo"),
            git_common_dir: PathBuf::from("/nonexistent/.git"),
            cache: Arc::new(cache),
        }
    }

    // Builtin daemon: any git-bool truthy value enables it.
    for truthy in ["true", "1", "yes", "on", "TRUE"] {
        assert!(
            repo_with_fsmonitor(Some(truthy)).is_builtin_fsmonitor_enabled(),
            "{truthy} should enable builtin fsmonitor"
        );
    }

    // Watchman hook path is NOT the builtin daemon — must return false even
    // though the value is non-empty and truthy in the colloquial sense.
    assert!(
        !repo_with_fsmonitor(Some("/usr/local/bin/git-fsmonitor-watchman.sh"))
            .is_builtin_fsmonitor_enabled()
    );

    // Explicitly disabled and unset both report false.
    for falsy in ["false", "0", "no", "off"] {
        assert!(
            !repo_with_fsmonitor(Some(falsy)).is_builtin_fsmonitor_enabled(),
            "{falsy} should disable builtin fsmonitor"
        );
    }
    assert!(!repo_with_fsmonitor(None).is_builtin_fsmonitor_enabled());
}