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
// sarif.rs
// SARIF 2.1.0 reporter: writes jscpd-report.sarif.

use crate::context::ReportContext;
use crate::reporter::{Reporter, ReporterError, ReporterOptions};
use crate::rules::{self, rule_id};
use crate::shared::{Style, clean_source_id, clone_pair_hash, print_saved_report};
use cpd_core::models::CpdClone;
use serde_json::{Value, json};
use std::{collections::HashMap, fs, path::Path};

/// The description of each rule: `(id, short, full)`, in the order the
/// driver declares them.
const RULES: [(&str, &str, &str); 5] = [
    (
        rules::DUPLICATE,
        "Duplicated code detected",
        "Duplicate sections of code increase the risk of development errors, especially if fixes are made to one code block but not the other. Duplicates that share the same abstractions should be refactored into reusable helper methods as an application of the Don't Repeat Yourself principle.",
    ),
    (
        rules::RENAMED,
        "Renamed duplicate code detected",
        "Code blocks that are identical after renaming identifiers, literals or annotations (Type-2 clones). They carry the same maintenance risk as exact duplicates and usually indicate a missing abstraction.",
    ),
    (
        rules::SIMILAR,
        "Similar code detected",
        "Code blocks that match except for a few inserted, removed or changed lines (Type-3 clones): exact matches merged across a gap of at most --max-gap-lines lines. The similarity property holds the matched tokens over the merged span.",
    ),
    (
        rules::SIMILAR_FUNCTION,
        "Functions with a similar structure detected",
        "JavaScript/TypeScript functions whose syntax-tree structure overlaps by at least --similarity (Type-3 clones found by structure rather than by a token run). The similarity property holds the weighted Jaccard index of the two functions' node-type shingles; names and literal values are not part of it.",
    ),
    (
        rules::SEMANTIC,
        "Semantically similar code detected",
        "Functions that appear to do the same thing written differently, possibly in different languages (Type-4 clones, --semantic, experimental). Found by comparing embeddings of the functions' code: each function is the other's closest match and their cosine similarity, held in the similarity property, reaches the configured threshold. Review before refactoring; an embedding model can pair functions that are related without being duplicates.",
    ),
];

fn rule_json(id: &str, short: &str, full: &str) -> Value {
    json!({
        "id": id,
        "name": id,
        "shortDescription": { "text": short },
        "fullDescription": { "text": full },
        "defaultConfiguration": { "enabled": true, "level": "warning" },
        "helpUri": "https://github.com/kucherenko/jscpd/",
        "properties": { "tags": [ "quality" ], "problem.severity": "warning" }
    })
}

pub struct SarifReporter {
    blame: bool,
    style: Style,
    tool_version: String,
    error_tokens: Option<u32>,
    threshold: Option<f64>,
}

impl SarifReporter {
    pub fn new(opts: &ReporterOptions) -> Self {
        Self {
            blame: opts.blame,
            style: Style::new(opts.no_colors),
            tool_version: opts.tool_version.clone(),
            error_tokens: opts.sarif_error_tokens,
            threshold: opts.threshold,
        }
    }

    /// Severity for one clone: "error" when the clone is new relative to the
    /// baseline, when it reaches the configured token cutoff, or when the run
    /// as a whole exceeded the duplication threshold (`over_threshold` — same
    /// strictly-greater comparison the ThresholdReporter fails the build
    /// with); "warning" otherwise.
    fn level(&self, clone: &CpdClone, over_threshold: bool) -> &'static str {
        if over_threshold || clone.is_new {
            return "error";
        }
        match self.error_tokens {
            Some(cutoff) if clone.token_count >= cutoff => "error",
            _ => "warning",
        }
    }
}

fn make_region(frag: &cpd_core::models::Fragment) -> Value {
    json!({
        "startLine": frag.start.line,
        "startColumn": frag.start.column + 1,
        "endLine": frag.end.line,
        "endColumn": frag.end.column + 1,
    })
}

// Use the full scan-root-relative path, not just the file name: basenames
// like mod.rs or index.ts are ambiguous, and this matches the adjacent
// artifactLocation.uri.
fn make_file_and_line_string(frag: &cpd_core::models::Fragment) -> String {
    format!("{}:{}", clean_source_id(&frag.source_id), frag.start.line)
}

impl Reporter for SarifReporter {
    fn name(&self) -> &str {
        "sarif"
    }

    fn report(
        &self,
        clones: &[CpdClone],
        ctx: &ReportContext,
        output_dir: &Path,
    ) -> Result<(), ReporterError> {
        fs::create_dir_all(output_dir)?;
        let path = output_dir.join("jscpd-report.sarif");

        let over_threshold = self
            .threshold
            .is_some_and(|t| ctx.stats.total.percentage > t);

        // Artifact identity: (source_root, cleaned source_id) so that the same
        // relative path under two scan roots gets distinct artifact entries.
        let mut seen_artifacts: Vec<(Option<String>, String)> = Vec::new();
        let mut root_to_base_id: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();

        let make_artifact_loc = |frag: &cpd_core::models::Fragment,
                                 seen: &mut Vec<(Option<String>, String)>,
                                 roots: &mut std::collections::HashMap<String, String>|
         -> Value {
            let uri = clean_source_id(&frag.source_id).to_string();
            let key = (frag.source_root.clone(), uri.clone());
            let idx = match seen.iter().position(|k| *k == key) {
                Some(i) => i,
                None => {
                    seen.push(key);
                    seen.len() - 1
                }
            };
            let mut loc = json!({ "uri": uri, "index": idx });
            if let Some(ref root) = frag.source_root {
                let next_id = roots.len();
                let base_id = roots
                    .entry(root.clone())
                    .or_insert_with(|| {
                        if next_id == 0 {
                            "%SRCROOT%".to_string()
                        } else {
                            format!("%SRCROOT{}%", next_id)
                        }
                    })
                    .clone();
                loc["uriBaseId"] = json!(base_id);
            }
            loc
        };
        let mut file_cache: HashMap<String, String> = HashMap::new();

        let results: Vec<Value> = clones.iter().map(|clone| {
            let loc_a = make_artifact_loc(&clone.fragment_a, &mut seen_artifacts, &mut root_to_base_id);
            let loc_b = make_artifact_loc(&clone.fragment_b, &mut seen_artifacts, &mut root_to_base_id);

            let clone_hash = clone_pair_hash(&mut file_cache, clone);
            let mut props = json!({
                "token_count": clone.token_count,
            });
            if let Some(similarity) = clone.similarity_rounded() {
                props["similarity"] = json!(similarity);
            }
            if let Some(method) = clone.similarity_method {
                props["similarity_method"] = json!(method.as_str());
            }
            if let Some(hash) = &clone_hash {
                props["clone_hash"] = json!(hash);
            }
            if self.blame
                && let Some(blame) = &clone.fragment_a.blame {
                    props["blame"] = json!({
                        "sha": blame.commit_sha,
                        "author": blame.author,
                        "timestamp": blame.timestamp,
                    });
                }

            let mut result = json!({
                "ruleId": rule_id(clone),
                "level": self.level(clone, over_threshold),
                // The embedded link [text](0) references relatedLocations id 0 —
                // GitHub code scanning only surfaces related locations that the
                // primary message links to this way.
                "message": { "text": format!(
                    "Duplicated code block ({} tokens), duplicated at [{}](0)",
                    clone.token_count,
                    make_file_and_line_string(&clone.fragment_b)
                ) },
                "locations": [{
                    "physicalLocation": {
                        "artifactLocation": loc_a,
                        "region": make_region(&clone.fragment_a),
                    }
                }],
                "relatedLocations": [{
                    "id": 0,
                    "message": { "text": format!("Duplicated at {}", make_file_and_line_string(&clone.fragment_b)) },
                    "physicalLocation": {
                        "artifactLocation": loc_b,
                        "region": make_region(&clone.fragment_b),
                    }
                }],
                "properties": props,
            });
            // GitHub code scanning and other SARIF consumers use partialFingerprints
            // for result identity across runs; the properties bag alone is opaque to them.
            if let Some(hash) = clone_hash {
                result["partialFingerprints"] = json!({ "jscpdCloneHash/v1": hash });
            }
            result
        }).collect();

        let artifacts: Vec<Value> = seen_artifacts
            .iter()
            .map(|(root, uri)| {
                let mut loc = json!({ "uri": uri });
                if let Some(root) = root
                    && let Some(base_id) = root_to_base_id.get(root)
                {
                    loc["uriBaseId"] = json!(base_id);
                }
                json!({ "location": loc })
            })
            .collect();

        let mut original_uri_base_ids = json!({});
        for (root, base_id) in &root_to_base_id {
            let uri = if root.starts_with('/') {
                format!("file://{}/", root)
            } else {
                let mut s = root.clone();
                if !s.ends_with('\\') && !s.ends_with('/') {
                    s.push('\\');
                }
                s
            };
            original_uri_base_ids[base_id] = json!({ "uri": uri });
        }

        // The duplicate-code rule is always declared; the others only when a
        // clone references them, so default runs keep their single-rule driver.
        let rules: Vec<Value> = RULES
            .iter()
            .filter(|(id, _, _)| {
                *id == rules::DUPLICATE || clones.iter().any(|c| rule_id(c) == *id)
            })
            .map(|(id, short, full)| rule_json(id, short, full))
            .collect();
        let mut run = json!({
            "tool": {
                "driver": {
                    "name": "jscpd",
                    "version": self.tool_version,
                    "informationUri": "https://github.com/kucherenko/jscpd/",
                    "rules": rules
                }
            },
            "artifacts": artifacts,
            "results": results,
        });
        if !root_to_base_id.is_empty() {
            run["originalUriBaseIds"] = original_uri_base_ids;
        }

        let sarif = json!({
            "version": "2.1.0",
            "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
            "runs": [run]
        });

        let content = serde_json::to_string_pretty(&sarif)
            .map_err(|e| ReporterError::Format(e.to_string()))?;
        fs::write(&path, content)?;
        print_saved_report(&self.style, "SARIF", &path);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::reporter::ReporterOptions;
    use crate::shared::fixtures::{empty_ctx, report_to_file, stats_with_pct, tmp_dir};
    use cpd_core::models::{BlameEntry, CloneKind, CpdClone, Fragment, Location, SimilarityMethod};

    fn make_clone() -> CpdClone {
        let loc = Location {
            line: 10,
            column: 0,
            offset: 0,
        };
        let end = Location {
            line: 20,
            column: 0,
            offset: 0,
        };
        let blame = BlameEntry {
            commit_sha: "deadbeef".to_string(),
            author: "Bob".to_string(),
            timestamp: 1_700_000_000,
        };
        CpdClone {
            format: "rust".to_string(),
            fragment_a: Fragment::new("src/foo.rs", loc.clone(), end.clone(), [0, 100])
                .with_blame(blame),
            fragment_b: Fragment::new("src/bar.rs", loc, end, [0, 100]),
            token_count: 80,
            is_new: false,
            kind: Default::default(),
            similarity: None,
            similarity_method: None,
            unmatched_lines: [0, 0],
        }
    }

    /// Write source fixtures into a fresh temp dir and point the clone's
    /// fragments at them via absolute paths, so tests never touch the
    /// crate's real `src/` tree and parallel tests cannot race on files.
    fn write_test_sources(clone: &mut CpdClone, num_lines: u32) {
        let dir = tmp_dir("sarif-src");
        let lines = (1..=num_lines)
            .map(|i| format!("line {}", i))
            .collect::<Vec<_>>()
            .join("\n");

        for fragment in [&mut clone.fragment_a, &mut clone.fragment_b] {
            let name = std::path::Path::new(&fragment.source_id)
                .file_name()
                .unwrap()
                .to_owned();
            let path = dir.join(name);
            fs::write(&path, &lines).unwrap();
            fragment.source_id = path.to_string_lossy().into_owned();
        }
    }

    /// Rule ids declared by the run, in order.
    fn rule_ids(parsed: &serde_json::Value) -> Vec<String> {
        parsed["runs"][0]["tool"]["driver"]["rules"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r["id"].as_str().unwrap().to_string())
            .collect()
    }

    /// `properties` of the first result of a report over `clones`.
    fn first_result_properties(clones: &[CpdClone]) -> serde_json::Value {
        let content = run_sarif_report(clones, false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        parsed["runs"][0]["results"][0]["properties"].clone()
    }

    fn run_sarif_report(clones: &[CpdClone], blame: bool) -> String {
        let dir = tmp_dir("sarif");
        let mut opts = ReporterOptions::new(dir.clone());
        opts.blame = blame;
        let reporter = SarifReporter::new(&opts);
        let ctx = empty_ctx();
        reporter.report(clones, &ctx, &dir).unwrap();
        std::fs::read_to_string(dir.join("jscpd-report.sarif")).unwrap()
    }

    #[test]
    fn sarif_version_is_2_1_0() {
        let content = run_sarif_report(&[], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed["version"], "2.1.0");
    }

    #[test]
    fn sarif_output_has_runs_and_results() {
        let content = run_sarif_report(&[make_clone()], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert!(parsed["runs"][0]["results"].is_array());
        assert_eq!(parsed["runs"][0]["results"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn sarif_renamed_clone_uses_renamed_code_rule_and_declares_it() {
        let mut renamed = make_clone();
        renamed.kind = CloneKind::Renamed;
        let content = run_sarif_report(&[renamed, make_clone()], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let results = parsed["runs"][0]["results"].as_array().unwrap();
        assert_eq!(results[0]["ruleId"], "jscpd/renamed-code");
        assert_eq!(results[1]["ruleId"], "jscpd/duplicate-code");
        assert_eq!(
            rule_ids(&parsed),
            ["jscpd/duplicate-code", "jscpd/renamed-code"]
        );
    }

    /// A `similar` clone found by `method`, with `similarity`.
    fn similar_clone(method: SimilarityMethod, similarity: f32) -> CpdClone {
        let mut similar = make_clone();
        similar.kind = CloneKind::Similar;
        similar.similarity = Some(similarity);
        similar.similarity_method = Some(method);
        similar
    }

    #[test]
    fn sarif_merged_clone_uses_similar_code_rule_with_similarity_property() {
        let content = run_sarif_report(&[similar_clone(SimilarityMethod::Gap, 0.85)], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let result = &parsed["runs"][0]["results"][0];
        assert_eq!(result["ruleId"], "jscpd/similar-code");
        assert_eq!(result["properties"]["similarity"], 0.85);
        assert_eq!(result["properties"]["similarity_method"], "gap");
        assert_eq!(
            rule_ids(&parsed),
            ["jscpd/duplicate-code", "jscpd/similar-code"]
        );
    }

    #[test]
    fn sarif_similar_functions_use_their_own_rule() {
        let content = run_sarif_report(&[similar_clone(SimilarityMethod::Ast, 0.9)], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let result = &parsed["runs"][0]["results"][0];
        assert_eq!(result["ruleId"], "jscpd/similar-function");
        assert_eq!(result["properties"]["similarity"], 0.9);
        assert_eq!(result["properties"]["similarity_method"], "ast");
        assert_eq!(
            rule_ids(&parsed),
            ["jscpd/duplicate-code", "jscpd/similar-function"]
        );
    }

    #[test]
    fn sarif_declares_both_similar_rules_when_both_mechanisms_found_clones() {
        let content = run_sarif_report(
            &[
                similar_clone(SimilarityMethod::Ast, 0.9),
                similar_clone(SimilarityMethod::Gap, 0.85),
            ],
            false,
        );
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(
            rule_ids(&parsed),
            [
                "jscpd/duplicate-code",
                "jscpd/similar-code",
                "jscpd/similar-function"
            ]
        );
    }

    #[test]
    fn sarif_semantic_clone_uses_semantic_code_rule_with_similarity_property() {
        let mut semantic = make_clone();
        semantic.kind = CloneKind::Semantic;
        semantic.similarity = Some(0.781);
        let content = run_sarif_report(&[semantic], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let result = &parsed["runs"][0]["results"][0];
        assert_eq!(result["ruleId"], "jscpd/semantic-code");
        assert_eq!(result["properties"]["similarity"], 0.781);
        assert!(result["properties"].get("similarity_method").is_none());
        assert_eq!(
            rule_ids(&parsed),
            ["jscpd/duplicate-code", "jscpd/semantic-code"]
        );
    }

    #[test]
    fn sarif_exact_only_run_declares_a_single_rule() {
        let content = run_sarif_report(&[make_clone()], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let rules = parsed["runs"][0]["tool"]["driver"]["rules"]
            .as_array()
            .unwrap();
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0]["id"], "jscpd/duplicate-code");
    }

    #[test]
    fn sarif_new_clone_is_error_level() {
        let mut clone = make_clone();
        clone.is_new = true;
        let content = run_sarif_report(&[clone, make_clone()], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let results = parsed["runs"][0]["results"].as_array().unwrap();
        assert_eq!(results[0]["level"], "error", "new clone must be error");
        assert_eq!(results[1]["level"], "warning", "known clone stays warning");
    }

    #[test]
    fn sarif_related_locations_have_messages_that_reference_the_location() {
        let content = run_sarif_report(&[make_clone()], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();

        let result = &parsed["runs"][0]["results"][0];
        let message = &result["relatedLocations"][0]["message"];
        assert!(
            message.is_object(),
            "related location should include a message"
        );
        assert_eq!(
            message["text"], "Duplicated at src/bar.rs:10",
            "related location message should use the full relative path"
        );
        let primary = result["message"]["text"].as_str().unwrap();
        assert!(
            primary.contains("duplicated at [src/bar.rs:10](0)"),
            "primary message must reference relatedLocations id 0 via an embedded link, got: {primary}"
        );
    }

    #[test]
    fn sarif_blame_included_when_flag_set() {
        let content = run_sarif_report(&[make_clone()], true);
        assert!(
            content.contains("deadbeef"),
            "SARIF must include blame SHA when blame=true"
        );
    }

    #[test]
    fn sarif_result_includes_clone_hash_property() {
        let mut clone = make_clone();
        write_test_sources(&mut clone, 25);

        let content = run_sarif_report(&[clone], false);
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        let result = &parsed["runs"][0]["results"][0];
        let properties = &result["properties"];
        assert!(
            properties["clone_hash"].is_string(),
            "clone_hash must be present and be a string"
        );
        let hash = properties["clone_hash"].as_str().unwrap();
        assert_eq!(hash.len(), 16, "clone_hash must be 16-char hex string");
        assert!(
            hash.chars().all(|c| c.is_ascii_hexdigit()),
            "clone_hash must be hex"
        );
        assert_eq!(
            result["partialFingerprints"]["jscpdCloneHash/v1"], *hash,
            "partialFingerprints must carry the same hash"
        );
    }

    #[test]
    fn sarif_clone_hash_is_stable_across_fragment_order() {
        let mut clone = make_clone();
        write_test_sources(&mut clone, 25);
        let mut swapped = clone.clone();
        std::mem::swap(&mut swapped.fragment_a, &mut swapped.fragment_b);

        let extract_hash = |content: &str| -> String {
            let parsed: serde_json::Value = serde_json::from_str(content).unwrap();
            parsed["runs"][0]["results"][0]["properties"]["clone_hash"]
                .as_str()
                .unwrap()
                .to_string()
        };
        let hash_ab = extract_hash(&run_sarif_report(&[clone], false));
        let hash_ba = extract_hash(&run_sarif_report(&[swapped], false));
        assert_eq!(
            hash_ab, hash_ba,
            "clone_hash must not depend on which copy is fragment A"
        );
    }

    #[test]
    fn sarif_result_excludes_clone_hash_when_snippets_empty() {
        let mut clone = make_clone();
        clone.fragment_a.source_id = "nonexistent-a.rs".to_string();
        clone.fragment_b.source_id = "nonexistent-b.rs".to_string();

        let properties = first_result_properties(&[clone]);
        assert!(
            properties["clone_hash"].is_null(),
            "clone_hash must not be present when snippet is empty"
        );
    }

    #[test]
    fn sarif_result_includes_token_count_property() {
        let properties = first_result_properties(&[make_clone()]);

        assert!(
            properties["token_count"].is_number(),
            "token_count must be present and be a number"
        );
        assert_eq!(
            properties["token_count"], 80,
            "token_count must match clone token count"
        );
    }

    fn result_level_with_ctx(
        clones: &[CpdClone],
        error_tokens: Option<u32>,
        threshold: Option<f64>,
        total_pct: f64,
    ) -> String {
        let content = report_to_file(
            "sarif",
            "jscpd-report.sarif",
            clones,
            &stats_with_pct(total_pct, total_pct as u64),
            |opts| {
                opts.sarif_error_tokens = error_tokens;
                opts.threshold = threshold;
            },
            SarifReporter::new,
        );
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        parsed["runs"][0]["results"][0]["level"]
            .as_str()
            .unwrap()
            .to_string()
    }

    fn result_level(clones: &[CpdClone], error_tokens: Option<u32>) -> String {
        result_level_with_ctx(clones, error_tokens, None, 0.0)
    }

    #[test]
    fn sarif_level_is_warning_without_error_cutoff() {
        // make_clone() has 80 tokens
        assert_eq!(result_level(&[make_clone()], None), "warning");
    }

    #[test]
    fn sarif_level_is_error_at_or_above_cutoff() {
        assert_eq!(
            result_level(&[make_clone()], Some(80)),
            "error",
            "a clone exactly at the cutoff must be an error"
        );
        assert_eq!(result_level(&[make_clone()], Some(10)), "error");
    }

    #[test]
    fn sarif_level_stays_warning_below_cutoff() {
        assert_eq!(result_level(&[make_clone()], Some(81)), "warning");
    }

    #[test]
    fn sarif_level_is_error_when_threshold_exceeded() {
        // 25% duplication > 20% threshold: every result escalates,
        // even though the clone is below the token cutoff.
        assert_eq!(
            result_level_with_ctx(&[make_clone()], Some(1000), Some(20.0), 25.0),
            "error"
        );
        assert_eq!(
            result_level_with_ctx(&[make_clone()], None, Some(20.0), 25.0),
            "error"
        );
    }

    #[test]
    fn sarif_level_stays_warning_at_or_below_threshold() {
        // Same strictly-greater semantics as the ThresholdReporter:
        // equal to the threshold does not fail the build, so it must
        // not escalate severity either.
        assert_eq!(
            result_level_with_ctx(&[make_clone()], None, Some(20.0), 20.0),
            "warning"
        );
        assert_eq!(
            result_level_with_ctx(&[make_clone()], None, Some(20.0), 10.0),
            "warning"
        );
    }

    #[test]
    fn sarif_tool_version_comes_from_options() {
        let dir = tmp_dir("sarif");
        let mut opts = ReporterOptions::new(dir.clone());
        opts.tool_version = "9.9.9-test".to_string();
        let reporter = SarifReporter::new(&opts);
        reporter.report(&[], &empty_ctx(), &dir).unwrap();
        let content = std::fs::read_to_string(dir.join("jscpd-report.sarif")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(
            parsed["runs"][0]["tool"]["driver"]["version"], "9.9.9-test",
            "driver.version must come from ReporterOptions.tool_version, not a hardcoded string"
        );
    }

    #[test]
    fn sarif_reporter_name_is_sarif() {
        let opts = ReporterOptions::new(std::path::PathBuf::from("/tmp"));
        assert_eq!(SarifReporter::new(&opts).name(), "sarif");
    }
}