cpd-reporter 0.1.21

Output format reporters for cpd
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
// dashboard.rs — one static screen with the whole picture (`--dashboard`):
// health, project size, duplication, complexity and dead code. The numbers
// are gathered once into a [`DashboardView`], which the console prints and
// the JSON reporter serializes, so the two can never disagree.

use crate::health_render;
use crate::shared::Style;
use crate::summary_render::human_size;
use cpd_core::deadcode::Report as DeadCodeReport;
use cpd_core::health::Health;
use cpd_core::models::{CloneKind, CpdClone, Statistics};
use cpd_core::summary::{FileSummary, Summary};
use serde::Serialize;
use std::time::Duration;

/// Everything the dashboard shows, computed by the caller from one clone run,
/// one full-length summary and, when available, one dead-code run.
pub struct Dashboard<'a> {
    pub health: &'a Health,
    pub statistics: &'a Statistics,
    pub clones: &'a [CpdClone],
    /// Every file, not a top-N: the dashboard ranks it two ways.
    pub summary: &'a Summary,
    /// `None` when no file is in a language dead-code analysis supports.
    pub dead_code: Option<&'a DeadCodeReport>,
    /// Rows per ranked list.
    pub top: usize,
    pub elapsed: Duration,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DashboardView {
    pub health: Health,
    pub project: ProjectView,
    pub duplication: DuplicationView,
    pub complexity: ComplexityView,
    /// `null` when no file is in a language dead-code analysis supports.
    pub dead_code: Option<DeadCodeView>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectView {
    pub files: u64,
    pub lines: u64,
    pub tokens: u64,
    /// Every format, largest first.
    pub formats: Vec<FormatLines>,
    /// The largest code files, by lines; prose, data and markup files are
    /// left out, as they are from the complexity list.
    pub largest_files: Vec<LargeFile>,
}

#[derive(Debug, Serialize)]
pub struct FormatLines {
    pub format: String,
    pub lines: u64,
}

#[derive(Debug, Serialize)]
pub struct LargeFile {
    pub path: String,
    pub format: String,
    pub lines: u64,
    pub tokens: u64,
    pub bytes: u64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DuplicationView {
    pub percentage: f64,
    pub clones: u64,
    pub exact: u64,
    pub renamed: u64,
    pub similar: u64,
    /// Every format with at least one duplicated line, most duplicated first.
    pub formats: Vec<FormatDuplication>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FormatDuplication {
    pub format: String,
    pub percentage: f64,
    pub duplicated_lines: u64,
    pub clones: u64,
}

#[derive(Debug, Serialize)]
pub struct ComplexityView {
    pub total: u64,
    /// Mean per code file; prose and data files are left out.
    pub mean: f64,
    /// The most complex files.
    pub files: Vec<ComplexFile>,
}

#[derive(Debug, Serialize)]
pub struct ComplexFile {
    pub path: String,
    pub complexity: u64,
    pub lines: u64,
    pub bytes: u64,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeadCodeView {
    pub percentage: f64,
    pub findings: u64,
    pub files: u64,
    pub by_category: Vec<CategoryFindings>,
    /// The largest findings, by lines.
    pub largest: Vec<LargeFinding>,
}

#[derive(Debug, Serialize)]
pub struct CategoryFindings {
    pub category: &'static str,
    pub count: u32,
}

#[derive(Debug, Serialize)]
pub struct LargeFinding {
    pub category: &'static str,
    pub path: String,
    /// Empty for a whole-file finding.
    pub name: String,
    pub line: u32,
    pub lines: u32,
}

const WIDTH: usize = 60;

fn heading(title: &str, style: &Style) {
    let rule = "─".repeat(WIDTH.saturating_sub(title.chars().count() + 4));
    println!("{}", style.bold(&format!("── {title} {rule}")));
}

pub(crate) fn thousands(n: u64) -> String {
    match n {
        0..1_000 => n.to_string(),
        1_000..1_000_000 => format!("{:.1}K", n as f64 / 1_000.0),
        _ => format!("{:.1}M", n as f64 / 1_000_000.0),
    }
}

/// `1 file`, `2 files`.
fn plural(n: u64, noun: &str) -> String {
    match n {
        1 => format!("1 {noun}"),
        _ => format!("{n} {noun}s"),
    }
}

/// `N label` joined with ` · `, skipping zero counts.
fn counts(parts: &[(u64, &str)]) -> String {
    parts
        .iter()
        .filter(|(n, _)| *n > 0)
        .map(|(n, label)| format!("{n} {label}"))
        .collect::<Vec<_>>()
        .join(" · ")
}

/// The first `numeric` columns right-aligned, the rest left-aligned.
fn table(headers: &[&str], numeric: usize, rows: &[Vec<String>], style: &Style) {
    // A cell can be a file path, a format name or a finding name — all from
    // the repository being scanned, not literal jscpd text. A newline in
    // one would print as an extra row with none of the other columns'
    // data, forging a table row that never came from a real scan.
    let rows: Vec<Vec<String>> = rows
        .iter()
        .map(|row| {
            row.iter()
                .map(|cell| cell.replace(['\n', '\r'], " "))
                .collect()
        })
        .collect();
    let last = headers.len() - 1;
    let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
    for row in &rows {
        for (w, cell) in widths.iter_mut().zip(row) {
            *w = (*w).max(cell.chars().count());
        }
    }
    let line = |cells: Vec<String>| {
        cells
            .iter()
            .enumerate()
            .map(|(i, c)| match (i < numeric, i == last) {
                (true, _) => format!("{c:>w$}", w = widths[i]),
                (false, true) => c.clone(),
                (false, false) => format!("{c:<w$}", w = widths[i]),
            })
            .collect::<Vec<_>>()
            .join("  ")
    };
    println!(
        "    {}",
        style.dim(&line(headers.iter().map(|h| h.to_string()).collect()))
    );
    for row in &rows {
        println!("    {}", line(row.clone()));
    }
}

fn round1(value: f64) -> f64 {
    (value * 10.0).round() / 10.0
}

/// Matches the two decimal places the console already prints this value
/// with (`{:.2}%`), so JSON carries the same number, not the raw
/// `f64` division noise (`49.583333333333336`) behind that formatted text.
fn round2(value: f64) -> f64 {
    (value * 100.0).round() / 100.0
}

impl Dashboard<'_> {
    /// Gather every number the dashboard shows.
    pub fn view(&self) -> DashboardView {
        let total = &self.statistics.total;
        let mut formats: Vec<FormatLines> = self
            .statistics
            .formats
            .iter()
            .map(|(format, row)| FormatLines {
                format: format.clone(),
                lines: row.lines,
            })
            .collect();
        formats.sort_by(|a, b| b.lines.cmp(&a.lines).then(a.format.cmp(&b.format)));

        let kind_count =
            |kind: CloneKind| self.clones.iter().filter(|c| c.kind == kind).count() as u64;
        // Prose/data formats (markdown, JSON, YAML, ...) and markup formats
        // (HTML, CSS, templates, ...) never count toward the health score's
        // duplication share; a row for them here would describe a number
        // the score does not have.
        let mut duplicated_formats: Vec<FormatDuplication> = self
            .statistics
            .formats
            .iter()
            .filter(|(format, row)| row.duplicated_lines > 0 && cpd_core::summary::is_code(format))
            .map(|(format, row)| FormatDuplication {
                format: format.clone(),
                percentage: round1(row.percentage),
                duplicated_lines: row.duplicated_lines,
                clones: row.clones,
            })
            .collect();
        duplicated_formats.sort_by(|a, b| {
            b.percentage
                .total_cmp(&a.percentage)
                .then(b.duplicated_lines.cmp(&a.duplicated_lines))
                .then(a.format.cmp(&b.format))
        });

        // A lockfile or a changelog is often the longest file in a
        // repository and nothing anyone would split: only code is ranked.
        let mut largest: Vec<&FileSummary> = self
            .summary
            .files
            .iter()
            .filter(|f| cpd_core::summary::is_code(&f.format))
            .collect();
        largest.sort_by(|a, b| {
            b.lines
                .cmp(&a.lines)
                .then(b.bytes.cmp(&a.bytes))
                .then(a.path.cmp(&b.path))
        });

        let mut code: Vec<&FileSummary> = self
            .summary
            .files
            .iter()
            .filter(|f| f.complexity > 0)
            .collect();
        let total_complexity: u64 = code.iter().map(|f| f.complexity).sum();
        let mean = match code.len() {
            0 => 0.0,
            n => total_complexity as f64 / n as f64,
        };
        code.sort_by(|a, b| b.complexity.cmp(&a.complexity).then(a.path.cmp(&b.path)));

        DashboardView {
            health: self.health.clone(),
            project: ProjectView {
                files: total.sources,
                lines: total.lines,
                tokens: total.tokens,
                formats,
                largest_files: largest
                    .iter()
                    .take(self.top)
                    .map(|f| LargeFile {
                        path: f.path.clone(),
                        format: f.format.clone(),
                        lines: f.lines,
                        tokens: f.tokens,
                        bytes: f.bytes,
                    })
                    .collect(),
            },
            duplication: DuplicationView {
                percentage: round2(total.percentage),
                clones: self.clones.len() as u64,
                exact: kind_count(CloneKind::Exact),
                renamed: kind_count(CloneKind::Renamed),
                similar: kind_count(CloneKind::Similar),
                formats: duplicated_formats.into_iter().take(self.top).collect(),
            },
            complexity: ComplexityView {
                total: total_complexity,
                mean: round1(mean),
                files: code
                    .iter()
                    .take(self.top)
                    .map(|f| ComplexFile {
                        path: f.path.clone(),
                        complexity: f.complexity,
                        lines: f.lines,
                        bytes: f.bytes,
                    })
                    .collect(),
            },
            dead_code: self.dead_code.map(|report| {
                let mut largest: Vec<_> = report.findings.iter().collect();
                largest.sort_by(|a, b| {
                    b.lines
                        .cmp(&a.lines)
                        .then(a.path.cmp(&b.path))
                        .then(a.start.line.cmp(&b.start.line))
                });
                DeadCodeView {
                    percentage: round2(report.statistics.percentage),
                    findings: report.findings.len() as u64,
                    files: u64::from(report.statistics.files),
                    by_category: report
                        .statistics
                        .by_category
                        .iter()
                        .map(|c| CategoryFindings {
                            category: c.category.as_str(),
                            count: c.count,
                        })
                        .collect(),
                    largest: largest
                        .iter()
                        .take(self.top)
                        .map(|f| LargeFinding {
                            category: f.category.as_str(),
                            path: f.path.clone(),
                            name: f.name.clone(),
                            line: f.start.line,
                            lines: f.lines,
                        })
                        .collect(),
                }
            }),
        }
    }
}

/// Print the dashboard: the health badge on top, then one section per view.
pub fn print_dashboard(view: &DashboardView, top: usize, elapsed: Duration, style: &Style) {
    crate::health_render::print_badge(&view.health, style);
    println!();

    heading("Project", style);
    let project = &view.project;
    println!(
        "  {} · {} lines · {} tokens · {}",
        plural(project.files, "file"),
        thousands(project.lines),
        thousands(project.tokens),
        plural(project.formats.len() as u64, "format")
    );
    if !project.formats.is_empty() {
        let largest = project
            .formats
            .iter()
            .take(top)
            .map(|f| {
                format!(
                    "{} {}",
                    f.format.replace(['\n', '\r'], " "),
                    thousands(f.lines)
                )
            })
            .collect::<Vec<_>>()
            .join(", ");
        println!("  {} {largest} lines", style.dim("largest:"));
    }
    if !project.largest_files.is_empty() {
        println!("  {}", style.dim("Largest code files:"));
        let rows: Vec<Vec<String>> = project
            .largest_files
            .iter()
            .map(|f| {
                vec![
                    f.lines.to_string(),
                    f.tokens.to_string(),
                    human_size(f.bytes),
                    f.path.clone(),
                ]
            })
            .collect();
        table(&["LINES", "TOKENS", "SIZE", "PATH"], 3, &rows, style);
    }

    println!();
    heading("Duplication", style);
    let duplication = &view.duplication;
    let kinds = counts(&[
        (duplication.exact, "exact"),
        (duplication.renamed, "renamed"),
        (duplication.similar, "similar"),
    ]);
    println!(
        "  {} duplicated lines · {}{}",
        style.bold(&format!("{:.2}%", duplication.percentage)),
        plural(duplication.clones, "clone"),
        match kinds.is_empty() {
            true => String::new(),
            false => format!(" ({kinds})"),
        }
    );
    if !duplication.formats.is_empty() {
        println!("  {}", style.dim("By format:"));
        let rows: Vec<Vec<String>> = duplication
            .formats
            .iter()
            .map(|f| {
                vec![
                    format!("{:.1}", f.percentage),
                    f.duplicated_lines.to_string(),
                    f.clones.to_string(),
                    f.format.clone(),
                ]
            })
            .collect();
        table(&["DUP%", "LINES", "CLONES", "FORMAT"], 3, &rows, style);
    }

    println!();
    heading("Complexity", style);
    let complexity = &view.complexity;
    println!(
        "  {} total · {:.1} mean per file",
        style.bold(&complexity.total.to_string()),
        complexity.mean
    );
    if !complexity.files.is_empty() {
        println!("  {}", style.dim("Most complex files:"));
        let rows: Vec<Vec<String>> = complexity
            .files
            .iter()
            .map(|f| {
                vec![
                    f.complexity.to_string(),
                    f.lines.to_string(),
                    human_size(f.bytes),
                    f.path.clone(),
                ]
            })
            .collect();
        table(&["CX", "LINES", "SIZE", "PATH"], 3, &rows, style);
    }

    println!();
    heading("Dead code", style);
    match &view.dead_code {
        None => println!(
            "  {}",
            style.dim("no JavaScript, TypeScript, Python or compiler-checked Rust files")
        ),
        Some(dead) => {
            println!(
                "  {} unused lines · {} in {}",
                style.bold(&format!("{:.2}%", dead.percentage)),
                plural(dead.findings, "finding"),
                plural(dead.files, "file")
            );
            let by_category = dead
                .by_category
                .iter()
                .map(|c| format!("{} {}", c.count, c.category))
                .collect::<Vec<_>>()
                .join(" · ");
            if !by_category.is_empty() {
                println!("  {by_category}");
            }
            if !dead.largest.is_empty() {
                println!("  {}", style.dim("Largest findings:"));
                let rows: Vec<Vec<String>> = dead
                    .largest
                    .iter()
                    .map(|f| {
                        let place = match f.name.is_empty() {
                            true => f.path.clone(),
                            false => format!("{}:{} {}", f.path, f.line, f.name),
                        };
                        vec![f.lines.to_string(), f.category.to_string(), place]
                    })
                    .collect();
                table(&["LINES", "CATEGORY", "WHERE"], 1, &rows, style);
            }
        }
    }
    println!();
    println!(
        "{}",
        style.dim(&format!("time: {:.3}ms", elapsed.as_secs_f64() * 1000.0))
    );
}

/// A GitHub-flavoured Markdown render of the dashboard: the health section,
/// then one table per section, in the same order the console prints them.
pub fn render_markdown(view: &DashboardView) -> String {
    let mut md = String::new();
    md.push_str("# Project dashboard\n\n## Health\n\n");
    md.push_str(&health_render::markdown_section(&view.health));

    md.push_str("## Project\n\n");
    let project = &view.project;
    md.push_str(&format!(
        "{} · {} lines · {} tokens · {}\n\n",
        plural(project.files, "file"),
        thousands(project.lines),
        thousands(project.tokens),
        plural(project.formats.len() as u64, "format")
    ));
    if !project.formats.is_empty() {
        md.push_str("| Format | Lines |\n|---|---:|\n");
        for f in &project.formats {
            md.push_str(&format!(
                "| {} | {} |\n",
                health_render::markdown_cell(&f.format),
                f.lines
            ));
        }
        md.push('\n');
    }
    if !project.largest_files.is_empty() {
        md.push_str("Largest code files:\n\n");
        md.push_str("| Lines | Tokens | Size | Path |\n|---:|---:|---:|---|\n");
        for f in &project.largest_files {
            md.push_str(&format!(
                "| {} | {} | {} | {} |\n",
                f.lines,
                f.tokens,
                human_size(f.bytes),
                health_render::markdown_cell(&f.path)
            ));
        }
        md.push('\n');
    }

    md.push_str("## Duplication\n\n");
    let duplication = &view.duplication;
    md.push_str(&format!(
        "**{:.2}%** duplicated lines · {} (exact {}, renamed {}, similar {})\n\n",
        duplication.percentage,
        plural(duplication.clones, "clone"),
        duplication.exact,
        duplication.renamed,
        duplication.similar
    ));
    if !duplication.formats.is_empty() {
        md.push_str("| Dup% | Lines | Clones | Format |\n|---:|---:|---:|---|\n");
        for f in &duplication.formats {
            md.push_str(&format!(
                "| {:.1} | {} | {} | {} |\n",
                f.percentage,
                f.duplicated_lines,
                f.clones,
                health_render::markdown_cell(&f.format)
            ));
        }
        md.push('\n');
    }

    md.push_str("## Complexity\n\n");
    let complexity = &view.complexity;
    md.push_str(&format!(
        "{} total · {:.1} mean per file\n\n",
        complexity.total, complexity.mean
    ));
    if !complexity.files.is_empty() {
        md.push_str("| CX | Lines | Size | Path |\n|---:|---:|---:|---|\n");
        for f in &complexity.files {
            md.push_str(&format!(
                "| {} | {} | {} | {} |\n",
                f.complexity,
                f.lines,
                human_size(f.bytes),
                health_render::markdown_cell(&f.path)
            ));
        }
        md.push('\n');
    }

    md.push_str("## Dead code\n\n");
    match &view.dead_code {
        None => md.push_str("no JavaScript, TypeScript, Python or compiler-checked Rust files\n"),
        Some(dead) => {
            md.push_str(&format!(
                "**{:.2}%** unused lines · {} in {}\n\n",
                dead.percentage,
                plural(dead.findings, "finding"),
                plural(dead.files, "file")
            ));
            let by_category = dead
                .by_category
                .iter()
                .map(|c| format!("{} {}", c.count, c.category))
                .collect::<Vec<_>>()
                .join(" · ");
            if !by_category.is_empty() {
                md.push_str(&format!("{by_category}\n\n"));
            }
            if !dead.largest.is_empty() {
                md.push_str("| Lines | Category | Where |\n|---:|---|---|\n");
                for f in &dead.largest {
                    let place = match f.name.is_empty() {
                        true => f.path.clone(),
                        false => format!("{}:{} {}", f.path, f.line, f.name),
                    };
                    md.push_str(&format!(
                        "| {} | {} | {} |\n",
                        f.lines,
                        f.category,
                        health_render::markdown_cell(&place)
                    ));
                }
                md.push('\n');
            }
        }
    }
    md
}

/// The dashboard as a standalone HTML page: the health section, then one
/// table per section, in the same order the console prints them.
pub fn render_html(view: &DashboardView) -> String {
    let mut body = String::new();
    body.push_str("<h1>Project dashboard</h1>\n<h2>Health</h2>\n");
    body.push_str(&health_render::html_section(&view.health));

    body.push_str("<h2>Project</h2>\n");
    let project = &view.project;
    body.push_str(&format!(
        "<p>{} · {} lines · {} tokens · {}</p>\n",
        plural(project.files, "file"),
        thousands(project.lines),
        thousands(project.tokens),
        plural(project.formats.len() as u64, "format")
    ));
    if !project.formats.is_empty() {
        body.push_str("<table>\n<thead><tr><th>Format</th><th>Lines</th></tr></thead>\n<tbody>\n");
        for f in &project.formats {
            body.push_str(&format!(
                "<tr><td>{}</td><td>{}</td></tr>\n",
                health_render::escape(&f.format),
                f.lines
            ));
        }
        body.push_str("</tbody>\n</table>\n");
    }
    if !project.largest_files.is_empty() {
        body.push_str(
            "<p>Largest code files:</p>\n<table>\n<thead><tr><th>Lines</th><th>Tokens</th><th>Size</th><th>Path</th></tr></thead>\n<tbody>\n",
        );
        for f in &project.largest_files {
            body.push_str(&format!(
                "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n",
                f.lines,
                f.tokens,
                human_size(f.bytes),
                health_render::escape(&f.path)
            ));
        }
        body.push_str("</tbody>\n</table>\n");
    }

    body.push_str("<h2>Duplication</h2>\n");
    let duplication = &view.duplication;
    body.push_str(&format!(
        "<p><strong>{:.2}%</strong> duplicated lines · {} (exact {}, renamed {}, similar {})</p>\n",
        duplication.percentage,
        plural(duplication.clones, "clone"),
        duplication.exact,
        duplication.renamed,
        duplication.similar
    ));
    if !duplication.formats.is_empty() {
        body.push_str(
            "<table>\n<thead><tr><th>Dup%</th><th>Lines</th><th>Clones</th><th>Format</th></tr></thead>\n<tbody>\n",
        );
        for f in &duplication.formats {
            body.push_str(&format!(
                "<tr><td>{:.1}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n",
                f.percentage,
                f.duplicated_lines,
                f.clones,
                health_render::escape(&f.format)
            ));
        }
        body.push_str("</tbody>\n</table>\n");
    }

    body.push_str("<h2>Complexity</h2>\n");
    let complexity = &view.complexity;
    body.push_str(&format!(
        "<p>{} total · {:.1} mean per file</p>\n",
        complexity.total, complexity.mean
    ));
    if !complexity.files.is_empty() {
        body.push_str(
            "<table>\n<thead><tr><th>CX</th><th>Lines</th><th>Size</th><th>Path</th></tr></thead>\n<tbody>\n",
        );
        for f in &complexity.files {
            body.push_str(&format!(
                "<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>\n",
                f.complexity,
                f.lines,
                human_size(f.bytes),
                health_render::escape(&f.path)
            ));
        }
        body.push_str("</tbody>\n</table>\n");
    }

    body.push_str("<h2>Dead code</h2>\n");
    match &view.dead_code {
        None => body.push_str("<p class=\"muted\">no JavaScript, TypeScript, Python or compiler-checked Rust files</p>\n"),
        Some(dead) => {
            body.push_str(&format!(
                "<p><strong>{:.2}%</strong> unused lines · {} in {}</p>\n",
                dead.percentage,
                plural(dead.findings, "finding"),
                plural(dead.files, "file")
            ));
            let by_category = dead
                .by_category
                .iter()
                .map(|c| format!("{} {}", c.count, c.category))
                .collect::<Vec<_>>()
                .join(" · ");
            if !by_category.is_empty() {
                body.push_str(&format!("<p>{}</p>\n", health_render::escape(&by_category)));
            }
            if !dead.largest.is_empty() {
                body.push_str(
                    "<table>\n<thead><tr><th>Lines</th><th>Category</th><th>Where</th></tr></thead>\n<tbody>\n",
                );
                for f in &dead.largest {
                    let place = match f.name.is_empty() {
                        true => f.path.clone(),
                        false => format!("{}:{} {}", f.path, f.line, f.name),
                    };
                    body.push_str(&format!(
                        "<tr><td>{}</td><td>{}</td><td>{}</td></tr>\n",
                        f.lines,
                        f.category,
                        health_render::escape(&place)
                    ));
                }
                body.push_str("</tbody>\n</table>\n");
            }
        }
    }

    format!(
        "<!doctype html>\n<html><head><meta charset=\"utf-8\"><title>Project dashboard</title><style>{}</style></head><body>\n{body}</body></html>\n",
        health_render::CSS
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn thousands_rounds_to_one_decimal() {
        assert_eq!(thousands(999), "999");
        assert_eq!(thousands(38_240), "38.2K");
        assert_eq!(thousands(2_500_000), "2.5M");
    }

    /// Matches the console's own `{:.2}%` formatting: JSON must carry the
    /// same two-decimal number, not the raw division noise behind it.
    #[test]
    fn round2_matches_the_consoles_two_decimal_display() {
        let value = 100.0 / 3.0; // 33.333333333333336
        assert_eq!(round2(value), 33.33);
        assert_eq!(format!("{:.2}", value), format!("{:.2}", round2(value)));
    }

    #[test]
    fn plural_only_for_one() {
        assert_eq!(plural(1, "clone"), "1 clone");
        assert_eq!(plural(0, "clone"), "0 clones");
        assert_eq!(plural(2, "format"), "2 formats");
    }

    #[test]
    fn counts_skip_zeroes() {
        assert_eq!(
            counts(&[(3, "exact"), (0, "renamed"), (1, "similar")]),
            "3 exact · 1 similar"
        );
        assert_eq!(counts(&[(0, "exact")]), "");
    }

    /// A health nothing was scored into: these tests are about the sections
    /// under the badge.
    fn unscored_health() -> Health {
        Health {
            score: None,
            grade: None,
            size: cpd_core::health::Size {
                lines: 0,
                files: 0,
                class: "XS",
            },
            dimensions: vec![],
            skipped: vec![],
        }
    }

    fn statistics_of(
        formats: std::collections::HashMap<String, cpd_core::models::StatRow>,
    ) -> Statistics {
        Statistics {
            total: Default::default(),
            formats,
            detection_date: "2024-01-01".to_string(),
        }
    }

    #[test]
    fn duplication_by_format_excludes_prose_data_and_markup() {
        use cpd_core::models::StatRow;
        use cpd_core::summary::SummaryMetric;
        use std::collections::HashMap;

        let mut formats = HashMap::new();
        formats.insert(
            "javascript".to_string(),
            StatRow {
                duplicated_lines: 40,
                percentage: 10.0,
                clones: 2,
                ..StatRow::default()
            },
        );
        // json has complexity 0 in the health model: a row here would
        // describe a number the health score does not have.
        formats.insert(
            "json".to_string(),
            StatRow {
                duplicated_lines: 20,
                percentage: 5.0,
                clones: 1,
                ..StatRow::default()
            },
        );
        // markup — the tokenizer's format name for HTML, XML, SVG, … — has
        // no complexity and its duplication does not count toward the
        // health score: same reasoning as json, a different exclusion.
        // `html` is the same markup under its second name, the one an
        // embedded block carries (a Vue `<template>`, a svelte skeleton).
        formats.insert(
            "markup".to_string(),
            StatRow {
                duplicated_lines: 15,
                percentage: 20.0,
                clones: 1,
                ..StatRow::default()
            },
        );
        formats.insert(
            "html".to_string(),
            StatRow {
                duplicated_lines: 30,
                percentage: 25.0,
                clones: 1,
                ..StatRow::default()
            },
        );
        let statistics = statistics_of(formats);
        let health = unscored_health();
        let summary = Summary {
            by: SummaryMetric::Complexity,
            total_files: 0,
            total_folders: 0,
            files: vec![],
            folders: vec![],
        };
        let view = Dashboard {
            health: &health,
            statistics: &statistics,
            clones: &[],
            summary: &summary,
            dead_code: None,
            top: 5,
            elapsed: Duration::ZERO,
        }
        .view();
        let names: Vec<&str> = view
            .duplication
            .formats
            .iter()
            .map(|f| f.format.as_str())
            .collect();
        assert_eq!(
            names,
            vec!["javascript"],
            "json is prose/data, html is markup: neither counts toward the health score"
        );
    }

    /// The list is for finding a file worth splitting, so it ranks code by
    /// lines: a lockfile, a changelog or a long HTML page would otherwise
    /// take every row of it.
    #[test]
    fn largest_files_rank_code_by_lines() {
        use cpd_core::summary::SummaryMetric;
        use std::collections::HashMap;

        let file = |path: &str, format: &str, lines: u64, bytes: u64| FileSummary {
            path: path.to_string(),
            format: format.to_string(),
            lines,
            tokens: lines * 5,
            bytes,
            duplicated_lines: 0,
            duplicated_tokens: 0,
            complexity: 0,
        };
        let summary = Summary {
            by: SummaryMetric::Complexity,
            total_files: 6,
            total_folders: 1,
            files: vec![
                file("small.ts", "typescript", 10, 200),
                file("package-lock.json", "json", 9000, 300_000),
                file("big.ts", "typescript", 400, 9000),
                file("page.html", "markup", 800, 20_000),
                // Same length as b.rs: the heavier file first.
                file("a.rs", "rust", 120, 3000),
                file("b.rs", "rust", 120, 4000),
            ],
            folders: vec![],
        };
        let statistics = statistics_of(HashMap::new());
        let health = unscored_health();
        let view = Dashboard {
            health: &health,
            statistics: &statistics,
            clones: &[],
            summary: &summary,
            dead_code: None,
            top: 3,
            elapsed: Duration::ZERO,
        }
        .view();
        let paths: Vec<&str> = view
            .project
            .largest_files
            .iter()
            .map(|f| f.path.as_str())
            .collect();
        assert_eq!(paths, vec!["big.ts", "b.rs", "a.rs"]);
        assert_eq!(view.project.largest_files[0].tokens, 2000);
    }

    fn sample_view() -> DashboardView {
        DashboardView {
            health: unscored_health(),
            project: ProjectView {
                files: 1,
                lines: 10,
                tokens: 20,
                formats: vec![FormatLines {
                    format: "javascript".to_string(),
                    lines: 10,
                }],
                largest_files: vec![],
            },
            duplication: DuplicationView {
                percentage: 0.0,
                clones: 0,
                exact: 0,
                renamed: 0,
                similar: 0,
                formats: vec![],
            },
            complexity: ComplexityView {
                total: 0,
                mean: 0.0,
                files: vec![],
            },
            dead_code: None,
        }
    }

    /// A format name can come from `--formats-names`/`--formats-exts`, and a
    /// complexity file path is whatever the scanned repository named the
    /// file: both are untrusted text that must not break out of a Markdown
    /// table cell or survive as raw HTML.
    #[test]
    fn markdown_escapes_hostile_format_names_and_paths() {
        let mut view = sample_view();
        let hostile = "fmt|`<img src=x onerror=alert(1)>&\ninjected";
        view.project.formats[0].format = hostile.to_string();
        view.duplication.formats.push(FormatDuplication {
            format: hostile.to_string(),
            percentage: 50.0,
            duplicated_lines: 5,
            clones: 1,
        });
        view.project.largest_files.push(LargeFile {
            path: hostile.to_string(),
            format: "javascript".to_string(),
            lines: 5,
            tokens: 20,
            bytes: 100,
        });
        view.complexity.files.push(ComplexFile {
            path: hostile.to_string(),
            complexity: 10,
            lines: 5,
            bytes: 100,
        });

        let md = render_markdown(&view);
        for line in md.lines() {
            assert!(!line.contains("<img"), "raw HTML survived: {line}");
        }
        assert!(md.contains("fmt\\|`&lt;img"), "{md}");
        // The embedded newline did not start a new line of its own: every
        // occurrence of the hostile text keeps "injected" on the same line.
        for line in md.lines().filter(|l| l.contains("fmt")) {
            assert!(line.contains("injected"), "{line}");
        }
        assert!(!render_html(&view).contains("<img"), "raw HTML survived");
    }

    #[test]
    fn markdown_and_html_include_every_section() {
        let view = sample_view();
        let md = render_markdown(&view);
        for heading in [
            "## Health",
            "## Project",
            "## Duplication",
            "## Complexity",
            "## Dead code",
        ] {
            assert!(md.contains(heading), "{md}");
        }
        assert!(md.contains("not scored"), "{md}");

        let html = render_html(&view);
        for heading in [
            "<h2>Health</h2>",
            "<h2>Project</h2>",
            "<h2>Duplication</h2>",
            "<h2>Complexity</h2>",
            "<h2>Dead code",
        ] {
            assert!(html.contains(heading), "{html}");
        }
        assert!(html.contains("<html"), "{html}");
    }
}