gitlimes 0.1.0

Fast, low-memory git history CLI: colored log, branches, author stats and a unicode commit graph
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
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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
//! End-to-end tests: they run the real built binary against a real git
//! repository, which is the only way to cover `repo.rs` (the streaming record
//! reader) and the argument parsing in `cmd/`.

mod fixture;

use fixture::{
    empty_repo, graph_shape, has_ansi, non_repo, repo, strip_ansi, Fixture, ALICE_COMMITS,
    BOB_COMMITS, BODY_MARKER, MAIN_COMMITS, SIDE_BRANCH, TRICKY_SUBJECT,
};

// ---------------------------------------------------------------- fixture

#[test]
fn fixture_builds_the_expected_topology() {
    let f = repo();
    let graph = f.git(&["log", "--graph", "--oneline", "--format=%s"]);
    assert_eq!(
        graph_shape(&graph),
        vec!["*", "*", "|\\", "| *", "| *", "* |", "|/", "*", "*"],
        "fixture history is not the shape the tests assume:\n{}",
        graph
    );
}

// -------------------------------------------------------------------- log

#[test]
fn log_lists_every_reachable_commit_in_git_order() {
    let f = repo();
    let expected = f.git(&["log", "--format=%h"]);
    let out = f.ok(&["log", "--no-color"]);

    let got: Vec<&str> = out
        .lines()
        .map(|l| l.split_whitespace().next().unwrap())
        .collect();
    let want: Vec<&str> = expected.lines().collect();
    assert_eq!(got, want, "log dropped, added or reordered commits");
    assert_eq!(
        got.len(),
        MAIN_COMMITS,
        "main should have 7 reachable commits"
    );
}

#[test]
fn log_never_leaks_the_commit_message_body() {
    // %s is the subject alone. If the record reader mis-split on newlines the
    // body would ride along into the output.
    let f = repo();
    let out = f.ok(&["log", "--no-color"]);
    assert!(
        !out.contains(BODY_MARKER),
        "the message body leaked into log output:\n{}",
        out
    );
    assert!(out.contains("docs: readme"), "the subject is missing");
}

#[test]
fn log_survives_separators_quotes_and_unicode_in_a_subject() {
    let f = repo();
    let out = f.ok(&["log", "--no-color"]);
    assert!(
        out.contains(TRICKY_SUBJECT),
        "a subject with quotes, a pipe, a backslash and unicode was mangled:\n{}",
        out
    );
    assert_eq!(
        out.lines().count(),
        MAIN_COMMITS,
        "the tricky subject split a record"
    );
}

#[test]
fn log_n_limits_output() {
    let f = repo();
    assert_eq!(f.ok(&["log", "-n", "3", "--no-color"]).lines().count(), 3);
    assert_eq!(
        f.ok(&["log", "--max-count=2", "--no-color"])
            .lines()
            .count(),
        2,
        "--flag=value form is not parsed"
    );
}

#[test]
fn log_author_filter_selects_one_persons_commits() {
    let f = repo();
    let out = f.ok(&["log", "--author", "Bob", "--no-color"]);
    assert_eq!(
        out.lines().count(),
        2,
        "Bob has 2 commits reachable from main"
    );
    assert!(out.lines().all(|l| l.contains("Bob")));
}

#[test]
fn log_oneline_prints_hash_and_subject_only() {
    let f = repo();
    let out = f.ok(&["log", "-n", "1", "--oneline", "--no-color"]);
    let line = out.lines().next().unwrap();
    assert!(line.ends_with("chore: release"));
    assert!(!line.contains("Alice"), "--oneline should omit the author");
}

#[test]
fn log_decorates_refs() {
    let f = repo();
    let out = f.ok(&["log", "-n", "1", "--no-color"]);
    assert!(
        out.contains("HEAD -> main"),
        "missing HEAD decoration:\n{}",
        out
    );
    assert!(
        out.contains("tag: v1.0"),
        "missing tag decoration:\n{}",
        out
    );
}

#[test]
fn log_accepts_a_path_after_a_double_dash() {
    let f = repo();
    let out = f.ok(&["log", "--no-color", "--", "c.txt"]);
    assert_eq!(out.lines().count(), 1, "only one commit touched c.txt");
    assert!(out.contains("feat: first side"));
}

#[test]
fn log_all_reaches_commits_off_the_current_branch() {
    let f = repo();
    let out = f.ok(&["log", "--all", "--no-color"]);
    assert!(
        out.contains("wip: abandoned"),
        "--all should reach the unmerged branch"
    );
    assert_eq!(out.lines().count(), MAIN_COMMITS + 1);
}

// --------------------------------------------------------------- branches

#[test]
fn branches_lists_every_local_branch_with_the_current_one_marked() {
    let f = repo();
    let out = f.ok(&["branches", "--no-color"]);
    assert_eq!(out.lines().count(), 3, "main, feature and stale/old");
    let current: Vec<&str> = out.lines().filter(|l| l.starts_with('*')).collect();
    assert_eq!(current.len(), 1, "exactly one branch is current");
    assert!(current[0].contains("main"));
    assert!(out.contains(SIDE_BRANCH));
}

#[test]
fn branches_vs_reports_ahead_and_behind() {
    // The exact numbers matter: `%(ahead-behind:)` reports "ahead behind" while
    // `rev-list --left-right` reports "behind ahead", so an inverted pair is a
    // silent, plausible-looking wrong answer.
    //
    // The side branch forked at E and added G, so it is ahead by 1. It is
    // behind by 4, not 2: main gained F and the merge M, and M also brought C
    // and D into main's reachable set.
    let f = repo();
    let out = f.ok(&["branches", "--vs", "main", "--no-color"]);
    let side = out
        .lines()
        .find(|l| l.contains(SIDE_BRANCH))
        .expect("the side branch is listed");
    assert!(
        side.contains("ahead 1, behind 4"),
        "expected 'ahead 1, behind 4', got: {}",
        side
    );

    let main = out
        .lines()
        .find(|l| l.starts_with('*'))
        .expect("main is listed");
    assert!(
        !main.contains("ahead") && !main.contains("behind"),
        "main compared against itself must show no divergence, got: {}",
        main
    );
}

#[test]
fn branches_marks_old_branches_as_stale() {
    let f = repo();
    // Every fixture commit is dated 2021, so a 1-day threshold marks them all.
    let out = f.ok(&["branches", "--stale", "1", "--no-color"]);
    assert_eq!(
        out.lines().filter(|l| l.contains("stale")).count(),
        3,
        "all three branches are older than a day:\n{}",
        out
    );
    let fresh = f.ok(&["branches", "--stale", "99999", "--no-color"]);
    assert_eq!(
        fresh.lines().filter(|l| l.contains("stale")).count(),
        0,
        "nothing should be marked stale with a huge threshold:
{}",
        fresh
    );
}

// -------------------------------------------------------------------- who

#[test]
fn who_counts_commits_per_author() {
    let f = repo();
    let out = strip_ansi(&f.ok(&["who", "--no-color"]));
    let alice = out
        .lines()
        .find(|l| l.contains("Alice"))
        .expect("Alice listed");
    let bob = out.lines().find(|l| l.contains("Bob")).expect("Bob listed");
    // Alice: init, readme, mainline fix, merge, release. Bob: the two side commits.
    assert!(
        alice.trim_start().starts_with(&ALICE_COMMITS.to_string()),
        "Alice row: {}",
        alice
    );
    assert!(
        bob.trim_start().starts_with(&BOB_COMMITS.to_string()),
        "Bob row: {}",
        bob
    );
    assert!(
        out.contains("alice"),
        "the email column identifies the author"
    );
}

#[test]
fn who_ranks_by_commit_count() {
    let f = repo();
    let out = strip_ansi(&f.ok(&["who", "--no-color"]));
    let rows: Vec<&str> = out.lines().skip(1).collect();
    assert!(rows[0].contains("Alice"), "the busiest author comes first");
    assert!(rows[1].contains("Bob"));
}

#[test]
fn who_limit_truncates_the_table() {
    let f = repo();
    let out = f.ok(&["who", "--limit", "1", "--no-color"]);
    assert_eq!(out.lines().count(), 2, "one header plus one author");
    assert!(out.contains("Alice"));
}

#[test]
fn who_scoped_to_a_path_only_counts_that_path() {
    let f = repo();
    let out = strip_ansi(&f.ok(&["who", "--no-color", "--", "c.txt"]));
    assert!(out.contains("Bob"), "Bob created c.txt");
    assert!(
        !out.contains("Alice"),
        "Alice never touched c.txt:\n{}",
        out
    );
}

#[test]
fn who_lines_counts_added_and_removed() {
    let f = repo();
    let out = strip_ansi(&f.ok(&["who", "--lines", "--no-color"]));
    assert!(out.contains("+LINES") && out.contains("-LINES"));
    let alice = out.lines().find(|l| l.contains("Alice")).unwrap();
    assert!(
        alice.contains('+'),
        "expected an added-lines figure: {}",
        alice
    );
}

// ------------------------------------------------------------------ graph

#[test]
fn graph_topology_matches_git_log_graph() {
    let f = repo();
    let out = strip_ansi(&f.ok(&["graph", "--ascii", "--no-color"]));
    assert_eq!(
        graph_shape(&out),
        vec![
            "*",    // chore: release
            "o",    // merge: feature
            "+-\\", //   branches out to the side lane
            "| *",  //   the tricky-subject commit
            "| *",  //   feat: first side
            "* |",  // fix: mainline fix
            "+-/",  //   the side lane folds back in
            "*",    // docs: readme
            "*",    // chore: init
        ],
        "graph shape drifted:\n{}",
        out
    );
}

#[test]
fn graph_commit_order_matches_git_topo_order() {
    let f = repo();
    let want: Vec<String> = f
        .git(&["log", "--topo-order", "--format=%h"])
        .lines()
        .map(str::to_string)
        .collect();
    let out = strip_ansi(&f.ok(&["graph", "--no-color"]));
    let got: Vec<String> = out
        .lines()
        .filter_map(|l| {
            l.split_whitespace()
                .find(|w| w.len() == 7 && w.chars().all(|c| c.is_ascii_hexdigit()))
                .map(str::to_string)
        })
        .collect();
    assert_eq!(got, want, "graph visited commits in the wrong order");
}

#[test]
fn graph_marks_merges_with_a_hollow_dot() {
    let f = repo();
    let out = strip_ansi(&f.ok(&["graph", "--ascii", "--no-color"]));
    let merge = out.lines().find(|l| l.contains("merge: feature")).unwrap();
    assert!(merge.starts_with('o'), "merge row: {}", merge);
    let normal = out.lines().find(|l| l.contains("chore: release")).unwrap();
    assert!(normal.starts_with('*'), "ordinary commit row: {}", normal);
}

#[test]
fn graph_ascii_and_unicode_describe_the_same_history() {
    let f = repo();
    let ascii = strip_ansi(&f.ok(&["graph", "--ascii", "--no-color"]));
    let unicode = strip_ansi(&f.ok(&["graph", "--no-color"]));
    assert_eq!(
        ascii.lines().count(),
        unicode.lines().count(),
        "the two charsets disagree on row count"
    );
    assert!(
        !unicode.contains('*'),
        "unicode mode should not emit ASCII dots"
    );
    assert!(
        unicode.contains('\u{25cf}') && unicode.contains('\u{2502}'),
        "expected box-drawing glyphs"
    );
}

// ------------------------------------------------------------ colour rules

#[test]
fn output_is_plain_when_redirected() {
    // Output is captured through a pipe, so tty detection must turn colour off
    // even though no flag was passed.
    let f = repo();
    for args in [
        vec!["log", "-n", "1"],
        vec!["branches"],
        vec!["who"],
        vec!["graph", "-n", "1"],
    ] {
        let out = f.ok(&args);
        assert!(!has_ansi(&out), "{:?} emitted colour when redirected", args);
    }
}

#[test]
fn color_flag_forces_colour_even_off_a_tty() {
    let f = repo();
    assert!(has_ansi(&f.ok(&["log", "-n", "1", "--color"])));
    assert!(has_ansi(&f.ok(&["graph", "-n", "1", "--color"])));
}

#[test]
fn no_color_env_suppresses_colour() {
    let f = repo();
    // Forced on, but NO_COLOR in the environment must still win.
    let out = f.run_no_color_env(&["log", "-n", "1"]);
    assert!(!has_ansi(&String::from_utf8_lossy(&out.stdout)));
}

// -------------------------------------------------------- errors and exits

#[test]
fn outside_a_repository_every_command_fails_cleanly() {
    let f = non_repo();
    for cmd in ["log", "branches", "who", "graph"] {
        let out = f.run(&[cmd]);
        assert!(
            !out.status.success(),
            "{} should exit non-zero outside a repository",
            cmd
        );
        let err = String::from_utf8_lossy(&out.stderr);
        assert!(
            err.to_lowercase().contains("not a git repository"),
            "{} gave an unhelpful error: {}",
            cmd,
            err
        );
        assert!(out.stdout.is_empty(), "{} printed rows anyway", cmd);
    }
}

#[test]
fn an_empty_repository_does_not_panic() {
    let f = empty_repo();
    for cmd in ["log", "branches", "who", "graph"] {
        let out = f.run(&[cmd]);
        let err = String::from_utf8_lossy(&out.stderr);
        assert!(
            !err.contains("panicked"),
            "{} panicked on an empty repository: {}",
            cmd,
            err
        );
    }
}

#[test]
fn unknown_commands_and_flags_exit_two() {
    let f = repo();
    assert_eq!(f.run(&["bogus"]).status.code(), Some(2));
    assert_eq!(f.run(&["log", "--bogus"]).status.code(), Some(2));
    assert_eq!(f.run(&[]).status.code(), Some(2), "no command prints usage");
    // A flag that needs a value but has none must be rejected, not ignored.
    assert_eq!(f.run(&["log", "-n"]).status.code(), Some(2));
    assert_eq!(f.run(&["who", "--limit", "abc"]).status.code(), Some(2));
    assert_eq!(
        f.run(&["branches", "--stale", "soon"]).status.code(),
        Some(2)
    );
}

#[test]
fn help_and_version_succeed_for_every_command() {
    let f = repo();
    for cmd in ["log", "branches", "who", "graph"] {
        let out = f.ok(&[cmd, "--help"]);
        assert!(out.contains("USAGE"), "{} --help lacks usage", cmd);
    }
    assert!(f.ok(&["--help"]).contains("gitlimes"));
    assert!(f.ok(&["--version"]).contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn a_revision_is_never_mistaken_for_a_flag() {
    // Everything the user supplies goes after `--`, so a path that looks like a
    // flag cannot reach git as one.
    let f = repo();
    let out = f.run(&["log", "--no-color", "--", "--not-a-real-flag"]);
    assert!(
        out.status.success(),
        "a path shaped like a flag should be treated as a path, stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(out.stdout.is_empty(), "no commit touches that path");
}

// ------------------------------------------------------------------- json

#[test]
fn json_emits_one_object_per_line() {
    let f = repo();
    let out = f.ok(&["log", "--json"]);
    assert_eq!(out.lines().count(), MAIN_COMMITS);
    for line in out.lines() {
        assert!(
            line.starts_with('{') && line.ends_with('}'),
            "not a self-contained object: {}",
            line
        );
    }
}

#[test]
fn json_escapes_quotes_and_backslashes_in_a_subject() {
    // The fixture subject contains a quote and a backslash. If either reached
    // the output raw the line would be invalid JSON, and every consumer would
    // break on exactly the commits that are hardest to notice.
    let f = repo();
    let line = f
        .ok(&["log", "--json"])
        .lines()
        .find(|l| l.contains("pipe"))
        .expect("the tricky subject is present")
        .to_string();

    assert!(
        line.contains(r#"\""#),
        "the quote was not escaped: {}",
        line
    );
    assert!(
        line.contains(r"\\"),
        "the backslash was not escaped: {}",
        line
    );
    assert!(
        line.contains("Přílíš žluťoučký kůň"),
        "non-ASCII should pass through unescaped: {}",
        line
    );
    assert_eq!(
        balanced_braces(&line),
        Some(1),
        "brace nesting is broken: {}",
        line
    );
}

#[test]
fn json_never_contains_a_raw_control_character() {
    let f = repo();
    for args in [
        vec!["log", "--json"],
        vec!["branches", "--json"],
        vec!["who", "--json"],
        vec!["graph", "--json"],
    ] {
        let out = f.ok(&args);
        for line in out.lines() {
            assert!(
                !line.chars().any(|c| (c as u32) < 0x20),
                "{:?} emitted a raw control character",
                args
            );
        }
    }
}

#[test]
fn json_output_is_never_coloured() {
    // --color forces colour on, but a JSON consumer would choke on escapes.
    let f = repo();
    for args in [
        vec!["log", "--json", "--color"],
        vec!["branches", "--json", "--color"],
        vec!["who", "--json", "--color"],
        vec!["graph", "--json", "--color"],
    ] {
        assert!(!has_ansi(&f.ok(&args)), "{:?} emitted colour", args);
    }
}

#[test]
fn log_json_carries_the_fields_a_consumer_needs() {
    let f = repo();
    let out = f.ok(&["log", "-n", "1", "--json"]);
    let line = out.lines().next().unwrap();
    for key in [
        r#""hash":"#,
        r#""short":"#,
        r#""parents":"#,
        r#""author":"#,
        r#""date":"#,
        r#""refs":"#,
        r#""subject":"#,
    ] {
        assert!(line.contains(key), "missing {} in {}", key, line);
    }
    assert!(line.contains(r#""head":true"#), "HEAD is not marked");
    assert!(line.contains(r#""v1.0""#), "the tag should appear in refs");
    assert!(
        !line.contains("tag: ") && !line.contains(" -> "),
        "decorations should be stripped from ref names: {}",
        line
    );
}

#[test]
fn graph_json_carries_lane_geometry() {
    // This is what lets a second renderer draw the graph without re-deriving
    // the layout, so it is the part most worth pinning.
    let f = repo();
    let out = f.ok(&["graph", "--json"]);
    assert_eq!(out.lines().count(), MAIN_COMMITS);

    let merge = out
        .lines()
        .find(|l| l.contains("merge: feature"))
        .expect("the merge commit is present");
    assert!(merge.contains(r#""merge":true"#), "merge not flagged");
    assert!(
        merge.contains(r#""opening":[1]"#),
        "the merge should open lane 1: {}",
        merge
    );

    let root = out
        .lines()
        .find(|l| l.contains("chore: init"))
        .expect("the root commit is present");
    assert!(root.contains(r#""merge":false"#));
    assert!(
        root.contains(r#""parents":[]"#),
        "the root has no parents: {}",
        root
    );
}

#[test]
fn who_json_reports_counts_and_the_sparkline_scale() {
    let f = repo();
    let out = f.ok(&["who", "--json"]);
    assert_eq!(out.lines().count(), 2, "two authors");
    let alice = out.lines().find(|l| l.contains("Alice")).unwrap();
    assert!(alice.contains(&format!(r#""commits":{}"#, ALICE_COMMITS)));
    assert!(
        alice.contains(r#""bucket_seconds":"#),
        "the sparkline scale must be stated, not implied: {}",
        alice
    );
    assert!(alice.contains(r#""activity":["#));
    assert!(
        !alice.contains(r#""added":"#),
        "line counts are opt-in via --lines"
    );
    assert!(f.ok(&["who", "--lines", "--json"]).contains(r#""added":"#));
}

#[test]
fn branches_json_marks_the_current_branch() {
    let f = repo();
    let out = f.ok(&["branches", "--json"]);
    assert_eq!(out.lines().count(), 3);
    assert_eq!(
        out.lines()
            .filter(|l| l.contains(r#""current":true"#))
            .count(),
        1,
        "exactly one branch is checked out"
    );
}

/// Returns the maximum brace depth, or `None` if the braces never balance.
/// Quotes and escapes are honoured so a `{` inside a subject does not count.
fn balanced_braces(s: &str) -> Option<usize> {
    let (mut depth, mut max, mut in_str, mut escaped) = (0i32, 0usize, false, false);
    for ch in s.chars() {
        if escaped {
            escaped = false;
            continue;
        }
        match ch {
            '\\' if in_str => escaped = true,
            '"' => in_str = !in_str,
            '{' if !in_str => {
                depth += 1;
                max = max.max(depth as usize);
            }
            '}' if !in_str => {
                depth -= 1;
                if depth < 0 {
                    return None;
                }
            }
            _ => {}
        }
    }
    if depth == 0 && !in_str {
        Some(max)
    } else {
        None
    }
}

// ------------------------------------------------------------------ pager

#[test]
fn paging_does_not_change_the_output() {
    // `cat` stands in for a real pager: same bytes, just routed through a pipe.
    let f = repo();
    let direct = f.ok(&["log", "--no-pager", "--no-color"]);
    let paged = f.run_env(
        &[("GITLIMES_PAGER", "cat")],
        &["log", "--pager", "--no-color"],
    );
    assert!(paged.status.success());
    assert_eq!(
        String::from_utf8_lossy(&paged.stdout),
        direct,
        "paging altered the output"
    );
}

#[test]
fn a_missing_pager_falls_back_instead_of_failing() {
    // A stale PAGER setting is common and must never break the tool.
    let f = repo();
    let out = f.run_env(
        &[("GITLIMES_PAGER", "definitely-not-a-real-program-xyz")],
        &["log", "-n", "2", "--pager", "--no-color"],
    );
    assert!(
        out.status.success(),
        "an unusable pager should degrade quietly, stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(String::from_utf8_lossy(&out.stdout).lines().count(), 2);
}

#[test]
fn an_empty_pager_setting_disables_paging() {
    let f = repo();
    let out = f.run_env(
        &[("PAGER", "")],
        &["log", "-n", "2", "--pager", "--no-color"],
    );
    assert!(out.status.success());
    assert_eq!(String::from_utf8_lossy(&out.stdout).lines().count(), 2);
}

#[test]
fn output_is_not_paged_when_redirected() {
    // Tests capture stdout through a pipe, so Auto mode must not page - if it
    // did, a nonexistent pager would be spawned on every ordinary run.
    let f = repo();
    let out = f.run_env(
        &[("GITLIMES_PAGER", "definitely-not-a-real-program-xyz")],
        &["log", "-n", "2", "--no-color"],
    );
    assert!(out.status.success());
    assert_eq!(String::from_utf8_lossy(&out.stdout).lines().count(), 2);
}

#[test]
fn every_command_accepts_the_pager_flags() {
    let f = repo();
    for cmd in ["log", "branches", "who", "graph"] {
        assert!(f.run(&[cmd, "--no-pager"]).status.success(), "{}", cmd);
        assert!(
            f.run_env(&[("GITLIMES_PAGER", "cat")], &[cmd, "--pager"])
                .status
                .success(),
            "{}",
            cmd
        );
    }
}

// ------------------------------------------------- json schema contract

/// The published field names, per command. Renaming or removing any of these
/// breaks every script written against the tool, silently and at a distance.
///
/// Adding a key is allowed by the contract, so a new one here is a prompt to
/// update this list and note it in CHANGELOG.md - not a failure.
#[test]
fn json_field_names_are_a_stable_contract() {
    let f = repo();

    let cases: [(&[&str], &[&str], &[&str]); 4] = [
        (
            &["log", "-n", "1", "--json"],
            &[
                "hash", "short", "parents", "author", "date", "refs", "subject",
            ],
            &["head"],
        ),
        (
            &["branches", "--json"],
            &["name", "current", "date", "author", "subject"],
            &["track"],
        ),
        (
            &["who", "--json"],
            &[
                "name",
                "email",
                "commits",
                "first",
                "last",
                "activity",
                "bucket_seconds",
            ],
            &["added", "removed"],
        ),
        (
            &["graph", "-n", "1", "--json"],
            &[
                "hash", "short", "parents", "author", "date", "refs", "subject", "graph",
            ],
            &["head"],
        ),
    ];

    for (args, required, optional) in cases {
        let out = f.ok(args);
        let line = out.lines().next().expect("at least one record");
        let keys = top_level_keys(line);

        for key in required {
            assert!(
                keys.iter().any(|k| k == key),
                "{:?} lost the required key {:?}; keys were {:?}",
                args,
                key,
                keys
            );
        }
        for key in &keys {
            assert!(
                required.contains(&key.as_str()) || optional.contains(&key.as_str()),
                "{:?} grew an undocumented key {:?}: add it to this list and to CHANGELOG.md",
                args,
                key
            );
        }
    }
}

#[test]
fn graph_json_geometry_keys_are_stable() {
    let f = repo();
    let out = f.ok(&["graph", "-n", "1", "--json"]);
    for key in ["col", "lanes", "merge", "closing", "opening", "shifts"] {
        assert!(
            out.contains(&format!("\"{}\":", key)),
            "graph geometry lost {:?}; a renderer depends on it",
            key
        );
    }
}

/// Top-level keys of a JSON object: the names before each `:` at depth 1.
///
/// Written by hand because the project has no dependencies. It tracks whether
/// the next string is a key or a value, so `"author":"Alice"` yields `author`
/// and not `Alice`, and it ignores anything nested or inside a string.
fn top_level_keys(text: &str) -> Vec<String> {
    let mut keys = Vec::new();
    let mut current = String::new();
    let mut depth = 0i32;
    // Commas inside an array separate elements, not key/value pairs.
    let mut array_depth = 0i32;
    let mut in_string = false;
    let mut escaped = false;
    // At depth 1 a string is a key until a ':' says the next one is a value.
    let mut next_string_is_key = false;

    for ch in text.chars() {
        if escaped {
            current.push(ch);
            escaped = false;
            continue;
        }
        if in_string {
            match ch {
                '\\' => escaped = true,
                '"' => {
                    in_string = false;
                    if depth == 1 && next_string_is_key {
                        keys.push(std::mem::take(&mut current));
                    }
                }
                c => current.push(c),
            }
            continue;
        }
        match ch {
            '"' => {
                current.clear();
                in_string = true;
            }
            '{' => {
                depth += 1;
                next_string_is_key = depth == 1 && array_depth == 0;
            }
            '}' => depth -= 1,
            '[' => {
                array_depth += 1;
                next_string_is_key = false;
            }
            ']' => array_depth -= 1,
            ',' => next_string_is_key = depth == 1 && array_depth == 0,
            ':' => next_string_is_key = false,
            _ => {}
        }
    }
    keys
}

#[test]
fn the_key_scanner_reads_keys_and_not_values() {
    // The contract test is only as trustworthy as this helper.
    assert_eq!(
        top_level_keys(r#"{"a":"x","b":1,"c":{"inner":2},"d":["e","f"]}"#),
        vec!["a", "b", "c", "d"],
        "nested keys and string values must not be counted"
    );
    assert_eq!(
        top_level_keys(r#"{"tricky":"has : and , and \" inside"}"#),
        vec!["tricky"],
        "punctuation inside a string must not confuse the scan"
    );
    assert!(top_level_keys("{}").is_empty());
}

// --------------------------------------------------- audit regressions

#[test]
fn a_zero_limit_prints_a_header_instead_of_crashing() {
    // `--limit 0` is accepted by the parser, so it must not then panic. The
    // guard against an empty author list ran before the truncation that
    // emptied it.
    let f = repo();
    let out = f.run(&["who", "--limit", "0", "--no-color", "--no-pager"]);
    assert!(
        out.status.success(),
        "who --limit 0 exited {:?}: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(f.run(&["who", "--limit=0"]).status.success());
}

#[test]
fn stale_rejects_values_that_cannot_mean_a_threshold() {
    // A negative threshold puts the cutoff in the future and marks everything
    // stale; a huge one overflowed the multiply into seconds.
    let f = repo();
    for bad in ["-1", "999999999999999", "1.5", "abc"] {
        let out = f.run(&["branches", "--stale", bad, "--no-color", "--no-pager"]);
        assert_eq!(
            out.status.code(),
            Some(2),
            "--stale {} should be rejected, got {:?}",
            bad,
            out.status.code()
        );
    }
    assert!(f.run(&["branches", "--stale", "0"]).status.success());
    assert!(f
        .run(&["branches", "--stale", "4294967295"])
        .status
        .success());
}

#[test]
fn global_flags_do_not_eat_operands_after_a_double_dash() {
    // A path may legitimately be spelled `--color`. Stripping it as a global
    // flag both changed the colour and silently dropped the path filter.
    let f = repo();
    let out = f.run(&["log", "--no-color", "--", "--color"]);
    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        !has_ansi(&text),
        "the operand was consumed as a colour flag"
    );
    assert!(
        text.trim().is_empty(),
        "no commit touches a path named --color, got: {}",
        text
    );

    let paged = f.run(&["log", "--no-pager", "--", "--pager"]);
    assert!(paged.status.success());
    assert!(String::from_utf8_lossy(&paged.stdout).trim().is_empty());
}

#[test]
fn boolean_flags_reject_an_inline_value() {
    // `--json=false` silently enabled JSON, because the value was parsed off
    // and then discarded.
    let f = repo();
    for bad in ["--json=false", "--oneline=no", "--all=0"] {
        let out = f.run(&["log", bad, "--no-color", "--no-pager"]);
        assert_eq!(
            out.status.code(),
            Some(2),
            "log {} should be rejected, got {:?}",
            bad,
            out.status.code()
        );
    }
    assert!(f.run(&["branches", "--json=false"]).status.code() == Some(2));
    assert!(f.run(&["who", "--lines=maybe"]).status.code() == Some(2));
    assert!(f.run(&["graph", "--ascii=yes"]).status.code() == Some(2));
}

#[test]
fn only_the_checked_out_commit_is_marked_head() {
    // `head` came from a substring test, so `origin/HEAD` and any branch named
    // like HEAD also claimed to be checked out.
    let f = Fixture::new("head-substring");
    f.git(&["branch", "HEADROOM", "main~2"]);
    f.git(&["branch", "SUBHEADING", "main~3"]);

    let out = f.ok(&["log", "--all", "--json"]);
    let marked: Vec<&str> = out
        .lines()
        .filter(|l| l.contains(r#""head":true"#))
        .collect();
    assert_eq!(
        marked.len(),
        1,
        "exactly one commit is checked out, got {}:\n{}",
        marked.len(),
        marked.join("\n")
    );
    assert!(
        marked[0].contains("chore: release"),
        "the wrong commit was marked: {}",
        marked[0]
    );
}

// ------------------------------------------------------- pager resolution

/// Copies the gitlimes binary itself into `dir` and returns the new path.
///
/// Using the binary under test as the pager keeps this portable: it is a real
/// executable on every platform, and `--version` gives it output of its own
/// that cannot be confused with a log line.
fn pager_stub(dir: &std::path::Path) -> std::path::PathBuf {
    std::fs::create_dir_all(dir).expect("create pager dir");
    let ext = if cfg!(windows) { ".exe" } else { "" };
    let dest = dir.join(format!("stubpager{}", ext));
    std::fs::copy(env!("CARGO_BIN_EXE_gitlimes"), &dest).expect("copy pager stub");
    dest
}

#[test]
fn a_pager_path_containing_spaces_still_runs() {
    // Splitting the setting on whitespace turned `C:\Program Files\...` into a
    // program plus arguments, which failed to spawn, which silently disabled
    // paging. On Windows most pager paths look like that.
    let f = repo();
    let spaced = f.path().join("pager dir with spaces");
    let stub = pager_stub(&spaced);
    assert!(
        stub.to_string_lossy().contains(' '),
        "the fixture path must contain a space"
    );

    let out = f.run_env(
        &[("GITLIMES_PAGER", &format!("{} --version", stub.display()))],
        &["log", "-n", "2", "--pager", "--no-color"],
    );
    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        text.contains("gitlimes "),
        "the pager never ran; output fell back to the log:\n{}",
        text
    );
}

#[test]
fn a_quoted_pager_path_may_still_take_arguments() {
    let f = repo();
    let spaced = f.path().join("another spaced dir");
    let stub = pager_stub(&spaced);

    let out = f.run_env(
        &[(
            "GITLIMES_PAGER",
            &format!("\"{}\" --version", stub.display()),
        )],
        &["log", "-n", "2", "--pager", "--no-color"],
    );
    assert!(out.status.success());
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("gitlimes "),
        "quoting a spaced path should keep the arguments working"
    );
}

#[test]
fn a_failing_command_does_not_open_a_pager() {
    // The pager used to be spawned before the first record was read, so a
    // command that was going to fail still opened one - over the top of git's
    // error message.
    let f = non_repo();
    let stub = pager_stub(&f.path().join("stub"));

    let out = f.run_env(
        &[("GITLIMES_PAGER", &format!("{} --version", stub.display()))],
        &["log", "--pager", "--no-color"],
    );
    assert!(!out.status.success(), "the command itself must still fail");
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        !text.contains("gitlimes "),
        "a pager was spawned for a command that produced nothing:\n{}",
        text
    );
    assert!(
        String::from_utf8_lossy(&out.stderr)
            .to_lowercase()
            .contains("not a git repository"),
        "git's own message must survive"
    );
}

#[test]
fn control_bytes_in_a_subject_survive_intact() {
    // git will store 0x1f and 0x1e in a commit subject if you ask it to, and
    // the record format used to be delimited by exactly those bytes - so a
    // subject containing one was silently truncated at it. NUL is used now,
    // which git rejects outright ("a NUL byte in commit log message not
    // allowed"), and the log is framed by newlines, which no field can carry.
    let f = Fixture::new("control-bytes");
    let unit = format!("before{}after unit-sep", '\u{1f}');
    let record = format!("before{}after record-sep", '\u{1e}');
    f.git(&["commit", "-q", "--allow-empty", "-m", &unit]);
    f.git(&["commit", "-q", "--allow-empty", "-m", &record]);

    let out = f.ok(&["log", "-n", "2", "--no-color", "--no-pager"]);
    assert!(
        out.contains(&record),
        "a subject containing 0x1e was mangled:\n{}",
        out
    );
    assert!(
        out.contains(&unit),
        "a subject containing 0x1f was mangled:\n{}",
        out
    );
    assert_eq!(out.lines().count(), 2, "the records must not split");

    // The JSON path must escape them rather than emit raw control bytes.
    let json = f.ok(&["log", "-n", "2", "--json"]);
    assert_eq!(json.lines().count(), 2);
    for line in json.lines() {
        assert!(
            !line.chars().any(|c| (c as u32) < 0x20),
            "a raw control byte reached the JSON output: {}",
            line
        );
    }
    assert!(
        json.contains("\\u001f") && json.contains("\\u001e"),
        "the control bytes should appear as unicode escapes"
    );
}

#[test]
fn a_branch_named_head_is_listed_and_the_symbolic_ref_is_not() {
    // `refs/remotes/origin/HEAD` shortens to `origin`, not `origin/HEAD`, so a
    // name test never caught the symbolic ref it was written for — while
    // `topic/HEAD`, a perfectly legal branch, was thrown away by it.
    let f = Fixture::new("symref");
    f.git(&["branch", "topic/HEAD"]);
    f.git(&["update-ref", "refs/remotes/origin/main", "main"]);
    f.git(&[
        "symbolic-ref",
        "refs/remotes/origin/HEAD",
        "refs/remotes/origin/main",
    ]);

    let out = f.ok(&["branches", "-a", "--no-color", "--no-pager"]);
    assert!(
        out.contains("topic/HEAD"),
        "a real branch named like HEAD was dropped:\n{}",
        out
    );
    assert!(
        out.contains("origin/main"),
        "the real remote branch should be listed:\n{}",
        out
    );

    // The symbolic ref appears as a bare `origin` column entry; it must not.
    let names: Vec<&str> = out
        .lines()
        .filter_map(|l| l.split_whitespace().next_back().map(|_| l))
        .map(|l| l.trim_start_matches('*').trim())
        .filter_map(|l| l.split_whitespace().next())
        .collect();
    assert!(
        !names.contains(&"origin"),
        "the symbolic ref leaked in as a branch: {:?}",
        names
    );

    // And the same through --json, which is what a script would read.
    let json = f.ok(&["branches", "-a", "--json"]);
    assert!(json.contains(r#""name":"topic/HEAD""#), "json: {}", json);
    assert!(!json.contains(r#""name":"origin""#), "json: {}", json);
}

// -------------------------------------------- who: control-byte survival

#[test]
fn who_does_not_drop_a_commit_whose_author_email_contains_0x1e() {
    // `who` used to frame its records on a literal 0x1e byte - a byte git
    // stores in an ident without complaint - so an author email containing
    // one split the record early and the commit vanished, silently
    // shrinking the total and skewing every other author's share.
    //
    // A private fixture, not the shared `repo()`: this commits directly onto
    // it, and `repo()` is reused read-only by every other test in this file.
    // It still starts from the same default history (its own Alice and Bob at
    // different addresses), so this checks for the poisoned author
    // specifically rather than assuming a total author count.
    let f = Fixture::new("who-control-byte");
    let poisoned_email = format!("carol{}x@e.com", '\u{1e}');
    f.git_as(
        99,
        "Carol",
        &poisoned_email,
        &[
            "commit",
            "-q",
            "--allow-empty",
            "-m",
            "carol with a poisoned email",
        ],
    );

    let out = strip_ansi(&f.ok(&["who", "--no-color"]));
    let carol = out
        .lines()
        .find(|l| l.contains("Carol"))
        .unwrap_or_else(|| panic!("Carol's commit vanished:\n{}", out));
    assert!(
        carol.trim_start().starts_with('1'),
        "Carol should show exactly 1 commit: {}",
        carol
    );

    let json = f.ok(&["who", "--json"]);
    let carol_json = json
        .lines()
        .find(|l| l.contains(r#""name":"Carol""#))
        .unwrap_or_else(|| panic!("Carol is missing from --json:\n{}", json));
    assert!(carol_json.contains(r#""commits":1"#), "{}", carol_json);
    // Per line, not the whole blob: NDJSON's own newlines between records are
    // expected and are not the control byte under test.
    assert!(
        !carol_json.chars().any(|c| (c as u32) < 0x20),
        "the poisoned byte must reach JSON as an escape, not a raw control byte: {}",
        carol_json
    );
    assert!(
        carol_json.contains("\\u001e"),
        "expected the poisoned byte as a unicode escape: {}",
        carol_json
    );
}

#[test]
fn who_lines_attributes_numstat_correctly_across_a_poisoned_commit() {
    // The same poisoned byte must not misattribute --numstat's added/removed
    // counts to the wrong author, or to no one. Uses names distinct from the
    // shared fixture's own Alice/Bob to keep the JSON lookups unambiguous.
    let f = Fixture::new("who-control-byte-lines");
    let poisoned_email = format!("bo{}b@e.com", '\u{1e}');

    std::fs::write(f.path().join("alicetwo.txt"), "one\ntwo\n").unwrap();
    f.git(&["add", "-A"]);
    f.git_as(
        50,
        "AliceTwo",
        "alicetwo@e.com",
        &["commit", "-q", "-m", "alice adds two lines"],
    );

    std::fs::write(f.path().join("bobtwo.txt"), "x\ny\nz\n").unwrap();
    f.git(&["add", "-A"]);
    f.git_as(
        51,
        "BobTwo",
        &poisoned_email,
        &["commit", "-q", "-m", "bob adds three lines"],
    );

    let json = f.ok(&["who", "--lines", "--json"]);
    let bob = json
        .lines()
        .find(|l| l.contains(r#""name":"BobTwo""#))
        .unwrap_or_else(|| panic!("BobTwo is missing from --json:\n{}", json));
    let alice = json
        .lines()
        .find(|l| l.contains(r#""name":"AliceTwo""#))
        .unwrap_or_else(|| panic!("AliceTwo is missing from --json:\n{}", json));
    assert!(
        bob.contains(r#""added":3"#),
        "Bob's added-lines count is wrong or missing: {}",
        bob
    );
    assert!(
        alice.contains(r#""added":2"#),
        "Alice's added-lines count is wrong, or Bob's stats leaked into hers: {}",
        alice
    );
}

// -------------------------------------------------- non-UTF-8 repositories

/// "café" encoded as ISO-8859-1: `c`,`a`,`f`,0xE9. Not valid UTF-8 on its own
/// (0xE9 is a continuation-less lead byte), so if this ever reaches a `&str`
/// unconverted it becomes the JSON- and terminal-safe replacement character.
const LATIN1_CAFE: [u8; 4] = [b'c', b'a', b'f', 0xE9];

#[test]
fn log_and_graph_recover_a_non_utf8_subject_via_git_encoding() {
    // A repository may set i18n.commitEncoding to something other than UTF-8;
    // git then emits %s in that encoding verbatim. Passing --encoding=UTF-8
    // to git asks IT to transcode, which is what fixes this - without it,
    // this project's whole &str pipeline would turn every non-ASCII
    // character into U+FFFD, silently and unrecoverably.
    let f = Fixture::new("non-utf8-subject");
    f.git(&["config", "i18n.commitEncoding", "ISO-8859-1"]);

    let mut subject = LATIN1_CAFE.to_vec();
    subject.push(b'\n');
    std::fs::write(f.path().join("msg.bin"), &subject).unwrap();
    f.git_as(
        90,
        "Author",
        "a@e.com",
        &["commit", "-q", "--allow-empty", "-F", "msg.bin"],
    );

    let out = f.ok(&["log", "-n", "1", "--no-color"]);
    assert!(
        out.contains("café"),
        "the Latin-1 subject was not recovered as UTF-8: {}",
        out
    );
    assert!(
        !out.contains('\u{fffd}'),
        "a replacement character means the byte was lost, not transcoded: {}",
        out
    );

    let graph = f.ok(&["graph", "-n", "1", "--no-color"]);
    assert!(graph.contains("café"), "graph: {}", graph);

    let json = f.ok(&["log", "-n", "1", "--json"]);
    assert!(json.contains(r#""subject":"café"#), "json: {}", json);
}

#[test]
fn who_and_branches_do_not_yet_transcode_a_non_utf8_author_identity() {
    // Documents a known, deliberate boundary rather than leaving it silently
    // unexamined: verified against a hand-built commit object that git's
    // --encoding flag transcodes the message body only, never author or
    // committer name/email, and `for-each-ref` (which `branches` uses) has
    // no --encoding flag at all. So unlike the subject line, a non-UTF-8
    // author identity still comes through lossy. If git ever starts
    // transcoding idents too, this test will fail and need deliberate
    // updating - which is the point, rather than this regressing silently.
    let f = Fixture::new("non-utf8-author");
    f.git(&["config", "i18n.commitEncoding", "ISO-8859-1"]);

    // Author name via a raw, hand-built commit object: env vars and argv are
    // themselves NUL/locale-constrained in ways that would confound a test
    // that went through git_as instead.
    let tree = f.git(&["hash-object", "-t", "tree", "--stdin"]);
    let tree = tree.trim();
    let mut body = Vec::new();
    body.extend_from_slice(format!("tree {}\n", tree).as_bytes());
    body.extend_from_slice(b"author Andr");
    body.push(0xE9); // the same Latin-1 'e-acute' as LATIN1_CAFE's last byte
    body.extend_from_slice(b" <a@e.com> 1700000000 +0000\n");
    body.extend_from_slice(b"committer Andr");
    body.push(0xE9);
    body.extend_from_slice(b" <a@e.com> 1700000000 +0000\n");
    body.extend_from_slice(b"\ntest\n");

    let commit_sha = f
        .git_with_stdin(&["hash-object", "-w", "-t", "commit", "--stdin"], &body)
        .trim()
        .to_string();
    f.git(&["update-ref", "refs/heads/main", &commit_sha]);

    // update-ref pointed main at a single, parentless commit, so this is the
    // only history `who` (HEAD-only, no --all) can see.
    let who_json = f.ok(&["who", "--json"]);
    let entry = who_json
        .lines()
        .next()
        .unwrap_or_else(|| panic!("expected exactly one author: {}", who_json));
    // The current, documented behaviour: the raw byte is not valid UTF-8, so
    // it is replaced, not transcoded. This assertion is the pin - it should
    // fail (and be updated deliberately) the day this gets a real fix.
    assert!(
        entry.contains('\u{fffd}'),
        "author identity encoding either regressed further or was fixed \
         without updating this pinned test: {}",
        entry
    );
}