worktrunk 0.48.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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
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.
    // is_bare() 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 repo_path_ignores_non_local_core_worktree() {
    use super::RepoCache;
    use indexmap::IndexMap;
    use std::sync::{Arc, RwLock};

    // Regression test: `git config --list -z` merges system + global + local
    // scope, but git only honors `core.worktree` from local config. A user
    // with a stray global `core.worktree` in a normal repo should still see
    // `parent(.git)` as the repo root — `rev-parse --show-toplevel` fails
    // from inside `.git` in that case and we fall through.
    let tmp = tempfile::tempdir().unwrap();
    let git_dir = tmp.path().join(".git");
    std::fs::create_dir(&git_dir).unwrap();

    let cache = RepoCache::default();
    let mut map: IndexMap<String, Vec<String>> = IndexMap::new();
    map.insert("core.bare".to_string(), vec!["false".to_string()]);
    // Simulate a `core.worktree` picked up from global config. The path
    // doesn't have to exist — it only has to be present in the bulk map.
    map.insert(
        "core.worktree".to_string(),
        vec!["/nonexistent/global/worktree".to_string()],
    );
    cache.all_config.set(RwLock::new(map)).unwrap();

    let repo = super::Repository {
        discovery_path: tmp.path().to_path_buf(),
        git_common_dir: git_dir.clone(),
        cache: Arc::new(cache),
    };

    // Should fall through to parent(git_common_dir), ignoring the bulk value.
    assert_eq!(repo.repo_path().unwrap(), tmp.path());
}

#[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 extract_failed_command_from_command_error() {
    // A buffered `git` failure (Repository::run_command,
    // WorkingTree::run_command) surfaces as a typed CommandError, possibly
    // wrapped by `.context(...)`. extract_failed_command must walk the
    // chain so callers like switch::worktree_creation_error keep working.
    use crate::git::CommandError;
    use anyhow::Context;

    let inner = CommandError {
        program: "git".into(),
        args: vec!["worktree".into(), "add".into(), "/path".into()],
        stderr: "fatal: invalid reference: foo".into(),
        stdout: String::new(),
        exit_code: Some(128),
    };
    let err: anyhow::Error = Err::<(), _>(inner)
        .context("creating worktree")
        .unwrap_err();

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

#[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());
}

#[test]
fn commit_details_many_returns_subject_with_spaces() {
    use crate::testing::TestRepo;

    let test = TestRepo::new();
    // Commit with a multi-word subject — regression against parsers that split
    // on the first space and treat "word1" as the timestamp.
    test.commit_with_message("first commit with spaces");
    let sha1 = test.repo.run_command(&["rev-parse", "HEAD"]).unwrap();
    let sha1 = sha1.trim().to_string();

    test.commit_with_message("second commit");
    let sha2 = test.repo.run_command(&["rev-parse", "HEAD"]).unwrap();
    let sha2 = sha2.trim().to_string();

    let result = test
        .repo
        .commit_details_many(&[sha1.as_str(), sha2.as_str()])
        .unwrap();

    assert_eq!(result.len(), 2);
    let (short1, ts1, subject1) = &result[&sha1];
    let (short2, ts2, subject2) = &result[&sha2];
    assert_eq!(subject1, "first commit with spaces");
    assert_eq!(subject2, "second commit");
    assert!(*ts1 > 0);
    assert!(*ts2 > 0);
    // Short SHAs are a prefix of the full SHA; default `core.abbrev` is 7,
    // and a fresh test repo never needs more than that.
    assert!(sha1.starts_with(short1.as_str()));
    assert!(sha2.starts_with(short2.as_str()));
}

#[test]
fn commit_details_many_empty_input_is_noop() {
    use crate::testing::TestRepo;

    let test = TestRepo::with_initial_commit();
    let result = test.repo.commit_details_many(&[]).unwrap();
    assert!(result.is_empty());
}

#[test]
fn commit_details_many_fails_loudly_on_unknown_sha() {
    // `git log --no-walk` refuses the whole batch on a single bad ref. The
    // error surfaces as an `Err`, which `collect()` turns into a user-facing
    // warning. Pin this behavior so we don't silently fall back to
    // empty-map defaults.
    use crate::testing::TestRepo;

    let test = TestRepo::with_initial_commit();
    let bogus = "0000000000000000000000000000000000000001";
    let err = test.repo.commit_details_many(&[bogus]).unwrap_err();
    let msg = format!("{err:#}");
    assert!(
        msg.contains("git") || msg.contains("unknown") || msg.contains("bad"),
        "error message should surface git's complaint about the bogus SHA, got: {msg}"
    );
}

#[test]
fn commit_details_many_preserves_multibyte_utf8_subject() {
    // Pin that multibyte UTF-8 round-trips through the NUL-delimited parser —
    // `splitn(3, '\0')` works on byte positions, so char boundaries inside the
    // subject must be preserved intact.
    use crate::testing::TestRepo;

    let test = TestRepo::new();
    let subject = "Add support for 日本語 and émoji 🎉";
    test.commit_with_message(subject);
    let sha = test
        .repo
        .run_command(&["rev-parse", "HEAD"])
        .unwrap()
        .trim()
        .to_string();

    let result = test.repo.commit_details_many(&[sha.as_str()]).unwrap();

    assert_eq!(result[&sha].2, subject);
}

#[test]
fn commit_details_many_deduplicates_repeated_sha() {
    // `git log --no-walk SHA SHA` emits each commit once; pin that the batch
    // returns a single entry for a duplicated input SHA.
    use crate::testing::TestRepo;

    let test = TestRepo::new();
    test.commit_with_message("only commit");
    let sha = test
        .repo
        .run_command(&["rev-parse", "HEAD"])
        .unwrap()
        .trim()
        .to_string();

    let result = test
        .repo
        .commit_details_many(&[sha.as_str(), sha.as_str(), sha.as_str()])
        .unwrap();

    assert_eq!(result.len(), 1);
    assert_eq!(result[&sha].2, "only commit");
}

#[test]
#[cfg(unix)]
fn worktree_at_path_resolves_symlinked_path() {
    // Reproduction for issue #2460: `wt switch` fails to resolve existing
    // worktrees through symlink paths because `worktree_at_path` compares
    // paths lexically and misses symlink-equivalent spellings.
    use crate::testing::TestRepo;

    let mut test = TestRepo::with_initial_commit();
    let worktree_path = test.add_worktree("feature");

    let parent = worktree_path.parent().unwrap();
    let symlink_path = parent.join("feature-link");
    std::os::unix::fs::symlink(&worktree_path, &symlink_path).unwrap();

    let resolved = test.repo.worktree_at_path(&symlink_path).unwrap();
    assert!(
        resolved.is_some(),
        "worktree_at_path should resolve a symlinked path to its target worktree, got None for {symlink_path:?} -> {worktree_path:?}"
    );
    let (_, branch) = resolved.unwrap();
    assert_eq!(branch.as_deref(), Some("feature"));
}