git-loom 0.18.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
use git2::Oid;

use crate::core::graph::{self, RenderOpts, Theme};
use crate::core::repo::{
    BranchInfo, CommitInfo, ContextCommit, FileChange, RemoteStatus, RepoInfo, UpstreamInfo,
};

/// Strip ANSI escape codes so tests can compare plain text.
fn strip_ansi(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Skip until 'm' (end of ANSI escape sequence)
            for inner in chars.by_ref() {
                if inner == 'm' {
                    break;
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

fn default_opts() -> RenderOpts {
    RenderOpts {
        terminal_width: None,
        theme: Theme::dark(),
        cwd_prefix: String::new(),
    }
}

/// Render and strip ANSI codes for plain-text comparison.
fn render_plain(info: RepoInfo) -> String {
    let ids = crate::core::shortid::IdAllocator::new(info.collect_entities());
    strip_ansi(&graph::render(info, &ids, &default_opts()))
}

/// Render with a specific terminal width for multi-column tests.
fn render_plain_with_width(info: RepoInfo, width: u16) -> String {
    let opts = RenderOpts {
        terminal_width: Some(width),
        theme: Theme::dark(),
        cwd_prefix: String::new(),
    };
    let ids = crate::core::shortid::IdAllocator::new(info.collect_entities());
    strip_ansi(&graph::render(info, &ids, &opts))
}

/// Helper to create a fake OID from a single byte (padded to 20 bytes).
fn oid(byte: u8) -> Oid {
    let mut bytes = [0u8; 20];
    bytes[0] = byte;
    Oid::from_bytes(&bytes).unwrap()
}

fn commit(byte: u8, message: &str, parent: Option<u8>) -> CommitInfo {
    CommitInfo {
        oid: oid(byte),
        short_id: format!("{:07x}", byte),
        message: message.to_string(),
        parent_oid: parent.map(oid),
        files: vec![],
    }
}

fn commit_with_files(
    byte: u8,
    message: &str,
    parent: Option<u8>,
    files: Vec<FileChange>,
) -> CommitInfo {
    CommitInfo {
        oid: oid(byte),
        short_id: format!("{:07x}", byte),
        message: message.to_string(),
        parent_oid: parent.map(oid),
        files,
    }
}

fn base_info() -> RepoInfo {
    RepoInfo {
        branch_name: "main".to_string(),
        upstream: UpstreamInfo {
            label: "origin/main".to_string(),
            base_short_id: "aaa0000".to_string(),
            base_message: "Initial commit".to_string(),
            base_date: "2025-07-06".to_string(),
            commits_ahead: 0,
            merge_base_oid: oid(0xAA),
        },
        commits: vec![],
        branches: vec![],
        working_changes: vec![],
        context_commits: vec![],
    }
}

#[test]
fn no_commits_no_changes() {
    let output = render_plain(base_info());
    assert_eq!(
        output,
        "\
╭─ zz [local changes]
│   no changes
│
● aaa0000 (upstream) [origin/main] Initial commit
"
    );
}

#[test]
fn working_changes_shown() {
    let mut info = base_info();
    info.working_changes = vec![
        FileChange {
            path: "src/main.rs".to_string(),
            index: ' ',
            worktree: 'M',
        },
        FileChange {
            path: "new_file.txt".to_string(),
            index: 'A',
            worktree: ' ',
        },
    ];

    let output = render_plain(info);
    assert!(
        output
            .starts_with("╭─ zz [local changes]\n│   ma  M src/main.rs\n│   nf A  new_file.txt\n")
    );
}

#[test]
fn single_branch() {
    let mut info = base_info();
    // Commits: A2 -> A1 -> upstream
    info.commits = vec![commit(2, "A2", Some(1)), commit(1, "A1", None)];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: None,
    }];

    let output = render_plain(info);
    assert_eq!(
        output,
        "\
╭─ zz [local changes]
│   no changes
│
│╭─ fa [feature-a]
│●    0200002 A2
│●    0100001 A1
├╯
│
● aaa0000 (upstream) [origin/main] Initial commit
"
    );
}

#[test]
fn independent_branches() {
    let mut info = base_info();
    // feature-b: B1 -> upstream
    // feature-a: A1 -> upstream
    // Topological order: B1, A1 (both have upstream as parent, not each other)
    info.commits = vec![commit(2, "B1", None), commit(1, "A1", None)];
    info.branches = vec![
        BranchInfo {
            name: "feature-b".to_string(),
            tip_oid: oid(2),
            remote: None,
        },
        BranchInfo {
            name: "feature-a".to_string(),
            tip_oid: oid(1),
            remote: None,
        },
    ];

    let output = render_plain(info);
    // Both branches start with "feature-" so IDs will be extended
    // B1's parent is NOT A1, so they should be independent (├╯ then │╭─)
    assert!(
        output.contains("├╯\n\n│╭─"),
        "expected independent branches, got:\n{}",
        output
    );
}

#[test]
fn stacked_branches() {
    let mut info = base_info();
    // feature-b: B2 -> B1 -> A2 -> A1 -> upstream
    // feature-a tip = A2
    // feature-b tip = B2
    info.commits = vec![
        commit(4, "B2", Some(3)),
        commit(3, "B1", Some(2)), // B1's parent is A2 (the tip of feature-a)
        commit(2, "A2", Some(1)),
        commit(1, "A1", None),
    ];
    info.branches = vec![
        BranchInfo {
            name: "feature-b".to_string(),
            tip_oid: oid(4),
            remote: None,
        },
        BranchInfo {
            name: "feature-a".to_string(),
            tip_oid: oid(2),
            remote: None,
        },
    ];

    let output = render_plain(info);
    // B1's parent IS A2 (oid(2)), so they should be stacked (││ then │├─)
    assert!(
        output.contains("││\n│├─"),
        "expected stacked branches, got:\n{}",
        output
    );
    // Only one ├╯ at the very end of the stack
    assert_eq!(
        output.matches("├╯").count(),
        1,
        "expected single ├╯, got:\n{}",
        output
    );
}

#[test]
fn loose_commits_on_integration_line() {
    let mut info = base_info();
    // Two commits not belonging to any branch
    info.commits = vec![commit(2, "Fix typo", Some(1)), commit(1, "Refactor", None)];

    let output = render_plain(info);
    assert!(
        output.contains("●    0200002 Fix typo\n●    0100001 Refactor"),
        "expected loose commits, got:\n{}",
        output
    );
    // No branch markers (only the working changes header, no │╭─)
    assert!(
        !output.contains("│╭─"),
        "unexpected branch header in:\n{}",
        output
    );
}

#[test]
fn mixed_loose_and_branch() {
    let mut info = base_info();
    // Loose commit on top, then a branch
    // Topological order: loose_commit, branch_tip, branch_commit
    info.commits = vec![
        commit(3, "Loose on top", Some(2)),
        commit(2, "B tip", Some(1)),
        commit(1, "B base", None),
    ];
    info.branches = vec![BranchInfo {
        name: "feature-b".to_string(),
        tip_oid: oid(2),
        remote: None,
    }];

    let output = render_plain(info);
    // Loose commit should appear before the branch
    assert!(
        output.contains("●    0300003 Loose on top\n\n│╭─ fb [feature-b]"),
        "expected loose then branch, got:\n{}",
        output
    );
}

#[test]
fn upstream_ahead_shows_indicator() {
    let mut info = base_info();
    info.upstream.commits_ahead = 3;

    let output = render_plain(info);
    assert!(
        output.contains("│●  [origin/main] ⏫ 3 new commits\n├╯ aaa0000 (common base) 2025-07-06 Initial commit\n"),
        "expected upstream-ahead indicator, got:\n{}",
        output
    );
}

#[test]
fn upstream_ahead_singular() {
    let mut info = base_info();
    info.upstream.commits_ahead = 1;

    let output = render_plain(info);
    assert!(
        output.contains("⏫ 1 new commit\n"),
        "expected singular 'commit', got:\n{}",
        output
    );
    assert!(
        !output.contains("commits\n"),
        "should not contain plural 'commits', got:\n{}",
        output
    );
}

#[test]
fn merge_based_integration_branch() {
    // Simulates a merge-based integration branch where feature-1 is merged
    // via --no-ff. The revwalk produces commits from both sides of the merge,
    // but only the feature-1 ancestors should be assigned to the branch.
    //
    // History (merge commit already filtered by walk_commits):
    //   feature-1: F4 -> F3 -> F2 -> F1 -> upstream
    //   integration first-parent: I3 -> I2 -> I1 -> upstream
    //
    // Topo order after skipping the merge: F4, F3, F2, F1, I3, I2, I1
    let mut info = base_info();
    info.commits = vec![
        commit(0x14, "Feature 1 improvement", Some(0x13)),
        commit(0x13, "fixup Feature 1", Some(0x12)),
        commit(0x12, "Bugfix 1", Some(0x11)),
        commit(0x11, "Feature 1", Some(0xaa)), // parent is upstream base
        commit(0x23, "Feature 3 depends on Feature 2", Some(0x22)),
        commit(0x22, "fixup Feature 2", Some(0x21)),
        commit(0x21, "Feature 2", Some(0xaa)), // parent is upstream base
    ];
    info.branches = vec![BranchInfo {
        name: "feature-1".to_string(),
        tip_oid: oid(0x14),
        remote: None,
    }];

    let output = render_plain(info);

    // feature-1 should have exactly 4 commits
    let branch_section_start = output.find("│╭─").expect("no branch header found");
    let branch_section_end = output[branch_section_start..]
        .find("├╯")
        .expect("no branch close found")
        + branch_section_start;
    let branch_section = &output[branch_section_start..branch_section_end];
    let branch_dots = branch_section.matches("│●").count();
    assert_eq!(
        branch_dots, 4,
        "feature-1 should have exactly 4 commits, got {} in:\n{}",
        branch_dots, output
    );

    // Integration-line commits should be loose (plain ● without │ prefix)
    assert!(
        output.contains("●    2300023 Feature 3 depends on Feature 2"),
        "expected loose integration commit, got:\n{}",
        output
    );
}

#[test]
fn co_located_branches_show_all_names() {
    let mut info = base_info();
    // Two branches pointing to the same tip commit
    info.commits = vec![commit(2, "A2", Some(1)), commit(1, "A1", None)];
    info.branches = vec![
        BranchInfo {
            name: "feature-a".to_string(),
            tip_oid: oid(2),
            remote: None,
        },
        BranchInfo {
            name: "feature-a-v2".to_string(),
            tip_oid: oid(2),
            remote: None,
        },
    ];

    let output = render_plain(info);
    // Both branch names should appear as headers
    assert!(
        output.contains("[feature-a]"),
        "expected [feature-a] header, got:\n{}",
        output
    );
    assert!(
        output.contains("[feature-a-v2]"),
        "expected [feature-a-v2] header, got:\n{}",
        output
    );
    // Newest (alphabetically last) on top with ╭─, oldest uses ├─
    let v2_pos = output.find("[feature-a-v2]").unwrap();
    let a_pos = output.find("[feature-a]").unwrap();
    assert!(
        v2_pos < a_pos,
        "expected feature-a-v2 on top of feature-a, got:\n{}",
        output
    );
    assert!(
        output.contains("│╭─") && output.contains("│├─"),
        "expected ╭─ then ├─ for co-located branches, got:\n{}",
        output
    );
    // Only one set of commits (not duplicated)
    assert_eq!(
        output.matches("│●").count(),
        2,
        "expected 2 commit dots (not duplicated), got:\n{}",
        output
    );
}

#[test]
fn branch_at_upstream_shown_as_section() {
    let mut info = base_info();
    // A branch whose tip is the merge-base (upstream) commit
    info.branches = vec![BranchInfo {
        name: "feature-4".to_string(),
        tip_oid: oid(0xaa), // same as upstream base_oid
        remote: None,
    }];

    let output = render_plain(info);
    // Should appear as a branch section header, not on the upstream line
    assert!(
        output.contains("│╭─") && output.contains("[feature-4]"),
        "expected branch section for feature-4, got:\n{}",
        output
    );
    assert!(
        output.contains("├╯"),
        "expected branch close, got:\n{}",
        output
    );
}

#[test]
fn short_ids_for_files_use_filename() {
    let mut info = base_info();
    info.working_changes = vec![
        FileChange {
            path: "src/graph.rs".to_string(),
            index: ' ',
            worktree: 'M',
        },
        FileChange {
            path: "src/git.rs".to_string(),
            index: ' ',
            worktree: 'M',
        },
    ];

    let output = render_plain(info);
    // "graph.rs" -> "gr", "git.rs" -> "gi" (same first letter is fine, full IDs are unique)
    assert!(
        output.contains("gr  M src/graph.rs"),
        "expected file short ID 'gr', got:\n{}",
        output
    );
    assert!(
        output.contains("gi  M src/git.rs"),
        "expected file short ID 'gi', got:\n{}",
        output
    );
}

#[test]
fn short_ids_collision_extends() {
    let mut info = base_info();
    info.working_changes = vec![
        FileChange {
            path: "src/main.rs".to_string(),
            index: ' ',
            worktree: 'M',
        },
        FileChange {
            path: "src/manifest.rs".to_string(),
            index: 'A',
            worktree: ' ',
        },
    ];

    let output = render_plain(info);
    // Both filenames start with "ma", so IDs should extend to 3+ chars
    let lines: Vec<&str> = output.lines().collect();
    let main_line = lines.iter().find(|l| l.contains("main.rs")).unwrap();
    let manifest_line = lines.iter().find(|l| l.contains("manifest.rs")).unwrap();
    // They should have different IDs
    assert_ne!(main_line, manifest_line);
}

#[test]
fn files_shown_under_branch_commits() {
    let mut info = base_info();
    info.commits = vec![
        commit_with_files(
            2,
            "A2",
            Some(1),
            vec![
                FileChange {
                    path: "src/graph.rs".to_string(),
                    index: 'M',
                    worktree: ' ',
                },
                FileChange {
                    path: "new_file.txt".to_string(),
                    index: 'A',
                    worktree: ' ',
                },
            ],
        ),
        commit_with_files(
            1,
            "A1",
            None,
            vec![FileChange {
                path: "src/status.rs".to_string(),
                index: 'M',
                worktree: ' ',
            }],
        ),
    ];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: None,
    }];

    let output = render_plain(info);
    // File shortids use commit_sid:index format
    assert!(
        output.contains(
            "│●    0200002 A2\n│┊      02:0 M  src/graph.rs\n│┊      02:1 A  new_file.txt\n"
        ),
        "expected files under A2, got:\n{}",
        output
    );
    assert!(
        output.contains("│●    0100001 A1\n│┊      01:0 M  src/status.rs\n"),
        "expected files under A1, got:\n{}",
        output
    );
}

#[test]
fn files_shown_under_loose_commits() {
    let mut info = base_info();
    info.commits = vec![commit_with_files(
        2,
        "Fix typo",
        Some(1),
        vec![FileChange {
            path: "README.md".to_string(),
            index: 'M',
            worktree: ' ',
        }],
    )];

    let output = render_plain(info);
    // Loose commit file should have ┊ prefix with commit_sid:index format
    assert!(
        output.contains("●    0200002 Fix typo\n┊       02:0 M  README.md\n"),
        "expected files under loose commit, got:\n{}",
        output
    );
}

#[test]
fn commit_file_ids_use_commit_sid_colon_index() {
    let mut info = base_info();
    info.commits = vec![commit_with_files(
        2,
        "A1",
        None,
        vec![
            FileChange {
                path: "foo.rs".to_string(),
                index: 'A',
                worktree: ' ',
            },
            FileChange {
                path: "bar.rs".to_string(),
                index: 'M',
                worktree: ' ',
            },
        ],
    )];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: None,
    }];

    let output = render_plain(info);
    assert!(
        output.contains("02:0 A  foo.rs"),
        "expected 02:0 for first file, got:\n{}",
        output
    );
    assert!(
        output.contains("02:1 M  bar.rs"),
        "expected 02:1 for second file, got:\n{}",
        output
    );
}

#[test]
fn root_commit_files_shown() {
    // A commit with no parent (root commit) should still show files
    let mut info = base_info();
    info.commits = vec![commit_with_files(
        1,
        "Initial",
        None,
        vec![FileChange {
            path: "init.rs".to_string(),
            index: 'A',
            worktree: ' ',
        }],
    )];

    let output = render_plain(info);
    assert!(
        output.contains("●    0100001 Initial\n┊       01:0 A  init.rs\n"),
        "expected file under root commit, got:\n{}",
        output
    );
}

#[test]
fn same_file_in_multiple_commits_gets_unique_ids() {
    let mut info = base_info();
    // Same file "src/main.rs" modified in both commits
    info.commits = vec![
        commit_with_files(
            2,
            "A2",
            Some(1),
            vec![FileChange {
                path: "src/main.rs".to_string(),
                index: 'M',
                worktree: ' ',
            }],
        ),
        commit_with_files(
            1,
            "A1",
            None,
            vec![FileChange {
                path: "src/main.rs".to_string(),
                index: 'M',
                worktree: ' ',
            }],
        ),
    ];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: None,
    }];

    let output = render_plain(info);
    // Same file in different commits should get different IDs (02:0 vs 01:0)
    assert!(
        output.contains("02:0 M  src/main.rs"),
        "expected 02:0 for commit 2's file, got:\n{}",
        output
    );
    assert!(
        output.contains("01:0 M  src/main.rs"),
        "expected 01:0 for commit 1's file, got:\n{}",
        output
    );
}

#[test]
fn context_commits_shown_below_upstream() {
    let mut info = base_info();
    info.context_commits = vec![
        ContextCommit {
            short_hash: "bbb0001".to_string(),
            message: "Earlier commit".to_string(),
            date: "2025-07-05".to_string(),
        },
        ContextCommit {
            short_hash: "bbb0002".to_string(),
            message: "Even earlier".to_string(),
            date: "2025-07-04".to_string(),
        },
    ];

    let output = render_plain(info);
    // Context commits should appear after the upstream line
    assert!(
        output.contains("· bbb0001 2025-07-05 Earlier commit\n· bbb0002 2025-07-04 Even earlier\n"),
        "expected context commits below upstream, got:\n{}",
        output
    );
    // Upstream line should come before context
    let upstream_pos = output.find("(upstream)").unwrap();
    let context_pos = output.find("· bbb0001").unwrap();
    assert!(
        upstream_pos < context_pos,
        "upstream should appear before context commits, got:\n{}",
        output
    );
}

#[test]
fn context_commits_shown_below_diverged_upstream() {
    let mut info = base_info();
    info.upstream.commits_ahead = 2;
    info.context_commits = vec![ContextCommit {
        short_hash: "ccc0001".to_string(),
        message: "Before base".to_string(),
        date: "2025-07-01".to_string(),
    }];

    let output = render_plain(info);
    // Context should appear after the common base line
    let base_pos = output.find("(common base)").unwrap();
    let context_pos = output.find("· ccc0001").unwrap();
    assert!(
        base_pos < context_pos,
        "context should appear below common base, got:\n{}",
        output
    );
}

#[test]
fn no_context_when_default() {
    let info = base_info();
    let output = render_plain(info);
    assert!(
        !output.contains('·'),
        "no middle-dot lines expected with empty context_commits, got:\n{}",
        output
    );
}

#[test]
fn tracked_files_shown_before_untracked() {
    let mut info = base_info();
    // Mix tracked and untracked in the input order: untracked first, then tracked
    info.working_changes = vec![
        FileChange {
            path: ".claude/".to_string(),
            index: '?',
            worktree: '?',
        },
        FileChange {
            path: "src/main.rs".to_string(),
            index: ' ',
            worktree: 'M',
        },
        FileChange {
            path: "todo.md".to_string(),
            index: '?',
            worktree: '?',
        },
        FileChange {
            path: "new_file.txt".to_string(),
            index: 'A',
            worktree: ' ',
        },
    ];

    let output = render_plain(info);
    // Tracked files should appear before untracked files, regardless of input order
    let main_pos = output.find("src/main.rs").unwrap();
    let new_file_pos = output.find("new_file.txt").unwrap();
    let claude_pos = output.find(".claude/").unwrap();
    let todo_pos = output.find("todo.md").unwrap();
    assert!(
        main_pos < claude_pos && main_pos < todo_pos,
        "tracked files should appear before untracked, got:\n{}",
        output
    );
    assert!(
        new_file_pos < claude_pos && new_file_pos < todo_pos,
        "tracked files should appear before untracked, got:\n{}",
        output
    );
}

#[test]
fn only_untracked_skips_no_changes() {
    let mut info = base_info();
    info.working_changes = vec![
        FileChange {
            path: ".claude/".to_string(),
            index: '?',
            worktree: '?',
        },
        FileChange {
            path: "todo.md".to_string(),
            index: '?',
            worktree: '?',
        },
    ];

    let output = render_plain(info);
    assert!(
        !output.contains("no changes"),
        "should not show 'no changes' when untracked files exist, got:\n{}",
        output
    );
    assert!(
        output.contains(" ⁕ .claude/"),
        "expected untracked file, got:\n{}",
        output
    );
    assert!(
        output.contains(" ⁕ todo.md"),
        "expected untracked file, got:\n{}",
        output
    );
}

#[test]
fn untracked_below_threshold_stays_single_column() {
    let mut info = base_info();
    // 5 untracked files (at threshold, not above) — should stay single-column
    info.working_changes = (1..=5)
        .map(|i| FileChange {
            path: format!("file{}.txt", i),
            index: '?',
            worktree: '?',
        })
        .collect();

    let output = render_plain_with_width(info, 120);
    // Each file should be on its own line
    for i in 1..=5 {
        let pattern = format!(" ⁕ file{}.txt", i);
        assert!(
            output.contains(&pattern),
            "expected single-column entry for file{}.txt, got:\n{}",
            i,
            output
        );
    }
    // Count lines with "⁕" to verify single-column
    let untracked_lines: Vec<&str> = output.lines().filter(|l| l.contains('')).collect();
    assert_eq!(
        untracked_lines.len(),
        5,
        "expected 5 single-column lines, got {} in:\n{}",
        untracked_lines.len(),
        output
    );
}

#[test]
fn untracked_above_threshold_uses_multicolumn() {
    let mut info = base_info();
    // 6 untracked files (above threshold) with short paths — should go multi-column at 80 cols
    info.working_changes = (1..=6)
        .map(|i| FileChange {
            path: format!("f{}.txt", i),
            index: '?',
            worktree: '?',
        })
        .collect();

    let output = render_plain_with_width(info, 80);
    // All files should still appear
    for i in 1..=6 {
        let pattern = format!("f{}.txt", i);
        assert!(
            output.contains(&pattern),
            "expected f{}.txt in output, got:\n{}",
            i,
            output
        );
    }
    // With short paths, multiple entries should fit on one line — fewer lines than entries
    let untracked_lines: Vec<&str> = output.lines().filter(|l| l.contains('')).collect();
    assert!(
        untracked_lines.len() < 6,
        "expected multi-column (fewer than 6 lines), got {} lines:\n{:?}",
        untracked_lines.len(),
        untracked_lines
    );
}

#[test]
fn multicolumn_no_tty_stays_single_column() {
    let mut info = base_info();
    // 10 untracked files, but terminal_width is None (piped output)
    info.working_changes = (1..=10)
        .map(|i| FileChange {
            path: format!("file{}.txt", i),
            index: '?',
            worktree: '?',
        })
        .collect();

    // render_plain uses default_opts() which has terminal_width: None
    let output = render_plain(info);
    let untracked_lines: Vec<&str> = output.lines().filter(|l| l.contains('')).collect();
    assert_eq!(
        untracked_lines.len(),
        10,
        "expected single-column (10 lines) when no TTY, got {} lines:\n{:?}",
        untracked_lines.len(),
        untracked_lines
    );
}

#[test]
fn multicolumn_fills_top_to_bottom_left_to_right() {
    let mut info = base_info();
    // 6 files with short names.
    // Entry "xx  ⁕ aa.txt" = 2+1+2+1+6 = 12 chars; col_slot = 12+5 = 17 (entry + "   │ ").
    // At width 55: available = 55-4 = 51; 51/17 = 3 cols; rows = ceil(6/3) = 2.
    // Column-major layout:
    //   Row 0: aa.txt (idx 0), cc.txt (idx 2), ee.txt (idx 4)
    //   Row 1: bb.txt (idx 1), dd.txt (idx 3), ff.txt (idx 5)
    info.working_changes = vec!["aa", "bb", "cc", "dd", "ee", "ff"]
        .into_iter()
        .map(|name| FileChange {
            path: format!("{}.txt", name),
            index: '?',
            worktree: '?',
        })
        .collect();

    let output = render_plain_with_width(info, 55);
    let untracked_lines: Vec<&str> = output.lines().filter(|l| l.contains('')).collect();

    assert_eq!(
        untracked_lines.len(),
        2,
        "expected 2 rows with 3 columns, got {} lines:\n{:?}",
        untracked_lines.len(),
        untracked_lines
    );

    // Row 0 should contain aa, cc, ee (column-major: indices 0, 2, 4)
    assert!(
        untracked_lines[0].contains("aa.txt")
            && untracked_lines[0].contains("cc.txt")
            && untracked_lines[0].contains("ee.txt"),
        "row 0 should be aa, cc, ee (column-major), got: {}",
        untracked_lines[0]
    );
    // Row 1 should contain bb, dd, ff (column-major: indices 1, 3, 5)
    assert!(
        untracked_lines[1].contains("bb.txt")
            && untracked_lines[1].contains("dd.txt")
            && untracked_lines[1].contains("ff.txt"),
        "row 1 should be bb, dd, ff (column-major), got: {}",
        untracked_lines[1]
    );
}

#[test]
fn multicolumn_has_pipe_separators() {
    let mut info = base_info();
    info.working_changes = (1..=6)
        .map(|i| FileChange {
            path: format!("f{}.txt", i),
            index: '?',
            worktree: '?',
        })
        .collect();

    let output = render_plain_with_width(info, 80);
    let untracked_lines: Vec<&str> = output.lines().filter(|l| l.contains('')).collect();
    // Multi-column lines should contain pipe separators between entries
    assert!(
        untracked_lines[0].contains(""),
        "expected pipe separator between columns, got: {}",
        untracked_lines[0]
    );
}

#[test]
fn remote_synced_shows_checkmark() {
    let mut info = base_info();
    info.commits = vec![commit(2, "A2", Some(1)), commit(1, "A1", None)];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: Some(RemoteStatus::Synced),
    }];

    let output = render_plain(info);
    assert!(
        output.contains("[feature-a] ✓"),
        "expected synced indicator, got:\n{}",
        output
    );
}

#[test]
fn remote_ahead_shows_up_arrow() {
    let mut info = base_info();
    info.commits = vec![commit(2, "A2", Some(1)), commit(1, "A1", None)];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: Some(RemoteStatus::Ahead),
    }];

    let output = render_plain(info);
    assert!(
        output.contains("[feature-a] ↑"),
        "expected ahead indicator, got:\n{}",
        output
    );
}

#[test]
fn remote_gone_shows_cross() {
    let mut info = base_info();
    info.commits = vec![commit(2, "A2", Some(1)), commit(1, "A1", None)];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: Some(RemoteStatus::Gone),
    }];

    let output = render_plain(info);
    assert!(
        output.contains("[feature-a] ✗"),
        "expected gone indicator, got:\n{}",
        output
    );
}

#[test]
fn no_remote_shows_no_indicator() {
    let mut info = base_info();
    info.commits = vec![commit(2, "A2", Some(1)), commit(1, "A1", None)];
    info.branches = vec![BranchInfo {
        name: "feature-a".to_string(),
        tip_oid: oid(2),
        remote: None,
    }];

    let output = render_plain(info);
    // Branch header line should end with ] and nothing after it
    let header_line = output.lines().find(|l| l.contains("[feature-a]")).unwrap();
    assert!(
        header_line.ends_with("[feature-a]"),
        "expected no indicator after ], got: {}",
        header_line
    );
}