patchcov 0.4.1

Patch coverage for git diffs: attribute lcov, llvm-cov, Cobertura, Go and JaCoCo reports to a diff and gate on it.
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
//! Rendering of a [`CoverageDiff`] to markdown, YAML, or JSON.
//!
//! The markdown renderer produces the PR comment: a `## Coverage` header, the
//! total line with 🟢/🔴 direction, the merge-base→head `Comparing` line, the
//! EPS-filtered per-file before/after/Δ table and the artifact footer, plus a
//! `### Patch coverage` section (the headline metric an aggregate comment could
//! never show) and an indirect-changes section. CI renders it via
//! `patchcov diff --output markdown`.

use anyhow::Result;
use serde::Serialize;

use super::analysis::CoverageDiff;
use crate::yaml::to_yaml;

/// The `explanation` block of structured output: what each field means and
/// whether it is populated in this serialization, so a reader (or an AI agent)
/// of one YAML or JSON document needs no other reference.
#[derive(Debug, Clone, Serialize)]
struct FieldExplanation {
    /// Descriptive text explaining the overall structure.
    text: String,
    /// Documentation for individual fields in the output.
    fields: Vec<FieldDocumentation>,
}

/// One entry of [`FieldExplanation::fields`].
#[derive(Debug, Clone, Serialize)]
struct FieldDocumentation {
    /// Path of the documented field, e.g. `patch_coverage.files[].path`.
    name: String,
    /// What the field contains.
    text: String,
    /// A command that produces the underlying data, when there is one.
    #[serde(skip_serializing_if = "Option::is_none")]
    command: Option<String>,
    /// Whether the field is present in the current output.
    present: bool,
}

/// Minimum per-file change (percentage points) for a row to be listed, matching
/// the original coverage comment (suppresses floating-point noise).
const EPS: f64 = 0.05;

/// Output serialisation for `patchcov diff`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Markdown PR comment (default).
    Markdown,
    /// YAML following the project's structured-output conventions.
    Yaml,
    /// JSON for programmatic use.
    Json,
}

/// Decoration inputs and options for rendering.
#[derive(Debug, Clone, Default)]
pub struct RenderOptions {
    /// Omit the explanation block from JSON/YAML output (default: false).
    pub no_explanation: bool,
    /// Link to the full coverage-summary artifact.
    pub artifact_url: Option<String>,
    /// Link to the CI run, rendered independently of the artifact URL.
    pub run_url: Option<String>,
    /// Base (merge-base) commit SHA.
    pub base_sha: Option<String>,
    /// Head commit SHA.
    pub head_sha: Option<String>,
    /// Commit-URL prefix for linking SHAs (e.g. `https://…/<repo>/commit`).
    pub commit_url: Option<String>,
    /// Collapse consecutive uncovered new lines into ranges (e.g. `9-11`).
    pub collapse_ranges: bool,
}

/// Renders `diff` in the requested `format`.
pub fn render(diff: &CoverageDiff, opts: &RenderOptions, format: OutputFormat) -> Result<String> {
    match format {
        OutputFormat::Markdown => Ok(render_markdown(diff, opts)),
        OutputFormat::Yaml => {
            let mut view = CoverageDiffView::build(diff, opts);
            view.update_field_presence();
            to_yaml(&view)
        }
        OutputFormat::Json => {
            let mut view = CoverageDiffView::build(diff, opts);
            view.update_field_presence();
            Ok(serde_json::to_string_pretty(&view)?)
        }
    }
}

// ---------------------------------------------------------------------------
// Number formatting (mirrors the jq `rnd`/`pct` helpers of the original comment)
// ---------------------------------------------------------------------------

/// Rounds to two decimal places, normalising negative zero to `0.0`.
fn round2(x: f64) -> f64 {
    let r = (x * 100.0).round() / 100.0;
    if r == 0.0 {
        0.0
    } else {
        r
    }
}

/// Formats a number with up to two decimals, trailing zeros trimmed (`100`, `65.4`).
fn fmt_num(x: f64) -> String {
    let s = format!("{:.2}", round2(x));
    s.trim_end_matches('0').trim_end_matches('.').to_string()
}

/// Formats an optional percentage; `None` renders as an em dash.
pub(crate) fn pct(x: Option<f64>) -> String {
    match x {
        Some(v) => format!("{}%", fmt_num(v)),
        None => "—".to_string(),
    }
}

/// Direction emoji for a percentage-point delta.
///
/// The direction is taken from the *displayed* (rounded) value, not the raw
/// one: every caller prints [`fmt_num`] beside this emoji, and `fmt_num` rounds
/// through [`round2`]. Deriving the arrow from the raw delta let a move in
/// `(-0.005, 0)` render as a red arrow next to `0 pp` — an alarm colour beside a
/// number that says nothing moved.
fn arrow(d: f64) -> &'static str {
    let d = round2(d);
    if d > 0.0 {
        "🟢"
    } else if d < 0.0 {
        "🔴"
    } else {
        "⚪"
    }
}

/// Direction emoji for the *headline* total delta.
///
/// The per-file sections have suppressed cross-run measurement variance since
/// the first release — delta-table rows need `|d| >= EPS`, and an untouched file needs a net
/// move of `NOTABLE_UNCHANGED_LINES` covered lines — but the headline had no
/// equivalent gate, so every flip those sections hid still accumulated here and
/// was painted red. Applying the same `EPS` tolerance keeps the comment
/// internally consistent: a sub-tolerance total move is neutral, while the
/// number itself is still printed truthfully beside it.
fn headline_arrow(d: f64) -> &'static str {
    if d.abs() < EPS {
        "⚪"
    } else {
        arrow(d)
    }
}

/// Annotates the headline when the total moved but no per-file section can
/// account for it — the move is then, by construction, not attributable to this
/// diff. Without this a reader sees a total delta above a comment whose every
/// other section says nothing changed.
fn unattributed_note(diff: &CoverageDiff, d: f64) -> &'static str {
    let moved = round2(d) != 0.0;
    let explained = diff
        .file_deltas
        .iter()
        .any(|fd| fd.delta().is_none_or(|d| d.abs() >= EPS))
        || !diff.notable_unchanged.is_empty();
    if moved && !explained {
        " _(not attributable to this diff)_"
    } else {
        ""
    }
}

/// Renders a commit ref as a short, optionally-linked SHA.
fn sha_ref(sha: &str, commit_url: Option<&str>) -> String {
    let short: String = sha.chars().take(7).collect();
    match commit_url {
        Some(url) if !url.is_empty() => format!("[`{short}`]({url}/{sha})"),
        _ => format!("`{short}`"),
    }
}

/// Collapses a sorted, de-duplicated line list into `5, 9-11` style ranges.
fn collapse_ranges(lines: &[u32]) -> String {
    let mut parts = Vec::new();
    let mut i = 0;
    while i < lines.len() {
        let start = lines[i];
        let mut end = start;
        while i + 1 < lines.len() && lines[i + 1] == end + 1 {
            end += 1;
            i += 1;
        }
        if start == end {
            parts.push(start.to_string());
        } else {
            parts.push(format!("{start}-{end}"));
        }
        i += 1;
    }
    parts.join(", ")
}

// ---------------------------------------------------------------------------
// Markdown
// ---------------------------------------------------------------------------

fn render_markdown(diff: &CoverageDiff, opts: &RenderOptions) -> String {
    let mut out = String::new();
    out.push_str("## Coverage\n\n");

    // Total line.
    if diff.has_baseline {
        match (diff.total_after, diff.total_before) {
            (after, Some(before)) => {
                // The percentage displayed is always the real measured value;
                // the movement is computed from the `tolerate`-masked one, so a
                // silenced flip cannot move the arrow or the number beside it.
                let effective = diff.total_after_effective.or(after);
                let d = effective.unwrap_or(0.0) - before;
                out.push_str(&format!(
                    "Total: **{}** {} {} pp vs `main`{}\n\n",
                    pct(after),
                    headline_arrow(d),
                    fmt_num(d),
                    unattributed_note(diff, d)
                ));
            }
            (after, None) => {
                out.push_str(&format!("Total: **{}**\n\n", pct(after)));
            }
        }
    } else {
        out.push_str(&format!("Total: **{}**\n\n", pct(diff.total_after)));
    }

    // Comparing line.
    if let (Some(base), Some(head)) = (opts.base_sha.as_deref(), opts.head_sha.as_deref()) {
        if !base.is_empty() && !head.is_empty() {
            out.push_str(&format!(
                "Comparing {}..{} _(merge-base → PR head)_\n\n",
                sha_ref(base, opts.commit_url.as_deref()),
                sha_ref(head, opts.commit_url.as_deref())
            ));
        }
    }

    if diff.has_baseline {
        render_delta_table(diff, &mut out);
        render_notable_unchanged(diff, &mut out);
    } else {
        out.push_str(
            "_No baseline report supplied. Per-file deltas and indirect coverage changes \
             require a baseline report._\n\n",
        );
    }
    // Also without a baseline: `ignore` still shapes the total and the patch.
    render_markers(diff, &mut out);
    render_excluded(diff, &mut out);
    if !diff.unmeasured_files.is_empty() {
        out.push_str(&format!("<details>\n<summary>Touched files absent from every coverage report ({})</summary>\n\n", diff.unmeasured_files.len()));
        for path in &diff.unmeasured_files {
            out.push_str(&format!("- `{path}`\n"));
        }
        out.push_str("\nThese files may contain no executable code or may have been omitted from the coverage run.\n\n</details>\n\n");
    }

    render_patch_section(diff, opts, &mut out);

    if diff.has_baseline && !diff.indirect.is_empty() {
        render_indirect_section(diff, &mut out);
    }

    render_footer(opts, &mut out);
    out
}

fn render_delta_table(diff: &CoverageDiff, out: &mut String) {
    // Build rows as the original comment did: new files, or |delta| >= EPS.
    struct Row {
        path: String,
        before: Option<f64>,
        after: Option<f64>,
        delta: Option<f64>,
    }
    let mut rows: Vec<Row> = diff
        .file_deltas
        .iter()
        .map(|fd| {
            // `delta()` reads the `tolerate`-masked coverage, so a silenced flip
            // does not produce a row; `after` stays the real displayed value.
            let delta = fd.delta();
            Row {
                path: fd.path.clone(),
                before: fd.before,
                after: fd.after,
                delta,
            }
        })
        .filter(|r| r.delta.is_none_or(|d| d.abs() >= EPS))
        .collect();
    // New files (no delta) sort to the top, then largest decreases first.
    rows.sort_by(|a, b| {
        a.delta
            .unwrap_or(-1e9)
            .partial_cmp(&b.delta.unwrap_or(-1e9))
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    if rows.is_empty() {
        out.push_str("_No per-file coverage changes vs `main`._\n\n");
        return;
    }

    out.push_str("| File | Before | After | Δ |\n");
    out.push_str("|------|-------:|------:|---|\n");
    for r in rows {
        let change = match r.delta {
            None => "🆕 new".to_string(),
            Some(d) => format!("{} {} pp", arrow(d), fmt_num(d)),
        };
        out.push_str(&format!(
            "| `{}` | {} | {} | {} |\n",
            r.path,
            pct(r.before),
            pct(r.after),
            change
        ));
    }
    out.push('\n');
}

/// Renders the magnitude-gated note for unchanged files whose coverage moved
/// substantially — flagged as *not* attributable to the PR (measurement variance
/// or a cross-file effect like a removed test), kept collapsed so it does not
/// crowd out the actionable sections.
fn render_notable_unchanged(diff: &CoverageDiff, out: &mut String) {
    if diff.notable_unchanged.is_empty() {
        return;
    }
    out.push_str(&format!(
        "<details><summary>ℹ️ {} unchanged file(s) also moved (not attributed to this PR)</summary>\n\n",
        diff.notable_unchanged.len()
    ));
    out.push_str(
        "These files were not modified by this diff; the shift is either measurement variance \
         between the two runs or a cross-file effect (e.g. a removed test).\n\n",
    );
    out.push_str("| File | Before | After | Δ |\n");
    out.push_str("|------|-------:|------:|---|\n");
    for fd in &diff.notable_unchanged {
        let change = match fd.delta() {
            None => "🆕 new".to_string(),
            Some(d) => format!("{} {} pp", arrow(d), fmt_num(d)),
        };
        out.push_str(&format!(
            "| `{}` | {} | {} | {} |\n",
            fd.path,
            pct(fd.before),
            pct(fd.after),
            change
        ));
    }
    out.push_str("\n</details>\n\n");
}

/// Renders the collapsed note listing every source-marker region that applied.
///
/// Silencing is never invisible: a reviewer can always see which regions were
/// ignored or tolerated, where they are, and why their author silenced them.
fn render_markers(diff: &CoverageDiff, out: &mut String) {
    if diff.markers.is_empty() {
        return;
    }
    let count = |kind: crate::MarkerKind| diff.markers.iter().filter(|m| m.kind == kind).count();
    out.push_str(&format!(
        "<details><summary>🔇 {} ignored region(s), {} tolerated region(s)</summary>\n\n",
        count(crate::MarkerKind::Ignore),
        count(crate::MarkerKind::Tolerate)
    ));
    out.push_str(
        "`ignore` removes the lines from both reports; `tolerate` keeps them in the reported \
         percentage but scores them against the baseline, so a cross-run flip cannot move a \
         delta. Regions are read from each revision's own source.\n\n",
    );
    out.push_str("| File | Kind | Lines | Rev | Reason |\n");
    out.push_str("|------|------|-------|-----|--------|\n");
    for marker in &diff.markers {
        let lines = if marker.start == marker.end {
            marker.start.to_string()
        } else {
            format!("{}-{}", marker.start, marker.end)
        };
        out.push_str(&format!(
            "| `{}` | `{}` | {} | {} | {} |\n",
            marker.path,
            marker.kind.as_str(),
            lines,
            marker.side.as_str(),
            marker.reason
        ));
    }
    out.push_str("\n</details>\n\n");
}

/// Maximum touched paths listed in the markdown note; the rest are counted.
const EXCLUDED_LISTED: usize = 20;

/// `1 file` / `3 files`.
fn files_noun(n: usize) -> String {
    format!("{n} file{}", if n == 1 { "" } else { "s" })
}

/// Renders the note saying what `--ignore-filename-regex` removed.
///
/// The filter leaves no trace in the numbers, so without this a pattern wider
/// than intended cannot be told from a correct one by reading the comment. Only
/// the paths the diff touched are listed — the full set is in the structured
/// output, and is as long as the pattern is broad.
fn render_excluded(diff: &CoverageDiff, out: &mut String) {
    let excluded = &diff.excluded;
    if excluded.is_empty() {
        return;
    }
    let touched = match (excluded.touched_count(), excluded.new_executable_lines()) {
        (0, _) => "none of them touched by this diff".to_string(),
        (n, 0) => format!("{n} of them touched by this diff"),
        // A mixed diff still shows a patch percentage, so say how many of its
        // lines the filter took out of that denominator.
        (n, lines) => format!(
            "{n} of them touched by this diff, adding {lines} executable line{}",
            if lines == 1 { "" } else { "s" }
        ),
    };
    out.push_str(&format!(
        "_Excluded by ignore-filename-regex: {} ({touched})._\n\n",
        files_noun(excluded.count())
    ));
    if excluded.touched_count() == 0 {
        return;
    }
    out.push_str(&format!(
        "<details><summary>Excluded files touched by this diff ({})</summary>\n\n",
        excluded.touched_count()
    ));
    for path in excluded.touched().take(EXCLUDED_LISTED) {
        out.push_str(&format!("- `{path}`\n"));
    }
    if excluded.touched_count() > EXCLUDED_LISTED {
        out.push_str(&format!(
            "- _…and {} more_\n",
            excluded.touched_count() - EXCLUDED_LISTED
        ));
    }
    out.push_str("\n</details>\n\n");
}

fn render_patch_section(diff: &CoverageDiff, opts: &RenderOptions, out: &mut String) {
    out.push_str("### Patch coverage\n\n");

    if diff.patch.total() == 0 {
        // An empty patch is two different facts: the diff added no code, or all
        // of it sits in files the filter removed. Say which.
        match diff.excluded.new_executable_lines() {
            0 => out.push_str("_No new executable lines added by this diff._\n\n"),
            n => out.push_str(&format!(
                "_No new executable lines in the files measured: {n} new executable line{} \
                 {} in files excluded by ignore-filename-regex._\n\n",
                if n == 1 { "" } else { "s" },
                if n == 1 { "is" } else { "are" },
            )),
        }
        return;
    }

    out.push_str(&format!(
        "Patch: **{}** ({}/{} new lines covered)\n\n",
        pct(diff.patch.percent()),
        diff.patch.covered,
        diff.patch.total()
    ));

    if !diff.file_patches.is_empty() {
        out.push_str("| File | Patch | Uncovered new lines |\n");
        out.push_str("|------|------:|---------------------|\n");
        for fp in &diff.file_patches {
            let uncovered = if fp.uncovered_lines.is_empty() {
                "—".to_string()
            } else if opts.collapse_ranges {
                collapse_ranges(&fp.uncovered_lines)
            } else {
                fp.uncovered_lines
                    .iter()
                    .map(u32::to_string)
                    .collect::<Vec<_>>()
                    .join(", ")
            };
            out.push_str(&format!(
                "| `{}` | {} ({}/{}) | {} |\n",
                fp.path,
                pct(fp.patch.percent()),
                fp.patch.covered,
                fp.patch.total(),
                uncovered
            ));
        }
        out.push('\n');
    }

    if !diff.uncovered_new_lines.is_empty() {
        out.push_str(&format!(
            "<details><summary>Uncovered new lines ({})</summary>\n\n",
            diff.uncovered_new_lines.len()
        ));
        for (path, line) in &diff.uncovered_new_lines {
            out.push_str(&format!("- `{path}:{line}`\n"));
        }
        out.push_str("\n</details>\n\n");
    }
}

fn render_indirect_section(diff: &CoverageDiff, out: &mut String) {
    out.push_str("### Indirect coverage changes\n\n");
    out.push_str(&format!(
        "🔴 {} lines lost coverage, 🟢 {} lines gained coverage on unchanged code.\n\n",
        diff.indirect_newly_uncovered(),
        diff.indirect_newly_covered()
    ));
    out.push_str("<details><summary>Indirect changes</summary>\n\n");
    for change in &diff.indirect {
        let transition = if change.became_covered {
            "🟢 uncovered → covered"
        } else {
            "🔴 covered → uncovered"
        };
        out.push_str(&format!(
            "- `{}:{}` {}\n",
            change.path, change.head_line, transition
        ));
    }
    out.push_str("\n</details>\n\n");
}

fn render_footer(opts: &RenderOptions, out: &mut String) {
    let artifact = opts.artifact_url.as_deref().filter(|u| !u.is_empty());
    let run = opts.run_url.as_deref().filter(|u| !u.is_empty());
    if artifact.is_none() && run.is_none() {
        return;
    }
    out.push_str("<sub>");
    if let Some(artifact) = artifact {
        out.push_str(&format!("📦 [Full per-file coverage summary]({artifact})"));
    }
    if let Some(run) = run {
        if artifact.is_some() {
            out.push_str(" · ");
        }
        out.push_str(&format!("[run summary]({run})"));
    }
    out.push_str("</sub>\n");
}

// ---------------------------------------------------------------------------
// Structured (YAML / JSON) view
// ---------------------------------------------------------------------------

/// Serializable view of a [`CoverageDiff`] for YAML/JSON output, carrying the
/// field-presence explanation block the project uses for structured output.
#[derive(Debug, Clone, Serialize)]
struct CoverageDiffView {
    #[serde(skip_serializing_if = "Option::is_none")]
    explanation: Option<FieldExplanation>,
    patch_coverage: PatchView,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    uncovered_new_lines: Vec<String>,
    unmeasured_files: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    project_delta: Option<ProjectDeltaView>,
    #[serde(skip_serializing_if = "Option::is_none")]
    indirect_changes: Option<IndirectView>,
    /// Source-marker regions that applied. Empty when no marker was found.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    markers: Vec<MarkerView>,
    /// Files `--ignore-filename-regex` removed. Absent when it removed nothing.
    #[serde(skip_serializing_if = "Option::is_none")]
    excluded_files: Option<ExcludedFilesView>,
}

#[derive(Debug, Clone, Serialize)]
struct ExcludedFilesView {
    count: usize,
    touched_count: usize,
    /// Executable lines the diff added to excluded files: patch lines the filter
    /// took out of the denominator.
    new_executable_lines: u64,
    paths: Vec<String>,
    /// The subset of `paths` this diff touched.
    touched: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
struct MarkerView {
    path: String,
    kind: String,
    /// Which revision the region was observed on: `both`, `head`, or `base`.
    side: String,
    start: u32,
    end: u32,
    reason: String,
}

#[derive(Debug, Clone, Serialize)]
struct PatchView {
    percent: Option<f64>,
    covered: u64,
    total: u64,
    files: Vec<FilePatchView>,
}

#[derive(Debug, Clone, Serialize)]
struct FilePatchView {
    path: String,
    percent: Option<f64>,
    covered: u64,
    total: u64,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    uncovered_lines: Vec<u32>,
}

#[derive(Debug, Clone, Serialize)]
struct ProjectDeltaView {
    total_before: Option<f64>,
    /// The real, measured head coverage.
    total_after: Option<f64>,
    /// Head coverage with `tolerate` masking applied — the value the reported
    /// deltas are computed from. Present only when masking changed it.
    #[serde(skip_serializing_if = "Option::is_none")]
    total_after_effective: Option<f64>,
    files: Vec<FileDeltaView>,
    /// Unchanged files (not touched by the diff) that nonetheless moved
    /// substantially — flagged as not attributable to the PR.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    notable_unchanged: Vec<FileDeltaView>,
}

#[derive(Debug, Clone, Serialize)]
struct FileDeltaView {
    path: String,
    before: Option<f64>,
    /// The real, measured head coverage.
    after: Option<f64>,
    /// Head coverage with `tolerate` masking applied. Present only when masking
    /// changed it, in which case `delta` is `after_effective - before` rather
    /// than `after - before`.
    #[serde(skip_serializing_if = "Option::is_none")]
    after_effective: Option<f64>,
    delta: Option<f64>,
}

#[derive(Debug, Clone, Serialize)]
struct IndirectView {
    newly_covered: usize,
    newly_uncovered: usize,
    lines: Vec<IndirectLineView>,
}

#[derive(Debug, Clone, Serialize)]
struct IndirectLineView {
    path: String,
    head_line: u32,
    base_line: u32,
    transition: String,
}

impl CoverageDiffView {
    fn build(diff: &CoverageDiff, opts: &RenderOptions) -> Self {
        let patch_coverage = PatchView {
            percent: diff.patch.percent().map(round2),
            covered: diff.patch.covered,
            total: diff.patch.total(),
            files: diff
                .file_patches
                .iter()
                .map(|fp| FilePatchView {
                    path: fp.path.clone(),
                    percent: fp.patch.percent().map(round2),
                    covered: fp.patch.covered,
                    total: fp.patch.total(),
                    uncovered_lines: fp.uncovered_lines.clone(),
                })
                .collect(),
        };

        let uncovered_new_lines = diff
            .uncovered_new_lines
            .iter()
            .map(|(path, line)| format!("{path}:{line}"))
            .collect();

        let (project_delta, indirect_changes) = if diff.has_baseline {
            let file_delta_view = |fd: &crate::analysis::FileDelta| FileDeltaView {
                path: fd.path.clone(),
                before: fd.before.map(round2),
                after: fd.after.map(round2),
                after_effective: fd
                    .is_masked()
                    .then(|| fd.after_effective.map(round2))
                    .flatten(),
                delta: fd.delta().map(round2),
            };
            let project_delta = ProjectDeltaView {
                total_before: diff.total_before.map(round2),
                total_after: diff.total_after.map(round2),
                total_after_effective: (diff.total_after_effective != diff.total_after)
                    .then(|| diff.total_after_effective.map(round2))
                    .flatten(),
                files: diff.file_deltas.iter().map(file_delta_view).collect(),
                notable_unchanged: diff.notable_unchanged.iter().map(file_delta_view).collect(),
            };
            let indirect_changes = IndirectView {
                newly_covered: diff.indirect_newly_covered(),
                newly_uncovered: diff.indirect_newly_uncovered(),
                lines: diff
                    .indirect
                    .iter()
                    .map(|c| IndirectLineView {
                        path: c.path.clone(),
                        head_line: c.head_line,
                        base_line: c.base_line,
                        transition: if c.became_covered {
                            "uncovered_to_covered".to_string()
                        } else {
                            "covered_to_uncovered".to_string()
                        },
                    })
                    .collect(),
            };
            (Some(project_delta), Some(indirect_changes))
        } else {
            (None, None)
        };

        let markers = diff
            .markers
            .iter()
            .map(|m| MarkerView {
                path: m.path.clone(),
                kind: m.kind.as_str().to_string(),
                side: m.side.as_str().to_string(),
                start: m.start,
                end: m.end,
                reason: m.reason.clone(),
            })
            .collect();

        let excluded_files = (!diff.excluded.is_empty()).then(|| ExcludedFilesView {
            count: diff.excluded.count(),
            touched_count: diff.excluded.touched_count(),
            new_executable_lines: diff.excluded.new_executable_lines(),
            paths: diff.excluded.paths().map(str::to_string).collect(),
            touched: diff.excluded.touched().map(str::to_string).collect(),
        });

        Self {
            explanation: (!opts.no_explanation).then(explanation),
            patch_coverage,
            uncovered_new_lines,
            unmeasured_files: diff.unmeasured_files.clone(),
            project_delta,
            indirect_changes,
            markers,
            excluded_files,
        }
    }

    /// Sets the `present` flag on each documented field based on the data.
    fn update_field_presence(&mut self) {
        let Some(explanation) = &mut self.explanation else {
            return;
        };
        let has_patch_files = !self.patch_coverage.files.is_empty();
        let has_uncovered = !self.uncovered_new_lines.is_empty();
        let has_baseline = self.project_delta.is_some();
        let has_indirect = self
            .indirect_changes
            .as_ref()
            .is_some_and(|i| !i.lines.is_empty());
        let has_markers = !self.markers.is_empty();
        let has_excluded = self.excluded_files.is_some();
        for field in &mut explanation.fields {
            field.present = match field.name.as_str() {
                "patch_coverage.percent"
                | "patch_coverage.covered"
                | "patch_coverage.total"
                | "unmeasured_files[]" => true,
                "patch_coverage.files[].path" => has_patch_files,
                "uncovered_new_lines[]" => has_uncovered,
                "project_delta.total_after" | "project_delta.files[].path" => has_baseline,
                "indirect_changes.lines[].path" => has_indirect,
                "markers[].path" => has_markers,
                "excluded_files.paths[]" => has_excluded,
                _ => false,
            };
        }
    }
}

/// Builds the static field-explanation block for the coverage view.
fn explanation() -> FieldExplanation {
    fn field(name: &str, text: &str) -> FieldDocumentation {
        FieldDocumentation {
            name: name.to_string(),
            text: text.to_string(),
            command: None,
            present: false,
        }
    }
    FieldExplanation {
        text: "Diff/patch coverage analysis. `patch_coverage` attributes coverage to the lines \
               this diff added (needs only the head report + diff). `project_delta` and \
               `indirect_changes` are present only when a baseline report was supplied."
            .to_string(),
        fields: vec![
            field(
                "patch_coverage.percent",
                "Percentage of added, instrumented lines that are covered.",
            ),
            field("patch_coverage.covered", "Count of covered added lines."),
            field(
                "patch_coverage.total",
                "Count of added, instrumented lines (the patch-coverage denominator).",
            ),
            field(
                "patch_coverage.files[].path",
                "Per-file patch coverage for files that added instrumented lines.",
            ),
            field(
                "uncovered_new_lines[]",
                "Actionable `file:line` list of added lines that are not covered.",
            ),
            field(
                "project_delta.total_after",
                "Project line coverage before/after; present only with a baseline report.",
            ),
            field(
                "project_delta.files[].path",
                "Per-file before/after coverage and delta; present only with a baseline report.",
            ),
            field(
                "indirect_changes.lines[].path",
                "Lines whose coverage flipped without their content changing; needs a baseline.",
            ),
            field(
                "markers[].path",
                "Source-marker regions that applied. `kind` is `ignore` (lines removed from both \
                 reports) or `tolerate` (lines kept in the percentages, but their coverage flips \
                 masked). Where a region was tolerated, `delta` is computed from \
                 `after_effective`, not from the displayed `after`.",
            ),
            field(
                "unmeasured_files[]",
                "Non-deleted touched files absent under either name from every supplied report. Explicit filename exclusions are omitted. May be non-code or uninstrumented code; only matching require-measured globs fail the gate.",
            ),
            field(
                "excluded_files.paths[]",
                "Files `--ignore-filename-regex` (or `config.yaml`) removed from the head or \
                 baseline report. `touched` is the subset this diff changed, and \
                 `new_executable_lines` counts the executable lines it added to them, so an \
                 empty `patch_coverage` caused by the filter can be told from a diff that added \
                 no code. Absent when nothing was excluded.",
            ),
        ],
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::analysis::{
        AppliedMarker, ExcludedFiles, FileDelta, FilePatch, IndirectChange, MarkerSide,
        PatchCoverage,
    };

    #[test]
    fn fmt_num_trims_trailing_zeros() {
        assert_eq!(fmt_num(100.0), "100");
        assert_eq!(fmt_num(65.4), "65.4");
        assert_eq!(fmt_num(65.432), "65.43");
        assert_eq!(fmt_num(50.0), "50");
        assert_eq!(fmt_num(-0.001), "0");
    }

    #[test]
    fn collapse_ranges_groups_consecutive() {
        assert_eq!(collapse_ranges(&[5]), "5");
        assert_eq!(collapse_ranges(&[9, 10, 11]), "9-11");
        assert_eq!(collapse_ranges(&[5, 9, 10, 11, 20]), "5, 9-11, 20");
    }

    #[test]
    fn sha_ref_links_when_url_present() {
        assert_eq!(sha_ref("abcdef1234", None), "`abcdef1`");
        assert_eq!(
            sha_ref("abcdef1234", Some("https://x/commit")),
            "[`abcdef1`](https://x/commit/abcdef1234)"
        );
    }

    fn sample_diff() -> CoverageDiff {
        CoverageDiff {
            patch: PatchCoverage {
                covered: 4,
                uncovered: 1,
            },
            file_patches: vec![FilePatch {
                path: "src/a.rs".to_string(),
                patch: PatchCoverage {
                    covered: 4,
                    uncovered: 1,
                },
                uncovered_lines: vec![9],
            }],
            uncovered_new_lines: vec![("src/a.rs".to_string(), 9)],
            total_after: Some(80.0),
            ..Default::default()
        }
    }

    #[test]
    fn markdown_without_baseline_has_patch_section() {
        let diff = sample_diff();
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("## Coverage"));
        assert!(md.contains("Total: **80%**"));
        assert!(md.contains("### Patch coverage"));
        assert!(md.contains("Patch: **80%** (4/5 new lines covered)"));
        assert!(md.contains("`src/a.rs:9`"));
        assert!(md.contains("No baseline report supplied"));
        assert!(md.contains("require a baseline report"));
        assert!(!md.contains("will appear"));
        assert!(!md.contains("baseline artifact"));
        assert!(!md.contains("`main`"));
    }

    #[test]
    fn markdown_with_baseline_shows_total_delta_and_indirect() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(75.0);
        diff.indirect = vec![IndirectChange {
            path: "src/b.rs".to_string(),
            base_line: 5,
            head_line: 5,
            became_covered: false,
        }];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("🟢 5 pp vs `main`"));
        assert!(md.contains("### Indirect coverage changes"));
        assert!(md.contains("`src/b.rs:5`"));
    }

    /// The arrow must agree with the number printed beside it. A delta
    /// inside the rounding interval prints `0 pp`, so it must be neutral rather
    /// than raising a red alarm next to a number that says nothing moved.
    #[test]
    fn markdown_sub_rounding_delta_is_neutral() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(80.0);
        diff.total_after = Some(79.996);
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("\u{26aa} 0 pp vs `main`"), "{md}");
        assert!(
            !md.contains("\u{1f534}"),
            "sub-rounding move must not paint red: {md}"
        );
    }

    /// The same pairing in the per-file table, which the EPS row filter happens
    /// to protect, and in the notable-unchanged table, which it does not: that
    /// section is gated on *covered lines* (>= 10), so a large file can reach it
    /// with a sub-rounding percentage-point move.
    #[test]
    fn notable_unchanged_sub_rounding_delta_is_neutral() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(80.0);
        diff.notable_unchanged = vec![FileDelta::new(
            "src/big.rs".to_string(),
            Some(90.0),
            Some(89.998),
        )];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(
            md.contains("| `src/big.rs` | 90% | 90% | \u{26aa} 0 pp |"),
            "{md}"
        );
    }

    /// A docs-only PR whose headline moved because one
    /// CPU-conditional function flipped between two runner CPUs, while every
    /// per-file section of the same comment reported nothing.
    #[test]
    fn markdown_sub_eps_total_move_is_neutral_and_annotated() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(92.8012);
        diff.total_after = Some(92.7924);
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(
            !md.contains("\u{1f534}"),
            "sub-EPS move must not paint red: {md}"
        );
        assert!(md.contains("Total: **92.79%** \u{26aa} -0.01 pp"), "{md}");
        assert!(md.contains("_(not attributable to this diff)_"), "{md}");
    }

    /// Above the tolerance the headline still reports the direction — but with
    /// nothing below it to account for the move, it says so.
    #[test]
    fn markdown_unexplained_total_move_is_annotated() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(85.0);
        diff.total_after = Some(80.0);
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(
            md.contains("\u{1f534} -5 pp vs `main` _(not attributable to this diff)_"),
            "{md}"
        );
    }

    /// A move a per-file row *does* explain is left unannotated.
    #[test]
    fn markdown_explained_total_move_is_not_annotated() {
        let diff = baseline_diff();
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(!md.contains("not attributable"), "{md}");
    }

    /// A notable-unchanged entry also counts as an explanation, even though it
    /// is not attributed to the PR: the reader can see where the move came from.
    #[test]
    fn markdown_notable_unchanged_explains_total_move() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(85.0);
        diff.total_after = Some(80.0);
        diff.notable_unchanged = vec![FileDelta::new(
            "src/big.rs".to_string(),
            Some(90.0),
            Some(60.0),
        )];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(!md.contains("not attributable to this diff"), "{md}");
    }

    fn tolerated_marker() -> AppliedMarker {
        AppliedMarker {
            path: "src/util/simd/x86.rs".to_string(),
            kind: crate::MarkerKind::Tolerate,
            side: MarkerSide::Both,
            start: 41,
            end: 52,
            reason: "CPU-gated: the avx512f arm only runs on Zen 4+".to_string(),
        }
    }

    /// The motivating case: the headline shows the *real* percentage but
    /// takes its movement from the masked one, so the reported number stays
    /// truthful while the silenced flip stops moving the needle.
    #[test]
    fn markdown_headline_uses_effective_coverage_for_the_delta_only() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(92.8012);
        diff.total_after = Some(92.7924);
        diff.total_after_effective = Some(92.8012);
        diff.markers = vec![tolerated_marker()];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(
            md.contains("Total: **92.79%** \u{26aa} 0 pp vs `main`"),
            "{md}"
        );
        assert!(
            !md.contains("not attributable"),
            "a masked move is not a move: {md}"
        );
    }

    /// Silencing is never invisible.
    #[test]
    fn markdown_lists_every_applied_marker() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(80.0);
        diff.markers = vec![
            tolerated_marker(),
            AppliedMarker {
                path: "src/generated.rs".to_string(),
                kind: crate::MarkerKind::Ignore,
                side: MarkerSide::Head,
                start: 7,
                end: 7,
                reason: "generated".to_string(),
            },
        ];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(
            md.contains("\u{1f507} 1 ignored region(s), 1 tolerated region(s)"),
            "{md}"
        );
        assert!(
            md.contains("| `src/util/simd/x86.rs` | `tolerate` | 41-52 | both |"),
            "{md}"
        );
        assert!(
            md.contains("| `src/generated.rs` | `ignore` | 7 | head |"),
            "{md}"
        );
        assert!(md.contains("the avx512f arm only runs on Zen 4+"), "{md}");
    }

    /// `ignore` shapes the total and the patch even with no baseline, so its
    /// note must appear there too.
    #[test]
    fn markdown_lists_markers_without_a_baseline() {
        let mut diff = sample_diff();
        diff.markers = vec![tolerated_marker()];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("1 tolerated region(s)"), "{md}");
    }

    #[test]
    fn markdown_omits_the_note_when_no_marker_applied() {
        let md = render(
            &baseline_diff(),
            &RenderOptions::default(),
            OutputFormat::Markdown,
        )
        .unwrap();
        assert!(!md.contains("region(s)"), "{md}");
    }

    /// The structured views must agree with the markdown: `delta` is the masked
    /// value, and `after`/`total_after` stay real, with the effective value
    /// alongside so a consumer can see why they differ.
    #[test]
    fn json_reports_markers_and_effective_coverage() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(92.8012);
        diff.total_after = Some(92.7924);
        diff.total_after_effective = Some(92.8012);
        diff.file_deltas = vec![FileDelta {
            path: "src/util/simd/x86.rs".to_string(),
            before: Some(90.0),
            after: Some(80.0),
            after_effective: Some(90.0),
        }];
        diff.markers = vec![tolerated_marker()];
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(value["project_delta"]["total_after"], 92.79);
        assert_eq!(value["project_delta"]["total_after_effective"], 92.8);
        let file = &value["project_delta"]["files"][0];
        assert_eq!(file["after"], 80.0);
        assert_eq!(file["after_effective"], 90.0);
        assert_eq!(
            file["delta"], 0.0,
            "delta is computed from the masked value"
        );
        assert_eq!(value["markers"][0]["kind"], "tolerate");
        assert_eq!(value["markers"][0]["side"], "both");
        assert_eq!(value["markers"][0]["start"], 41);
    }

    /// An unmasked run must not grow the effective fields — they exist only to
    /// explain a discrepancy, so an absent one means "there was none".
    #[test]
    fn json_omits_effective_fields_when_nothing_was_masked() {
        let mut diff = baseline_diff();
        diff.total_after_effective = diff.total_after;
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(value["project_delta"]
            .get("total_after_effective")
            .is_none());
        assert!(value["project_delta"]["files"][0]
            .get("after_effective")
            .is_none());
        assert!(value.get("markers").is_none());
    }

    #[test]
    fn json_round_trips() {
        let diff = sample_diff();
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(value["patch_coverage"]["covered"], 4);
        assert_eq!(value["patch_coverage"]["total"], 5);
        assert_eq!(value["uncovered_new_lines"][0], "src/a.rs:9");
        // Baseline-only sections absent without a baseline.
        assert!(value.get("project_delta").is_none());
    }

    #[test]
    fn yaml_renders() {
        let diff = sample_diff();
        let yaml = render(&diff, &RenderOptions::default(), OutputFormat::Yaml).unwrap();
        assert!(yaml.contains("patch_coverage:"));
        assert!(yaml.contains("explanation:"));
    }

    /// A baseline diff exercising the delta table (new file, decrease, increase,
    /// below-EPS filtering, an em-dash `After`), the patch table with range
    /// collapsing, and the artifact footer.
    fn baseline_diff() -> CoverageDiff {
        CoverageDiff {
            patch: PatchCoverage {
                covered: 2,
                uncovered: 4,
            },
            file_patches: vec![FilePatch {
                path: "src/a.rs".to_string(),
                patch: PatchCoverage {
                    covered: 2,
                    uncovered: 4,
                },
                uncovered_lines: vec![9, 10, 11, 15],
            }],
            uncovered_new_lines: vec![
                ("src/a.rs".to_string(), 9),
                ("src/a.rs".to_string(), 10),
                ("src/a.rs".to_string(), 11),
                ("src/a.rs".to_string(), 15),
            ],
            has_baseline: true,
            total_after: Some(80.0),
            total_before: Some(80.0), // equal → ⚪ 0 pp
            file_deltas: vec![
                FileDelta::new("src/new.rs".to_string(), None, Some(50.0)),
                FileDelta::new("src/down.rs".to_string(), Some(100.0), Some(70.0)),
                FileDelta::new("src/up.rs".to_string(), Some(70.0), Some(90.0)),
                // below EPS → filtered out
                FileDelta::new("src/tiny.rs", Some(90.0), Some(90.02)),
                // `After` renders as an em dash
                FileDelta::new("src/gone.rs", Some(50.0), None),
            ],
            ..Default::default()
        }
    }

    fn excluded(touched_paths: &[&str], other_paths: &[&str], added: &[u32]) -> ExcludedFiles {
        use crate::diff::{DiffModel, FileDiff};
        use crate::model::FileCoverage;
        let mut e = ExcludedFiles::default();
        let mut diff = DiffModel::default();
        for path in touched_paths.iter().chain(other_paths) {
            let mut f = FileCoverage::new(*path);
            f.record(1, 1);
            e.record_head(vec![f]);
        }
        for path in touched_paths {
            diff.files.insert(
                (*path).to_string(),
                FileDiff::new(
                    *path,
                    None,
                    true,
                    false,
                    added.iter().copied().collect(),
                    std::collections::BTreeSet::new(),
                ),
            );
        }
        e.resolve(&diff);
        e
    }

    #[test]
    fn nothing_excluded_adds_nothing_to_either_format() {
        let diff = sample_diff();
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(!md.contains("Excluded"));
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        assert!(!json.contains("\"excluded_files\""));
    }

    #[test]
    fn markdown_says_how_many_files_were_excluded_and_touched() {
        let mut diff = sample_diff();
        diff.excluded = excluded(&["src/a.rs"], &["src/b.rs", "src/c.rs"], &[1]);
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains(
            "_Excluded by ignore-filename-regex: 3 files (1 of them touched by this diff, \
             adding 1 executable line)._"
        ));
        assert!(md.contains("Excluded files touched by this diff (1)"));
        assert!(md.contains("- `src/a.rs`"));
        assert!(
            !md.contains("- `src/b.rs`"),
            "untouched paths stay in the JSON"
        );
        // The patch is not empty here, so its sentence is untouched.
        assert!(md.contains("Patch: **80%**"));
    }

    #[test]
    fn markdown_caps_the_touched_list_and_counts_the_rest() {
        let mut diff = sample_diff();
        let paths: Vec<String> = (0..25).map(|i| format!("gen/f{i:02}.rs")).collect();
        let refs: Vec<&str> = paths.iter().map(String::as_str).collect();
        diff.excluded = excluded(&refs, &[], &[1]);
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("- `gen/f19.rs`"));
        assert!(!md.contains("- `gen/f20.rs`"));
        assert!(md.contains("- _…and 5 more_"));
    }

    #[test]
    fn markdown_says_when_the_diff_touched_no_excluded_file() {
        let mut diff = sample_diff();
        diff.excluded = excluded(&[], &["src/b.rs"], &[]);
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains(
            "_Excluded by ignore-filename-regex: 1 file (none of them touched by this diff)._"
        ));
        assert!(!md.contains("<summary>Excluded files touched"));
    }

    #[test]
    fn empty_patch_reads_differently_when_the_filter_took_the_new_lines() {
        let mut diff = CoverageDiff::default();
        let plain = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(plain.contains("_No new executable lines added by this diff._"));

        diff.excluded = excluded(&["src/gen.rs"], &[], &[1]);
        let one = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(!one.contains("_No new executable lines added by this diff._"));
        assert!(one.contains(
            "_No new executable lines in the files measured: 1 new executable line is in \
             files excluded by ignore-filename-regex._"
        ));

        diff.excluded = excluded(&["src/a.rs", "src/b.rs"], &[], &[1]);
        let two = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(two.contains("2 new executable lines are in files excluded"));
    }

    #[test]
    fn json_lists_excluded_paths_and_marks_the_field_present() {
        let mut diff = sample_diff();
        diff.excluded = excluded(&["src/a.rs"], &["src/b.rs"], &[1]);
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let e = &value["excluded_files"];
        assert_eq!(e["count"], 2);
        assert_eq!(e["touched_count"], 1);
        assert_eq!(e["new_executable_lines"], 1);
        assert_eq!(e["paths"], serde_json::json!(["src/a.rs", "src/b.rs"]));
        assert_eq!(e["touched"], serde_json::json!(["src/a.rs"]));
        let field = value["explanation"]["fields"]
            .as_array()
            .unwrap()
            .iter()
            .find(|f| f["name"] == "excluded_files.paths[]")
            .unwrap();
        assert_eq!(field["present"], true);
    }

    #[test]
    fn markdown_delta_table_and_footer() {
        let diff = baseline_diff();
        let opts = RenderOptions {
            artifact_url: Some("https://artifact".to_string()),
            run_url: Some("https://run".to_string()),
            collapse_ranges: true,
            ..Default::default()
        };
        let md = render(&diff, &opts, OutputFormat::Markdown).unwrap();
        assert!(md.contains("⚪ 0 pp vs `main`"));
        assert!(md.contains("| `src/new.rs` | — | 50% | 🆕 new |"));
        assert!(md.contains("🔴 -30 pp"));
        assert!(md.contains("🟢 20 pp"));
        assert!(md.contains("| `src/gone.rs` | 50% | — | 🔴 -50 pp |"));
        assert!(!md.contains("tiny.rs"), "below-EPS row must be filtered");
        // Patch table with collapsed ranges.
        assert!(md.contains("9-11, 15"));
        // Artifact footer with run link.
        assert!(md.contains("[Full per-file coverage summary](https://artifact)"));
        assert!(md.contains("[run summary](https://run)"));
    }

    #[test]
    fn markdown_footer_links_are_independent_and_optional() {
        for artifact in [None, Some(""), Some("https://artifact")] {
            for run in [None, Some(""), Some("https://run")] {
                let opts = RenderOptions {
                    artifact_url: artifact.map(str::to_string),
                    run_url: run.map(str::to_string),
                    ..Default::default()
                };
                let md = render(&sample_diff(), &opts, OutputFormat::Markdown).unwrap();
                let has_artifact = artifact == Some("https://artifact");
                let has_run = run == Some("https://run");
                assert_eq!(
                    md.contains("[Full per-file coverage summary](https://artifact)"),
                    has_artifact,
                    "{md}"
                );
                assert_eq!(md.contains("[run summary](https://run)"), has_run, "{md}");
                assert_eq!(md.contains("<sub>"), has_artifact || has_run, "{md}");
                assert_eq!(md.contains(" · "), has_artifact && has_run, "{md}");
                assert!(!md.contains("coverage-summary"), "{md}");
                assert!(!md.contains("attached"), "{md}");
            }
        }
    }

    #[test]
    fn markdown_comparing_line_and_covered_indirect() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(80.0);
        diff.indirect = vec![IndirectChange {
            path: "src/b.rs".to_string(),
            base_line: 5,
            head_line: 5,
            became_covered: true,
        }];
        let opts = RenderOptions {
            base_sha: Some("abcdef123".to_string()),
            head_sha: Some("fedcba321".to_string()),
            commit_url: Some("https://x/commit".to_string()),
            ..Default::default()
        };
        let md = render(&diff, &opts, OutputFormat::Markdown).unwrap();
        assert!(md.contains("Comparing [`abcdef1`](https://x/commit/abcdef123)"));
        assert!(md.contains("🟢 uncovered → covered"));
    }

    #[test]
    fn markdown_no_per_file_changes() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = Some(80.0);
        // No file_deltas → "no per-file coverage changes".
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("_No per-file coverage changes vs `main`._"));
    }

    #[test]
    fn markdown_baseline_without_total_before() {
        let mut diff = sample_diff();
        diff.has_baseline = true;
        diff.total_before = None;
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("Total: **80%**"));
        assert!(!md.contains("pp vs"));
    }

    #[test]
    fn markdown_no_added_lines() {
        let diff = CoverageDiff {
            total_after: Some(50.0),
            ..Default::default()
        };
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("_No new executable lines added by this diff._"));
    }

    #[test]
    fn json_and_yaml_with_baseline_include_project_delta() {
        let diff = baseline_diff();
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(value.get("project_delta").is_some());
        assert_eq!(value["project_delta"]["total_after"], 80.0);
        assert!(value.get("indirect_changes").is_some());

        let yaml = render(&diff, &RenderOptions::default(), OutputFormat::Yaml).unwrap();
        assert!(yaml.contains("project_delta:"));
    }

    #[test]
    fn markdown_renders_notable_unchanged_note() {
        let mut diff = baseline_diff();
        diff.notable_unchanged = vec![
            FileDelta::new("src/other.rs".to_string(), Some(80.0), Some(60.0)),
            // Absent from the baseline → delta() is None → renders as "🆕 new".
            FileDelta::new("src/fresh.rs".to_string(), None, Some(55.0)),
        ];
        let md = render(&diff, &RenderOptions::default(), OutputFormat::Markdown).unwrap();
        assert!(md.contains("unchanged file(s) also moved (not attributed to this PR)"));
        assert!(md.contains("`src/other.rs`"));
        assert!(md.contains("🔴 -20 pp"));
        assert!(md.contains("| `src/fresh.rs` | — | 55% | 🆕 new |"));
    }

    #[test]
    fn json_includes_notable_unchanged() {
        let mut diff = baseline_diff();
        diff.notable_unchanged = vec![FileDelta::new(
            "src/other.rs".to_string(),
            Some(80.0),
            Some(60.0),
        )];
        let json = render(&diff, &RenderOptions::default(), OutputFormat::Json).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(
            value["project_delta"]["notable_unchanged"][0]["path"],
            "src/other.rs"
        );
    }
}