diffler-core 0.16.1

Core review engine for diffler: diffs, sessions, comments, viewed marks
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
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
mod common;

use std::fmt::Write as _;
use std::path::Path;

use common::Fixture;
use diffler_core::classify::Kind;
use diffler_core::diffalgo::DiffSettings;
use diffler_core::git::GitVcs;
use diffler_core::model::{FileStatus, LineKind};
use diffler_core::vcs::{NetworkOp, Vcs, VcsError};

// helper fns run outside #[test] fns, where clippy's test allowances don't reach
#[allow(clippy::expect_used)]
fn vcs(fx: &Fixture) -> GitVcs {
    GitVcs::open(fx.root()).expect("open")
}

#[allow(clippy::expect_used)]
fn head_oid(fx: &Fixture) -> String {
    fx.repo
        .head()
        .expect("head")
        .peel_to_commit()
        .expect("commit")
        .id()
        .to_string()
}

#[test]
fn git_dir_resolves_to_the_dot_git_directory() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    let dir = vcs(&fx).git_dir().expect("git dir");
    assert_eq!(
        dir.canonicalize().expect("canonicalize"),
        fx.root().join(".git").canonicalize().expect("canonicalize")
    );
}

#[test]
fn git_dir_in_a_linked_worktree_resolves_the_gitlink() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    let wt_dir = tempfile::tempdir().expect("tempdir");
    let wt = wt_dir.path().join("wt");
    let output = std::process::Command::new("git")
        .arg("-C")
        .arg(fx.root())
        .arg("worktree")
        .arg("add")
        .arg(&wt)
        .output()
        .expect("git worktree add");
    assert!(
        output.status.success(),
        "worktree add failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(wt.join(".git").is_file(), "worktree .git is a gitlink file");

    let v = GitVcs::open(&wt).expect("open worktree");
    let dir = v.git_dir().expect("git dir");
    assert!(dir.is_dir(), "resolved gitdir exists: {}", dir.display());
    let expected = fx.root().join(".git/worktrees/wt");
    assert_eq!(
        dir.canonicalize().expect("canonicalize"),
        expected.canonicalize().expect("canonicalize")
    );
}

#[test]
fn context_lines_shrink_hunk_context() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=20 {
        writeln!(base, "line {i}").expect("write");
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    fx.write("a.txt", &base.replace("line 10\n", "LINE TEN\n"));

    let context = |lines: u32| -> usize {
        let v = GitVcs::open_with_settings(fx.root(), &DiffSettings::with_context(lines))
            .expect("open");
        let model = v.working_tree_diff().expect("diff");
        model.files[0].hunks[0]
            .lines
            .iter()
            .filter(|l| l.kind == LineKind::Context)
            .count()
    };
    assert_eq!(context(3), 6, "git default: three lines each side");
    assert_eq!(context(1), 2, "context_lines=1 keeps one line each side");
}

#[test]
fn rehunk_file_expands_context_from_the_files_own_text() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=40 {
        writeln!(base, "line {i}").expect("write");
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    fx.write("a.txt", &base.replace("line 20\n", "LINE TWENTY\n"));

    let model = vcs(&fx).working_tree_diff().expect("diff");
    let file = &model.files[0];
    let context_of = |hunks: &[diffler_core::model::Hunk]| -> usize {
        hunks
            .iter()
            .flat_map(|h| &h.lines)
            .filter(|l| l.kind == LineKind::Context)
            .count()
    };

    let default = context_of(&file.hunks);
    let algorithm = diffler_core::diffalgo::DiffAlgorithm::default();
    let wider = diffler_core::git::rehunk_file(file, 10, algorithm, true).expect("rehunk");
    let whole =
        diffler_core::git::rehunk_file(file, u32::MAX, algorithm, true).expect("rehunk all");

    assert!(
        context_of(&wider) > default,
        "more context lines when widened"
    );
    assert_eq!(
        context_of(&whole),
        39,
        "whole file: every unchanged line shown"
    );
}

#[test]
fn clean_tree_is_empty() {
    let fx = Fixture::new();
    fx.write("a.txt", "hello\n");
    fx.commit_all("base");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    assert!(model.files.is_empty());
}

#[test]
fn modified_file_produces_hunk_with_line_numbers() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\ntwo\nthree\n");
    fx.commit_all("base");
    fx.write("a.txt", "one\nTWO\nthree\n");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    assert_eq!(model.files.len(), 1);
    let file = &model.files[0];
    assert_eq!(file.path, "a.txt");
    assert_eq!(file.status, FileStatus::Modified);
    assert_eq!(file.old_text.as_deref(), Some("one\ntwo\nthree\n"));
    assert_eq!(file.new_text.as_deref(), Some("one\nTWO\nthree\n"));
    assert_eq!(file.hunks.len(), 1);
    let lines = &file.hunks[0].lines;
    let deleted: Vec<_> = lines
        .iter()
        .filter(|l| l.kind == LineKind::Deleted)
        .collect();
    let added: Vec<_> = lines.iter().filter(|l| l.kind == LineKind::Added).collect();
    assert_eq!(deleted.len(), 1);
    assert_eq!(deleted[0].text, "two");
    assert_eq!(deleted[0].old_no, Some(2));
    assert_eq!(deleted[0].new_no, None);
    assert_eq!(added[0].text, "TWO");
    assert_eq!(added[0].new_no, Some(2));
}

#[test]
fn hunk_context_captures_the_enclosing_section() {
    let fx = Fixture::new();
    // an enclosing function far enough above the change that git's default
    // three context lines don't reach it: git then names the section in the
    // hunk header, which we capture into `context`
    let mut base = String::from("fn outer() {\n");
    for i in 1..=10 {
        writeln!(base, "    let v{i} = {i};").expect("write");
    }
    base.push_str("}\n");
    fx.write("a.rs", &base);
    fx.commit_all("base");
    fx.write("a.rs", &base.replace("let v6 = 6;", "let v6 = 60;"));

    let model = vcs(&fx).working_tree_diff().expect("diff");
    let hunk = &model.files[0].hunks[0];
    assert!(
        hunk.context.contains("fn outer()"),
        "enclosing function captured as context: {:?}",
        hunk.context
    );
    // context must not leak into the hunk id, which keys on lines alone
    let lines = hunk.lines.clone();
    let id = diffler_core::model::hunk_id("a.rs", &lines, 0);
    assert_eq!(id, hunk.id, "context does not perturb the hunk id");
}

#[test]
fn two_hunks_with_identical_content_get_distinct_ids() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=20 {
        if i == 3 || i == 17 {
            base.push_str("dup\n");
        } else {
            writeln!(base, "line {i}").expect("write");
        }
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    // the same one-line edit, made twice, far enough apart with no context
    // lines between the two hunks that their content is byte-identical
    fx.write("a.txt", &base.replace("dup\n", "changed\n"));

    let model = GitVcs::open_with_settings(fx.root(), &DiffSettings::with_context(0))
        .expect("open")
        .working_tree_diff()
        .expect("diff");
    let hunks = &model.files[0].hunks;
    assert_eq!(hunks.len(), 2, "two separate, far-apart edits");
    assert_eq!(hunks[0].lines.len(), hunks[1].lines.len());
    for (a, b) in hunks[0].lines.iter().zip(&hunks[1].lines) {
        assert_eq!(a.kind, b.kind);
        assert_eq!(a.text, b.text);
    }
    assert_ne!(
        hunks[0].id, hunks[1].id,
        "identical content still gets distinct ids, so a cursor on the \
         second hunk never reseats onto the first"
    );
}

#[test]
fn top_of_file_hunk_has_empty_context() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=10 {
        writeln!(base, "line {i}").expect("write");
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    fx.write("a.txt", &base.replace("line 1\n", "LINE ONE\n"));

    let model = vcs(&fx).working_tree_diff().expect("diff");
    assert_eq!(
        model.files[0].hunks[0].context, "",
        "no enclosing section above a top-of-file change"
    );
}

#[test]
fn modified_line_pair_carries_intraline_emphasis() {
    let fx = Fixture::new();
    fx.write("a.py", "value = old_name\nrest = 1\n");
    fx.commit_all("base");
    fx.write("a.py", "value = new_name\nrest = 1\n");
    let mut model = vcs(&fx).working_tree_diff().expect("diff");
    // emphasis is deferred out of the backend: enrich the file to assert on it
    diffler_core::pairing::enrich_file(&mut model.files[0]);
    let lines = &model.files[0].hunks[0].lines;
    let deleted = lines
        .iter()
        .find(|l| l.kind == LineKind::Deleted)
        .expect("deleted line");
    let added = lines
        .iter()
        .find(|l| l.kind == LineKind::Added)
        .expect("added line");
    assert_eq!(deleted.text, "value = old_name");
    assert_eq!(added.text, "value = new_name");
    // substitution: both sides emphasize the swapped word
    assert!(!deleted.emphasis.is_empty());
    assert!(!added.emphasis.is_empty());
    let old_hl: String = deleted
        .emphasis
        .iter()
        .map(|r| &deleted.text[r.clone()])
        .collect();
    let new_hl: String = added
        .emphasis
        .iter()
        .map(|r| &added.text[r.clone()])
        .collect();
    // word-level emphasis: the whole substituted token, never a fragment
    assert_eq!(old_hl, "old_name");
    assert_eq!(new_hl, "new_name");
}

#[test]
fn untracked_file_is_included_as_added_lines() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.write("new.txt", "alpha\nbeta\n");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    let file = model
        .files
        .iter()
        .find(|f| f.path == "new.txt")
        .expect("untracked file present");
    assert_eq!(file.status, FileStatus::Untracked);
    let added: Vec<_> = file.hunks[0]
        .lines
        .iter()
        .filter(|l| l.kind == LineKind::Added)
        .map(|l| l.text.as_str())
        .collect();
    assert_eq!(added, vec!["alpha", "beta"]);
}

#[test]
fn deleted_file_reported() {
    let fx = Fixture::new();
    fx.write("gone.txt", "bye\n");
    fx.commit_all("base");
    fx.remove("gone.txt");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    let file = &model.files[0];
    assert_eq!(file.status, FileStatus::Deleted);
    assert!(file.new_text.is_none());
}

#[test]
fn staged_changes_are_included() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    fx.write("a.txt", "ONE\n");
    fx.stage("a.txt");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    assert_eq!(model.files.len(), 1);
    assert_eq!(model.files[0].status, FileStatus::Modified);
}

#[test]
fn binary_file_flagged_without_hunks() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    std::fs::write(fx.root().join("blob.bin"), [0u8, 159, 146, 150]).expect("write");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    let file = model
        .files
        .iter()
        .find(|f| f.path == "blob.bin")
        .expect("binary present");
    assert!(file.binary);
    assert!(file.hunks.is_empty());
}

#[test]
fn empty_repo_with_no_head_diffs_against_nothing() {
    let fx = Fixture::new();
    fx.write("first.txt", "hello\n");
    let model = vcs(&fx).working_tree_diff().expect("diff");
    let file = &model.files[0];
    assert_eq!(file.path, "first.txt");
    assert_eq!(file.status, FileStatus::Untracked);
}

#[test]
fn hunk_ids_survive_unrelated_edits() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=40 {
        writeln!(base, "line {i}").expect("write");
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    let edit_one = base.replace("line 5\n", "LINE FIVE\n");
    fx.write("a.txt", &edit_one);
    let m1 = vcs(&fx).working_tree_diff().expect("diff");
    let id_before = m1.files[0].hunks[0].id.clone();
    // unrelated edit far away creates a second hunk; first hunk id must not move
    let edit_two = edit_one.replace("line 35\n", "LINE THIRTY-FIVE\n");
    fx.write("a.txt", &edit_two);
    let m2 = vcs(&fx).working_tree_diff().expect("diff");
    assert!(m2.files[0].hunks.iter().any(|h| h.id == id_before));
    assert_eq!(m2.files[0].hunks.len(), 2);
}

#[test]
fn commit_diff_shows_only_that_commits_change() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    let root_oid = head_oid(&fx);
    fx.write("a.txt", "two\n");
    fx.write("b.txt", "other\n");
    fx.commit_all("second");
    let second_oid = head_oid(&fx);

    let v = vcs(&fx);
    let second = v.commit_diff(&second_oid).expect("diff");
    assert_eq!(second.files.len(), 2);
    let a = second
        .files
        .iter()
        .find(|f| f.path == "a.txt")
        .expect("a.txt");
    assert_eq!(a.status, FileStatus::Modified);
    let deleted: Vec<_> = a.hunks[0]
        .lines
        .iter()
        .filter(|l| l.kind == LineKind::Deleted)
        .map(|l| l.text.as_str())
        .collect();
    assert_eq!(deleted, vec!["one"]);

    // root commit diffs against the empty tree
    let root = v.commit_diff(&root_oid).expect("diff");
    assert_eq!(root.files.len(), 1);
    assert_eq!(root.files[0].status, FileStatus::Added);
}

#[test]
fn range_diff_combines_two_commits() {
    let fx = Fixture::new();
    fx.write("base.txt", "base\n");
    fx.commit_all("base");
    fx.write("a.txt", "from a\n");
    fx.commit_all("add a");
    let oldest = head_oid(&fx);
    fx.write("b.txt", "from b\n");
    fx.commit_all("add b");
    let newest = head_oid(&fx);

    let v = vcs(&fx);
    let model = v.range_diff(&oldest, &newest).expect("range diff");
    // the base-to-oldest^ boundary excludes base.txt but folds both commits'
    // additions into one diff
    let paths: Vec<&str> = model.files.iter().map(|f| f.path.as_str()).collect();
    assert_eq!(paths, vec!["a.txt", "b.txt"]);
    assert!(model.files.iter().all(|f| f.status == FileStatus::Added));
}

#[test]
fn range_diff_of_a_single_commit_equals_commit_diff() {
    let fx = Fixture::new();
    fx.write("base.txt", "base\n");
    fx.commit_all("base");
    fx.write("base.txt", "changed\n");
    fx.commit_all("change");
    let oid = head_oid(&fx);

    let v = vcs(&fx);
    let range = v.range_diff(&oid, &oid).expect("range diff");
    let single = v.commit_diff(&oid).expect("commit diff");
    assert_eq!(range.files, single.files);
}

#[test]
fn range_diff_over_a_root_commit_uses_the_empty_tree() {
    let fx = Fixture::new();
    fx.write("a.txt", "from a\n");
    fx.commit_all("add a");
    let root = head_oid(&fx);
    fx.write("b.txt", "from b\n");
    fx.commit_all("add b");
    let newest = head_oid(&fx);

    let v = vcs(&fx);
    let model = v.range_diff(&root, &newest).expect("range diff");
    // oldest is the root commit: the range spans the empty tree to newest, so
    // both files appear as additions
    let paths: Vec<&str> = model.files.iter().map(|f| f.path.as_str()).collect();
    assert_eq!(paths, vec!["a.txt", "b.txt"]);
    assert!(model.files.iter().all(|f| f.status == FileStatus::Added));
}

#[test]
fn log_is_newest_first_with_decorations() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("first");
    fx.branch("marker");
    fx.write("a.txt", "two\n");
    fx.commit_all("second");

    let v = vcs(&fx);
    let entries = v.log(10).expect("log");
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0].subject, "second");
    assert_eq!(entries[1].subject, "first");
    assert_eq!(entries[0].oid7.len(), 7);
    assert!(entries[0].oid.starts_with(&entries[0].oid7));
    assert_eq!(entries[0].author, "test");
    assert!(entries[0].time_unix > 0);

    let branch = v.head().expect("head").branch.expect("on a branch");
    assert!(entries[0].refs.contains(&branch));
    assert!(entries[1].refs.contains(&"marker".to_owned()));

    assert_eq!(v.log(1).expect("log").len(), 1);
}

#[test]
fn log_on_unborn_repo_is_empty() {
    let fx = Fixture::new();
    assert!(vcs(&fx).log(10).expect("log").is_empty());
}

#[test]
fn head_reports_branch_oid_and_subject() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    let info = vcs(&fx).head().expect("head");
    assert!(info.branch.is_some());
    assert_eq!(info.oid7.len(), 7);
    assert_eq!(info.subject, "base");
    assert!(info.upstream.is_none());
}

#[test]
fn head_on_unborn_repo_has_no_oid() {
    let fx = Fixture::new();
    let info = vcs(&fx).head().expect("head");
    assert!(info.oid7.is_empty());
    assert!(info.subject.is_empty());
}

#[test]
fn head_follows_fixture_checkout() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.branch("side");
    fx.checkout("side");
    let info = vcs(&fx).head().expect("head");
    assert_eq!(info.branch.as_deref(), Some("side"));
}

#[test]
fn status_separates_staged_and_unstaged_edits_of_same_file() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\ntwo\n");
    fx.commit_all("base");
    fx.write("a.txt", "ONE\ntwo\n");
    fx.stage("a.txt");
    fx.write("a.txt", "ONE\nTWO\n");

    let st = vcs(&fx).status().expect("status");
    assert!(st.untracked.files.is_empty());

    let staged = &st.staged.files;
    assert_eq!(staged.len(), 1);
    assert_eq!(staged[0].path, "a.txt");
    let staged_added: Vec<_> = staged[0].hunks[0]
        .lines
        .iter()
        .filter(|l| l.kind == LineKind::Added)
        .map(|l| l.text.as_str())
        .collect();
    assert_eq!(staged_added, vec!["ONE"]);

    let unstaged = &st.unstaged.files;
    assert_eq!(unstaged.len(), 1);
    assert_eq!(unstaged[0].path, "a.txt");
    let unstaged_added: Vec<_> = unstaged[0].hunks[0]
        .lines
        .iter()
        .filter(|l| l.kind == LineKind::Added)
        .map(|l| l.text.as_str())
        .collect();
    assert_eq!(unstaged_added, vec!["TWO"]);
}

#[test]
fn status_puts_untracked_in_its_own_section() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.write("new.txt", "fresh\n");

    let st = vcs(&fx).status().expect("status");
    assert_eq!(st.untracked.files.len(), 1);
    assert_eq!(st.untracked.files[0].path, "new.txt");
    assert_eq!(st.untracked.files[0].status, FileStatus::Untracked);
    assert!(st.unstaged.files.is_empty());
    assert!(st.staged.files.is_empty());
}

#[test]
fn branches_lists_locals_with_head_marker() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.branch("other");

    let v = vcs(&fx);
    let head_branch = v.head().expect("head").branch.expect("on a branch");
    let branches = v.branches().expect("branches");
    assert_eq!(branches.len(), 2);
    let current = branches
        .iter()
        .find(|b| b.name == head_branch)
        .expect("current listed");
    assert!(current.is_head);
    let other = branches
        .iter()
        .find(|b| b.name == "other")
        .expect("other listed");
    assert!(!other.is_head);
}

#[test]
fn branch_reports_ahead_and_behind_relative_to_upstream() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    let v = vcs(&fx);
    let branch_name = v.head().expect("head").branch.expect("on a branch");

    // upstream gains a commit the local branch never gets
    fx.branch("remote-work");
    fx.checkout("remote-work");
    fx.write("upstream.txt", "only on remote\n");
    fx.commit_all("remote only");
    let remote_oid = head_oid(&fx);
    fx.checkout(&branch_name);
    fx.track(&branch_name, &remote_oid);

    // local branch gains two commits the upstream never gets
    fx.write("a.txt", "two\n");
    fx.commit_all("second");
    fx.write("a.txt", "three\n");
    fx.commit_all("third");

    let branches = v.branches().expect("branches");
    let current = branches
        .iter()
        .find(|b| b.name == branch_name)
        .expect("current listed");
    assert_eq!(
        current.divergence, None,
        "a listing leaves the walk to the caller"
    );
    assert_eq!(
        v.divergence(&branch_name).expect("divergence"),
        Some((2, 1))
    );
}

/// A listing resolves no upstream, so a repository carrying hundreds of
/// branches pays for names and tips alone.
#[test]
fn listing_branches_asks_no_upstream() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    for index in 0..25 {
        fx.branch(&format!("topic-{index}"));
    }

    let v = vcs(&fx);
    let branches = v.branches().expect("branches");

    assert!(branches.len() >= 25);
    assert!(
        branches.iter().all(|branch| branch.divergence.is_none()),
        "every divergence is left to the caller"
    );
}

#[test]
fn branch_without_upstream_reports_zero_divergence_and_still_appears() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.branch("solo");

    let v = vcs(&fx);
    let branches = v.branches().expect("branches");
    assert!(
        branches.iter().any(|b| b.name == "solo"),
        "branch without an upstream is still listed"
    );
    assert_eq!(v.divergence("solo").expect("divergence"), None);
}

#[test]
fn branch_tip_unix_matches_the_tip_commit_and_orders_newest_first() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all_at("base", 1_700_000_000);
    let head_branch = vcs(&fx).head().expect("head").branch.expect("on a branch");

    fx.branch("older");
    fx.checkout("older");
    fx.write("a.txt", "older tip\n");
    fx.commit_all_at("older tip", 1_700_000_100);
    fx.checkout(&head_branch);
    fx.write("a.txt", "newer tip\n");
    fx.commit_all_at("newer tip", 1_700_000_200);

    let v = vcs(&fx);
    let mut branches = v.branches().expect("branches");
    let newer = branches
        .iter()
        .find(|b| b.name == head_branch)
        .expect("head branch listed");
    assert_eq!(newer.tip_unix, 1_700_000_200);
    let older = branches
        .iter()
        .find(|b| b.name == "older")
        .expect("older branch listed");
    assert_eq!(older.tip_unix, 1_700_000_100);

    branches.sort_by_key(|b| std::cmp::Reverse(b.tip_unix));
    assert_eq!(branches[0].name, head_branch, "newest tip sorts first");
    assert_eq!(branches[1].name, "older");
}

#[test]
fn stage_moves_untracked_to_staged() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.write("new.txt", "fresh\n");

    let v = vcs(&fx);
    v.stage(Path::new("new.txt")).expect("stage");

    let st = v.status().expect("status");
    assert!(st.untracked.files.is_empty());
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(st.staged.files[0].path, "new.txt");
    assert_eq!(st.staged.files[0].status, FileStatus::Added);
}

#[test]
fn stage_records_a_worktree_deletion() {
    let fx = Fixture::new();
    fx.write("gone.txt", "bye\n");
    fx.commit_all("base");
    fx.remove("gone.txt");

    let v = vcs(&fx);
    v.stage(Path::new("gone.txt")).expect("stage");

    let st = v.status().expect("status");
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(st.staged.files[0].status, FileStatus::Deleted);
}

#[test]
fn unstage_reverses_stage() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    fx.write("a.txt", "ONE\n");

    let v = vcs(&fx);
    v.stage(Path::new("a.txt")).expect("stage");
    assert_eq!(v.status().expect("status").staged.files.len(), 1);

    v.unstage(Path::new("a.txt")).expect("unstage");
    let st = v.status().expect("status");
    assert!(st.staged.files.is_empty());
    assert_eq!(st.unstaged.files.len(), 1);
    assert_eq!(st.unstaged.files[0].path, "a.txt");
}

#[test]
fn stage_one_hunk_of_two_then_unstage_hunk_reverses() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=40 {
        writeln!(base, "line {i}").expect("write");
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    let edited = base
        .replace("line 5\n", "LINE FIVE\n")
        .replace("line 35\n", "LINE THIRTY-FIVE\n");
    fx.write("a.txt", &edited);

    let v = vcs(&fx);
    let st = v.status().expect("status");
    assert_eq!(st.unstaged.files[0].hunks.len(), 2);
    let first = st.unstaged.files[0].hunks[0].id.clone();

    v.stage_hunk(Path::new("a.txt"), &first)
        .expect("stage hunk");

    let st = v.status().expect("status");
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(st.staged.files[0].hunks.len(), 1);
    assert_eq!(st.staged.files[0].hunks[0].id, first);
    assert_eq!(st.unstaged.files.len(), 1);
    assert_eq!(st.unstaged.files[0].hunks.len(), 1);

    v.unstage_hunk(Path::new("a.txt"), &first)
        .expect("unstage hunk");

    let st = v.status().expect("status");
    assert!(st.staged.files.is_empty());
    assert_eq!(st.unstaged.files[0].hunks.len(), 2);
}

#[test]
fn stage_hunk_on_untracked_file_stages_it() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.write("new.txt", "alpha\nbeta\n");

    let v = vcs(&fx);
    let st = v.status().expect("status");
    let id = st.untracked.files[0].hunks[0].id.clone();
    v.stage_hunk(Path::new("new.txt"), &id).expect("stage hunk");

    let st = v.status().expect("status");
    assert!(st.untracked.files.is_empty());
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(st.staged.files[0].path, "new.txt");
    assert_eq!(st.staged.files[0].status, FileStatus::Added);
    assert_eq!(
        st.staged.files[0].new_text.as_deref(),
        Some("alpha\nbeta\n")
    );
}

#[test]
fn stage_second_hunk_only_applies_at_its_offset() {
    let fx = Fixture::new();
    let mut base = String::new();
    for i in 1..=40 {
        writeln!(base, "line {i}").expect("write");
    }
    fx.write("a.txt", &base);
    fx.commit_all("base");
    let edited = base
        .replace("line 5\n", "LINE FIVE\n")
        .replace("line 35\n", "LINE THIRTY-FIVE\n");
    fx.write("a.txt", &edited);

    let v = vcs(&fx);
    let st = v.status().expect("status");
    assert_eq!(st.unstaged.files[0].hunks.len(), 2);
    let second = st.unstaged.files[0].hunks[1].id.clone();

    v.stage_hunk(Path::new("a.txt"), &second)
        .expect("stage hunk");

    let st = v.status().expect("status");
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(st.staged.files[0].hunks.len(), 1);
    assert_eq!(st.staged.files[0].hunks[0].id, second);
    let staged_text = st.staged.files[0].new_text.as_deref().expect("text");
    assert!(staged_text.contains("LINE THIRTY-FIVE"));
    assert!(!staged_text.contains("LINE FIVE"));
    assert_eq!(st.unstaged.files[0].hunks.len(), 1);
}

#[test]
fn stage_hunk_on_file_without_trailing_newline() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\ntwo\n");
    fx.commit_all("base");
    fx.write("a.txt", "one\ntwo\nthree");

    let v = vcs(&fx);
    let st = v.status().expect("status");
    let id = st.unstaged.files[0].hunks[0].id.clone();
    v.stage_hunk(Path::new("a.txt"), &id).expect("stage hunk");

    let st = v.status().expect("status");
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(
        st.staged.files[0].new_text.as_deref(),
        Some("one\ntwo\nthree")
    );
}

#[test]
fn stage_hunk_on_crlf_file() {
    let fx = Fixture::new();
    fx.write("a.txt", "alpha\r\nbeta\r\n");
    fx.commit_all("base");
    fx.write("a.txt", "alpha\r\nBETA\r\n");

    let v = vcs(&fx);
    let st = v.status().expect("status");
    let id = st.unstaged.files[0].hunks[0].id.clone();
    v.stage_hunk(Path::new("a.txt"), &id).expect("stage hunk");

    let st = v.status().expect("status");
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(
        st.staged.files[0].new_text.as_deref(),
        Some("alpha\r\nBETA\r\n")
    );
}

#[test]
fn stage_hunk_of_whole_file_deletion_records_the_delete() {
    let fx = Fixture::new();
    fx.write("gone.txt", "bye\n");
    fx.commit_all("base");
    fx.remove("gone.txt");

    let v = vcs(&fx);
    let st = v.status().expect("status");
    let id = st.unstaged.files[0].hunks[0].id.clone();
    v.stage_hunk(Path::new("gone.txt"), &id)
        .expect("stage hunk");

    let st = v.status().expect("status");
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.staged.files.len(), 1);
    assert_eq!(st.staged.files[0].status, FileStatus::Deleted);
    // the fixture handle caches the index; reload to see what apply wrote
    let mut index = fx.repo.index().expect("index");
    index.read(true).expect("reload");
    assert!(index.get_path(Path::new("gone.txt"), 0).is_none());
}

#[test]
fn unstage_hunk_of_staged_new_file_returns_it_to_untracked() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.write("new.txt", "fresh\n");

    let v = vcs(&fx);
    v.stage(Path::new("new.txt")).expect("stage");
    let st = v.status().expect("status");
    assert_eq!(st.staged.files[0].status, FileStatus::Added);
    let id = st.staged.files[0].hunks[0].id.clone();

    v.unstage_hunk(Path::new("new.txt"), &id)
        .expect("unstage hunk");

    let st = v.status().expect("status");
    assert!(st.staged.files.is_empty(), "no phantom staged entry");
    assert!(st.unstaged.files.is_empty());
    assert_eq!(st.untracked.files.len(), 1);
    assert_eq!(st.untracked.files[0].path, "new.txt");
    // the fixture handle caches the index; reload to see what apply wrote
    let mut index = fx.repo.index().expect("index");
    index.read(true).expect("reload");
    assert!(index.get_path(Path::new("new.txt"), 0).is_none());
}

#[test]
fn stage_hunk_with_stale_id_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    fx.write("a.txt", "ONE\n");

    let v = vcs(&fx);
    let stale = diffler_core::model::HunkId("0000000000000000000000000000000000000000".into());
    let err = v.stage_hunk(Path::new("a.txt"), &stale).expect_err("stale");
    assert!(matches!(err, VcsError::Rejected(_)));
}

#[test]
fn discard_restores_modified_file() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    fx.write("a.txt", "CHANGED\n");

    let v = vcs(&fx);
    v.discard(Path::new("a.txt")).expect("discard");

    let content = std::fs::read_to_string(fx.root().join("a.txt")).expect("read");
    assert_eq!(content, "one\n");
    assert!(v.working_tree_diff().expect("diff").files.is_empty());
}

#[test]
fn discard_leaves_file_clean_under_autocrlf() {
    // a Windows user with core.autocrlf=true: checkout smudges LF->CRLF, so the
    // file on disk differs in size from the stored blob. discard must still
    // leave the file reported as clean (matching `git status`), not phantom-dirty.
    let fx = Fixture::new();
    {
        let mut config = fx.repo.config().expect("config");
        config.set_str("core.autocrlf", "true").expect("autocrlf");
        config.set_str("core.eol", "crlf").expect("eol");
    }
    fx.write("a.txt", "one\ntwo\nthree\n");
    fx.commit_all("base");
    fx.write("a.txt", "one\nCHANGED\nthree\n");

    let v = vcs(&fx);
    v.discard(Path::new("a.txt")).expect("discard");

    assert!(
        v.working_tree_diff().expect("diff").files.is_empty(),
        "discard left a phantom modification under autocrlf"
    );
    let status = v.status().expect("status");
    assert_eq!(status.unstaged.files.len(), 0, "phantom unstaged file");
}

#[test]
fn discard_deletes_untracked_file() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    fx.write("junk.txt", "scratch\n");

    let v = vcs(&fx);
    v.discard(Path::new("junk.txt")).expect("discard");
    assert!(!fx.root().join("junk.txt").exists());
}

#[test]
fn discard_of_staged_file_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    fx.write("a.txt", "STAGED\n");

    let v = vcs(&fx);
    v.stage(Path::new("a.txt")).expect("stage");
    let err = v.discard(Path::new("a.txt")).expect_err("rejected");
    assert!(matches!(err, VcsError::Rejected(_)));
    let content = std::fs::read_to_string(fx.root().join("a.txt")).expect("read");
    assert_eq!(content, "STAGED\n");
}

#[test]
fn commit_creates_commit_and_clears_staged() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    fx.write("a.txt", "two\n");

    let v = vcs(&fx);
    v.stage(Path::new("a.txt")).expect("stage");
    let oid = v.commit("change a").expect("commit");
    assert_eq!(oid.len(), 40);

    assert!(v.status().expect("status").staged.files.is_empty());
    let entries = v.log(10).expect("log");
    assert_eq!(entries.len(), 2);
    assert_eq!(entries[0].subject, "change a");
    assert_eq!(entries[0].oid, oid);
}

#[test]
fn empty_commit_message_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");

    let v = vcs(&fx);
    let err = v.commit("  \n").expect_err("rejected");
    assert!(matches!(err, VcsError::Rejected(_)));
}

#[test]
fn amend_rewrites_head_and_folds_in_the_index() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("first");

    let v = vcs(&fx);
    // stage a follow-up change and amend with a new message
    fx.write("b.txt", "two\n");
    v.stage(Path::new("b.txt")).expect("stage");
    let oid = v.amend(Some("first amended"), true).expect("amend");

    let entries = v.log(10).expect("log");
    assert_eq!(entries.len(), 1, "amend replaces HEAD, no new parent");
    assert_eq!(entries[0].subject, "first amended");
    assert_eq!(entries[0].oid, oid);
    // the staged file folded into the amended commit
    assert!(v.status().expect("status").staged.files.is_empty());
}

#[test]
fn extend_reuses_the_head_message() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("keep this message");

    let v = vcs(&fx);
    fx.write("b.txt", "extra\n");
    v.stage(Path::new("b.txt")).expect("stage");
    v.amend(None, true).expect("extend");

    let entries = v.log(10).expect("log");
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].subject, "keep this message", "message reused");
    // b.txt is now part of HEAD: nothing left staged or changed
    assert!(v.working_tree_diff().expect("diff").files.is_empty());
}

#[test]
fn reword_changes_only_the_message_keeping_the_tree() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("old subject");

    let v = vcs(&fx);
    // a staged change must NOT enter a pure reword (use_index = false)
    fx.write("b.txt", "ignored by reword\n");
    v.stage(Path::new("b.txt")).expect("stage");
    v.amend(Some("new subject"), false).expect("reword");

    let entries = v.log(10).expect("log");
    assert_eq!(entries[0].subject, "new subject");
    // the staged change is still staged: reword left the tree alone
    assert!(
        v.status()
            .expect("status")
            .staged
            .files
            .iter()
            .any(|f| f.path == "b.txt"),
        "reword keeps HEAD's tree; the staged change stays staged"
    );
}

#[test]
fn head_message_returns_the_full_subject() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("the subject line\n\nthe body\n");
    let message = vcs(&fx).head_message().expect("head message");
    assert!(message.starts_with("the subject line"));
    assert!(message.contains("the body"));
}

#[test]
fn amend_with_empty_message_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    let err = vcs(&fx).amend(Some("  \n"), false).expect_err("rejected");
    assert!(matches!(err, VcsError::Rejected(_)));
}

#[test]
fn branch_create_checkout_and_delete() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");

    let v = vcs(&fx);
    let original = v.head().expect("head").branch.expect("on a branch");

    v.create_branch("feature", true).expect("create");
    assert_eq!(v.head().expect("head").branch.as_deref(), Some("feature"));

    let err = v.delete_branch("feature").expect_err("current branch");
    assert!(matches!(err, VcsError::Rejected(_)));

    let branches = v.branches().expect("branches");
    let feature = branches
        .iter()
        .find(|b| b.name == "feature")
        .expect("feature listed");
    assert!(feature.is_head);

    v.checkout(&original).expect("checkout");
    assert_eq!(v.head().expect("head").branch, Some(original));
    v.delete_branch("feature").expect("delete");
    assert!(
        !v.branches()
            .expect("branches")
            .iter()
            .any(|b| b.name == "feature")
    );
}

#[test]
fn create_branch_without_checkout_keeps_head() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");

    let v = vcs(&fx);
    let original = v.head().expect("head").branch;
    v.create_branch("idle", false).expect("create");
    assert_eq!(v.head().expect("head").branch, original);
    assert!(
        v.branches()
            .expect("branches")
            .iter()
            .any(|b| b.name == "idle")
    );
}

#[test]
fn network_argv_maps_each_op_to_the_git_cli() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    let v = vcs(&fx);
    assert_eq!(
        v.network_argv(NetworkOp::Fetch).expect("fetch"),
        ["git", "fetch"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::FetchAll).expect("fetch --all"),
        ["git", "fetch", "--all"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::Push).expect("push"),
        ["git", "push"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::PushSetUpstream {
            remote: "origin".into()
        })
        .expect("push -u"),
        ["git", "push", "-u", "origin", "HEAD"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::Pull).expect("pull"),
        ["git", "pull"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::PullFrom {
            remote: "origin".into(),
            branch: "main".into()
        })
        .expect("pull from"),
        ["git", "pull", "origin", "main"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::PullRebase)
            .expect("pull --rebase"),
        ["git", "pull", "--rebase"]
    );
    assert_eq!(
        v.network_argv(NetworkOp::PullMerge)
            .expect("pull --no-rebase"),
        ["git", "pull", "--no-rebase"]
    );
}

#[test]
fn workdir_is_the_repo_working_tree() {
    let fx = Fixture::new();
    fx.write("a.txt", "x\n");
    fx.commit_all("base");
    let dir = vcs(&fx).workdir().expect("workdir");
    assert_eq!(
        dir.canonicalize().expect("canonicalize"),
        fx.root().canonicalize().expect("canonicalize")
    );
}

// amend on an unborn HEAD (zero commits) must return a clean error; the app
// guards this at the UI layer, but the trait method must not panic
#[test]
fn amend_on_unborn_head_returns_error_not_panic() {
    let fx = Fixture::new();
    // no commits: HEAD is unborn
    let err = vcs(&fx)
        .amend(Some("anything"), false)
        .expect_err("amend on unborn HEAD must fail");
    // must be a VcsError (not a panic); the exact variant (Git or Rejected) is
    // an implementation detail but it must not be a NoWorkdir
    assert!(
        !matches!(err, VcsError::NoWorkdir),
        "unborn HEAD is not a missing workdir: {err}"
    );
}

#[test]
fn stash_push_clears_the_worktree_and_pop_restores_it() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\ntwo\nthree\n");
    fx.commit_all("init");
    fx.write("a.txt", "one\nTWO\nthree\n");
    let v = vcs(&fx);

    v.stash_push(None).expect("stash");
    assert!(
        v.working_tree_diff().expect("diff").files.is_empty(),
        "worktree matches HEAD after stashing"
    );

    v.stash_pop().expect("pop");
    let model = v.working_tree_diff().expect("diff");
    assert_eq!(model.files.len(), 1, "the change comes back");
    assert_eq!(model.files[0].path, "a.txt");
}

#[test]
fn stash_push_on_a_clean_tree_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("init");
    let err = vcs(&fx)
        .stash_push(None)
        .expect_err("nothing to stash on a clean tree");
    assert!(matches!(err, VcsError::Rejected(_)), "got {err:?}");
}

#[test]
fn stash_push_ignores_untracked_files() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("init");
    fx.write("untracked.txt", "new\n");
    let err = vcs(&fx)
        .stash_push(None)
        .expect_err("untracked-only is nothing to stash");
    assert!(matches!(err, VcsError::Rejected(_)), "got {err:?}");
}

#[test]
fn unpushed_is_none_without_a_remote_tracking_ref() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("init");
    assert!(vcs(&fx).unpushed(10).expect("unpushed").is_none());
}

#[test]
fn unpushed_stops_at_the_limit() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("init");
    fx.branch("elsewhere");
    fx.track("elsewhere", "HEAD");
    for n in 0..3 {
        fx.write("a.txt", &format!("line {n}\n"));
        fx.commit_all(&format!("commit {n}"));
    }
    let all = vcs(&fx)
        .unpushed(10)
        .expect("unpushed")
        .expect("has remote");
    assert_eq!(all.len(), 3, "everything past the remote ref: {all:?}");
    let capped = vcs(&fx).unpushed(2).expect("unpushed").expect("has remote");
    assert_eq!(capped.len(), 2);
    assert_eq!(capped[0].subject, "commit 2", "newest first");
}

#[test]
fn stash_pop_with_no_stash_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("init");
    let err = vcs(&fx).stash_pop().expect_err("no stash to pop");
    assert!(matches!(err, VcsError::Rejected(_)), "got {err:?}");
}

#[test]
fn stash_pop_that_conflicts_is_rejected() {
    let fx = Fixture::new();
    fx.write("a.txt", "base\n");
    fx.commit_all("init");
    fx.write("a.txt", "stashed change\n");
    let v = vcs(&fx);
    v.stash_push(None).expect("stash");
    // an incompatible edit to the same line the stash also changed
    fx.write("a.txt", "conflicting change\n");
    let err = v.stash_pop().expect_err("conflicting pop");
    assert!(matches!(err, VcsError::Rejected(_)), "got {err:?}");
}

#[test]
fn blame_attributes_each_line_to_the_commit_that_wrote_it() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\ntwo\n");
    fx.commit_all_at("first", 1_000);
    fx.write("a.txt", "one\ntwo\nthree\n");
    fx.commit_all_at("second", 2_000);

    let spans = vcs(&fx).blame(Path::new("a.txt")).expect("blame");
    let by_line: Vec<(u32, &str, i64)> = spans
        .iter()
        .map(|s| (s.start_line, s.summary.as_str(), s.time_unix))
        .collect();
    assert_eq!(
        by_line,
        vec![(1, "first", 1_000), (3, "second", 2_000)],
        "the untouched first two lines stay with the first commit"
    );
    assert!(spans.iter().all(|s| s.committed && s.oid7.len() == 7));
}

#[test]
fn blame_maps_onto_the_worktree_so_uncommitted_lines_are_their_own_span() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\ntwo\n");
    fx.commit_all("base");
    fx.write("a.txt", "inserted\none\ntwo\n");

    let spans = vcs(&fx).blame(Path::new("a.txt")).expect("blame");
    let first = spans.first().expect("a span");
    assert_eq!((first.start_line, first.line_count), (1, 1));
    assert!(!first.committed, "the new top line belongs to no commit");
    assert_eq!(
        spans.get(1).map(|s| (s.start_line, s.committed)),
        Some((2, true)),
        "the committed lines shift down instead of staying at line 1"
    );
}

#[test]
fn gitattributes_declare_a_files_bucket() {
    let fx = Fixture::new();
    fx.write(
        ".gitattributes",
        "src/schema.rs linguist-generated=true\nnotes/** linguist-documentation\nlib/** linguist-vendored=true\n",
    );
    fx.write("src/schema.rs", "x\n");
    fx.write("src/lib.rs", "y\n");
    fx.write("lib/dep.rs", "z\n");
    fx.write("notes/plan.rs", "w\n");
    fx.commit_all("base");

    let vcs = vcs(&fx);
    let declared = |path: &str| {
        let rel = Path::new(path).to_path_buf();
        diffler_core::classify::declared(|name| vcs.attr(&rel, name))
    };
    assert_eq!(declared("src/schema.rs"), Some(Kind::Generated));
    assert_eq!(declared("lib/dep.rs"), Some(Kind::Generated));
    assert_eq!(declared("notes/plan.rs"), Some(Kind::Docs));
    assert_eq!(
        declared("src/lib.rs"),
        None,
        "a file the repo says nothing about is left to the table"
    );
}

#[test]
fn tracked_files_lists_the_index_not_the_worktree() {
    let fx = Fixture::new();
    fx.write("src/a.txt", "x\n");
    fx.write("b.txt", "y\n");
    fx.commit_all("base");
    fx.write("untracked.txt", "z\n");
    fx.write("staged.txt", "w\n");
    fx.stage("staged.txt");

    let files = vcs(&fx).tracked_files().expect("tracked");
    let names: Vec<String> = files
        .iter()
        .map(|p| p.to_string_lossy().replace('\\', "/"))
        .collect();
    assert_eq!(names, vec!["b.txt", "src/a.txt", "staged.txt"]);
}

#[test]
fn read_at_returns_the_files_content_in_that_commits_tree() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    let oid = head_oid(&fx);
    fx.write("a.txt", "changed\n");

    let content = vcs(&fx).read_at(&oid, "a.txt").expect("read_at");
    assert_eq!(
        content.as_deref(),
        Some("one\n"),
        "the commit's own tree, not the edited worktree"
    );
}

#[test]
fn read_at_is_none_for_a_path_the_commit_never_had() {
    let fx = Fixture::new();
    fx.write("a.txt", "one\n");
    fx.commit_all("base");
    let oid = head_oid(&fx);

    let content = vcs(&fx).read_at(&oid, "missing.txt").expect("read_at");
    assert_eq!(content, None);
}

mod diff_algorithm {
    use std::fmt::Write as _;
    use std::path::Path;

    use diffler_core::diffalgo::{DiffAlgorithm, DiffSettings};
    use diffler_core::git::GitVcs;
    use diffler_core::model::LineKind;
    use diffler_core::vcs::Vcs;

    use super::Fixture;

    // helper fns run outside #[test] fns, where clippy's test allowances don't reach
    #[allow(clippy::expect_used)]
    fn open(fx: &Fixture, algorithm: DiffAlgorithm) -> GitVcs {
        GitVcs::open_with_settings(
            fx.root(),
            &DiffSettings {
                algorithm,
                ..DiffSettings::default()
            },
        )
        .expect("open")
    }

    /// Myers and patience disagree on how to align a unique line that moved
    /// past a run of repeated, non-unique ones: patience's own strength.
    #[test]
    fn patience_and_myers_disagree_on_a_classic_case() {
        let fx = Fixture::new();
        fx.write(
            "a.txt",
            "begin\nrepeat\nrepeat\nunique_anchor\nrepeat\nrepeat\nend\n",
        );
        fx.commit_all("base");
        fx.write(
            "a.txt",
            "begin\nunique_anchor\nrepeat\nrepeat\nrepeat\nrepeat\nend\n",
        );

        let hunks = |algorithm| -> Vec<(LineKind, String)> {
            open(&fx, algorithm)
                .working_tree_diff()
                .expect("diff")
                .files[0]
                .hunks
                .iter()
                .flat_map(|h| &h.lines)
                .map(|l| (l.kind, l.text.clone()))
                .collect()
        };
        let myers = hunks(DiffAlgorithm::Myers);
        let patience = hunks(DiffAlgorithm::Patience);
        assert_ne!(
            myers, patience,
            "patience aligns on unique lines differently than myers"
        );
    }

    /// Histogram has no git2 flag at all; it must still produce a correct
    /// line diff (not just "different from myers").
    #[test]
    fn histogram_finds_the_single_changed_line() {
        let fx = Fixture::new();
        let mut base = String::new();
        for i in 1..=10 {
            writeln!(base, "line {i}").expect("write");
        }
        fx.write("a.txt", &base);
        fx.commit_all("base");
        fx.write("a.txt", &base.replace("line 5\n", "LINE FIVE\n"));

        let model = open(&fx, DiffAlgorithm::Histogram)
            .working_tree_diff()
            .expect("diff");
        let lines = &model.files[0].hunks[0].lines;
        let deleted: Vec<&str> = lines
            .iter()
            .filter(|l| l.kind == LineKind::Deleted)
            .map(|l| l.text.as_str())
            .collect();
        let added: Vec<&str> = lines
            .iter()
            .filter(|l| l.kind == LineKind::Added)
            .map(|l| l.text.as_str())
            .collect();
        assert_eq!(deleted, vec!["line 5"]);
        assert_eq!(added, vec!["LINE FIVE"]);
    }

    /// Every algorithm stages exactly the hunk shown and nothing else, then
    /// reverses cleanly on unstage: hunk ids are computed from the same
    /// algorithm that produced them, so the id the reviewer picked is always
    /// findable regardless of which one is active.
    #[test]
    fn staging_stays_correct_under_every_algorithm() {
        for algorithm in DiffAlgorithm::ALL {
            let fx = Fixture::new();
            let mut base = String::new();
            for i in 1..=40 {
                writeln!(base, "line {i}").expect("write");
            }
            fx.write("a.txt", &base);
            fx.commit_all("base");
            let edited = base
                .replace("line 5\n", "LINE FIVE\n")
                .replace("line 35\n", "LINE THIRTY-FIVE\n");
            fx.write("a.txt", &edited);

            let v = open(&fx, algorithm);
            let st = v.status().expect("status");
            assert_eq!(
                st.unstaged.files[0].hunks.len(),
                2,
                "{algorithm}: two separate hunks"
            );
            let first = st.unstaged.files[0].hunks[0].id.clone();

            v.stage_hunk(Path::new("a.txt"), &first)
                .unwrap_or_else(|err| panic!("{algorithm}: stage hunk: {err}"));
            let st = v.status().expect("status");
            assert_eq!(st.staged.files.len(), 1, "{algorithm}: one file staged");
            assert_eq!(
                st.staged.files[0].hunks.len(),
                1,
                "{algorithm}: only the picked hunk staged"
            );
            let staged_text = st.staged.files[0].new_text.as_deref().expect("text");
            assert!(
                staged_text.contains("LINE FIVE"),
                "{algorithm}: the staged hunk landed"
            );
            assert!(
                !staged_text.contains("LINE THIRTY-FIVE"),
                "{algorithm}: the other hunk stayed unstaged"
            );

            v.unstage_hunk(Path::new("a.txt"), &first)
                .unwrap_or_else(|err| panic!("{algorithm}: unstage hunk: {err}"));
            let st = v.status().expect("status");
            assert!(
                st.staged.files.is_empty(),
                "{algorithm}: unstage reverses cleanly"
            );
            assert_eq!(st.unstaged.files[0].hunks.len(), 2, "{algorithm}");
        }
    }

    /// Stage hunk `pick` of `old` -> `new` alone and return the staged text,
    /// after checking that unstaging the staged hunk empties the index again.
    #[allow(clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
    fn stage_alone(old: &str, new: &str, algorithm: DiffAlgorithm, pick: usize) -> String {
        let fx = Fixture::new();
        fx.write("a.txt", old);
        fx.commit_all("base");
        fx.write("a.txt", new);
        let v = open(&fx, algorithm);
        let picked = v.status().expect("status").unstaged.files[0].hunks[pick]
            .id
            .clone();
        v.stage_hunk(Path::new("a.txt"), &picked)
            .unwrap_or_else(|err| panic!("{algorithm}: stage hunk: {err}"));
        let st = v.status().expect("status");
        let staged = st.staged.files[0].new_text.clone().expect("text");
        let back = st.staged.files[0].hunks[0].id.clone();
        v.unstage_hunk(Path::new("a.txt"), &back)
            .unwrap_or_else(|err| panic!("{algorithm}: unstage hunk: {err}"));
        assert!(
            v.status().expect("status").staged.files.is_empty(),
            "{algorithm}: unstage restores the index"
        );
        staged
    }

    /// We send the picked hunk without the ones above it, and a periodic
    /// file matches its lines at a shifted offset too, so a hunk placed by
    /// its own `+` start would land two lines early without complaint.
    #[test]
    fn a_later_hunk_staged_alone_lands_where_it_is_shown() {
        let pairs = "a\nb\n".repeat(15);
        let old = format!("t1\nt2\n{pairs}");
        let mut new = pairs;
        new.replace_range(20..21, "A");
        for algorithm in DiffAlgorithm::ALL {
            assert_eq!(
                stage_alone(&old, &new, algorithm, 1),
                format!("t1\nt2\n{new}"),
                "{algorithm}"
            );
        }
    }

    #[test]
    fn staging_keeps_line_endings_byte_for_byte_under_every_algorithm() {
        let cases = [
            ("a\r\nb\r\nc\r\n", "a\r\nB\r\nc\r\n"),
            ("a\r\nb\nc\r\n", "a\r\nB\nc\r\n"),
            ("a\nb\nc", "a\nb\nC"),
            ("a\nb\nc", "a\nb\nc\n"),
            ("a\nb\nc\n", "a\nb\nc"),
        ];
        for algorithm in DiffAlgorithm::ALL {
            for (old, new) in cases {
                assert_eq!(stage_alone(old, new, algorithm, 0), new, "{algorithm}");
            }
        }
    }

    /// Histogram reads the worktree file raw, while git compares it through
    /// its clean filter; autocrlf keeps git's own hunks and an LF index.
    #[test]
    fn histogram_keeps_gits_hunks_under_autocrlf() {
        let fx = Fixture::new();
        fx.repo
            .config()
            .expect("config")
            .set_str("core.autocrlf", "true")
            .expect("autocrlf");
        fx.write("a.txt", "a\r\nb\r\nc\r\nd\r\n");
        fx.commit_all("base");
        fx.write("a.txt", "a\r\nB\r\nc\r\nd\r\n");

        let v = open(&fx, DiffAlgorithm::Histogram);
        let hunks = &v.status().expect("status").unstaged.files[0].hunks;
        let changed: Vec<_> = hunks[0]
            .lines
            .iter()
            .filter(|l| l.kind != LineKind::Context)
            .map(|l| l.text.as_str())
            .collect();
        assert_eq!(changed, ["b", "B"]);
        v.stage_hunk(Path::new("a.txt"), &hunks[0].id)
            .expect("stage hunk");
        let st = v.status().expect("status");
        assert_eq!(st.staged.files[0].new_text.as_deref(), Some("a\nB\nc\nd\n"));
    }

    #[test]
    fn worktree_hunks_come_from_histogram_where_it_disagrees_with_myers() {
        let old = "begin\nrepeat\nrepeat\nunique_anchor\nrepeat\nrepeat\nend\n";
        let new = "begin\nunique_anchor\nrepeat\nrepeat\nrepeat\nrepeat\nend\n";
        let fx = Fixture::new();
        fx.write("a.txt", old);
        fx.commit_all("base");
        fx.write("a.txt", new);
        let unstaged = |algorithm| {
            open(&fx, algorithm)
                .status()
                .expect("status")
                .unstaged
                .files[0]
                .hunks
                .clone()
        };
        let histogram = unstaged(DiffAlgorithm::Histogram);
        assert_eq!(
            histogram,
            diffler_core::diffalgo::histogram_hunks(old, new, "a.txt", 3, true)
        );
        assert_ne!(histogram, unstaged(DiffAlgorithm::Myers));
    }
}