Skip to main content

fallow_cli/report/
sarif.rs

1use std::path::Path;
2use std::process::ExitCode;
3
4use fallow_config::{RulesConfig, Severity};
5use fallow_core::duplicates::DuplicationReport;
6use fallow_core::results::{AnalysisResults, UnusedDependency, UnusedExport, UnusedMember};
7
8use super::relative_uri;
9
10/// Intermediate fields extracted from an issue for SARIF result construction.
11struct SarifFields {
12    rule_id: &'static str,
13    level: &'static str,
14    message: String,
15    uri: String,
16    region: Option<(u32, u32)>,
17    properties: Option<serde_json::Value>,
18}
19
20const fn severity_to_sarif_level(s: Severity) -> &'static str {
21    match s {
22        Severity::Error => "error",
23        Severity::Warn | Severity::Off => "warning",
24    }
25}
26
27/// Build a single SARIF result object.
28///
29/// When `region` is `Some((line, col))`, a `region` block with 1-based
30/// `startLine` and `startColumn` is included in the physical location.
31fn sarif_result(
32    rule_id: &str,
33    level: &str,
34    message: &str,
35    uri: &str,
36    region: Option<(u32, u32)>,
37) -> serde_json::Value {
38    let mut physical_location = serde_json::json!({
39        "artifactLocation": { "uri": uri }
40    });
41    if let Some((line, col)) = region {
42        physical_location["region"] = serde_json::json!({
43            "startLine": line,
44            "startColumn": col
45        });
46    }
47    serde_json::json!({
48        "ruleId": rule_id,
49        "level": level,
50        "message": { "text": message },
51        "locations": [{ "physicalLocation": physical_location }]
52    })
53}
54
55/// Append SARIF results for a slice of items using a closure to extract fields.
56fn push_sarif_results<T>(
57    sarif_results: &mut Vec<serde_json::Value>,
58    items: &[T],
59    extract: impl Fn(&T) -> SarifFields,
60) {
61    for item in items {
62        let fields = extract(item);
63        let mut result = sarif_result(
64            fields.rule_id,
65            fields.level,
66            &fields.message,
67            &fields.uri,
68            fields.region,
69        );
70        if let Some(props) = fields.properties {
71            result["properties"] = props;
72        }
73        sarif_results.push(result);
74    }
75}
76
77pub fn build_sarif(
78    results: &AnalysisResults,
79    root: &Path,
80    rules: &RulesConfig,
81) -> serde_json::Value {
82    let mut sarif_results = Vec::new();
83
84    push_sarif_results(&mut sarif_results, &results.unused_files, |file| {
85        SarifFields {
86            rule_id: "fallow/unused-file",
87            level: severity_to_sarif_level(rules.unused_files),
88            message: "File is not reachable from any entry point".to_string(),
89            uri: relative_uri(&file.path, root),
90            region: None,
91            properties: None,
92        }
93    });
94
95    let sarif_export = |export: &UnusedExport,
96                        rule_id: &'static str,
97                        level: &'static str,
98                        kind: &str,
99                        re_kind: &str|
100     -> SarifFields {
101        let label = if export.is_re_export { re_kind } else { kind };
102        SarifFields {
103            rule_id,
104            level,
105            message: format!(
106                "{} '{}' is never imported by other modules",
107                label, export.export_name
108            ),
109            uri: relative_uri(&export.path, root),
110            region: Some((export.line, export.col + 1)),
111            properties: if export.is_re_export {
112                Some(serde_json::json!({ "is_re_export": true }))
113            } else {
114                None
115            },
116        }
117    };
118
119    push_sarif_results(&mut sarif_results, &results.unused_exports, |export| {
120        sarif_export(
121            export,
122            "fallow/unused-export",
123            severity_to_sarif_level(rules.unused_exports),
124            "Export",
125            "Re-export",
126        )
127    });
128
129    push_sarif_results(&mut sarif_results, &results.unused_types, |export| {
130        sarif_export(
131            export,
132            "fallow/unused-type",
133            severity_to_sarif_level(rules.unused_types),
134            "Type export",
135            "Type re-export",
136        )
137    });
138
139    let sarif_dep = |dep: &UnusedDependency,
140                     rule_id: &'static str,
141                     level: &'static str,
142                     section: &str|
143     -> SarifFields {
144        SarifFields {
145            rule_id,
146            level,
147            message: format!(
148                "Package '{}' is in {} but never imported",
149                dep.package_name, section
150            ),
151            uri: relative_uri(&dep.path, root),
152            region: if dep.line > 0 {
153                Some((dep.line, 1))
154            } else {
155                None
156            },
157            properties: None,
158        }
159    };
160
161    push_sarif_results(&mut sarif_results, &results.unused_dependencies, |dep| {
162        sarif_dep(
163            dep,
164            "fallow/unused-dependency",
165            severity_to_sarif_level(rules.unused_dependencies),
166            "dependencies",
167        )
168    });
169
170    push_sarif_results(
171        &mut sarif_results,
172        &results.unused_dev_dependencies,
173        |dep| {
174            sarif_dep(
175                dep,
176                "fallow/unused-dev-dependency",
177                severity_to_sarif_level(rules.unused_dev_dependencies),
178                "devDependencies",
179            )
180        },
181    );
182
183    push_sarif_results(
184        &mut sarif_results,
185        &results.unused_optional_dependencies,
186        |dep| {
187            sarif_dep(
188                dep,
189                "fallow/unused-optional-dependency",
190                severity_to_sarif_level(rules.unused_optional_dependencies),
191                "optionalDependencies",
192            )
193        },
194    );
195
196    push_sarif_results(&mut sarif_results, &results.type_only_dependencies, |dep| {
197        SarifFields {
198            rule_id: "fallow/type-only-dependency",
199            level: severity_to_sarif_level(rules.type_only_dependencies),
200            message: format!(
201                "Package '{}' is only imported via type-only imports (consider moving to devDependencies)",
202                dep.package_name
203            ),
204            uri: relative_uri(&dep.path, root),
205            region: if dep.line > 0 {
206                Some((dep.line, 1))
207            } else {
208                None
209            },
210            properties: None,
211        }
212    });
213
214    let sarif_member = |member: &UnusedMember,
215                        rule_id: &'static str,
216                        level: &'static str,
217                        kind: &str|
218     -> SarifFields {
219        SarifFields {
220            rule_id,
221            level,
222            message: format!(
223                "{} member '{}.{}' is never referenced",
224                kind, member.parent_name, member.member_name
225            ),
226            uri: relative_uri(&member.path, root),
227            region: Some((member.line, member.col + 1)),
228            properties: None,
229        }
230    };
231
232    push_sarif_results(&mut sarif_results, &results.unused_enum_members, |member| {
233        sarif_member(
234            member,
235            "fallow/unused-enum-member",
236            severity_to_sarif_level(rules.unused_enum_members),
237            "Enum",
238        )
239    });
240
241    push_sarif_results(
242        &mut sarif_results,
243        &results.unused_class_members,
244        |member| {
245            sarif_member(
246                member,
247                "fallow/unused-class-member",
248                severity_to_sarif_level(rules.unused_class_members),
249                "Class",
250            )
251        },
252    );
253
254    push_sarif_results(&mut sarif_results, &results.unresolved_imports, |import| {
255        SarifFields {
256            rule_id: "fallow/unresolved-import",
257            level: severity_to_sarif_level(rules.unresolved_imports),
258            message: format!("Import '{}' could not be resolved", import.specifier),
259            uri: relative_uri(&import.path, root),
260            region: Some((import.line, import.col + 1)),
261            properties: None,
262        }
263    });
264
265    // Unlisted deps: one result per importing file (SARIF points to the import site)
266    for dep in &results.unlisted_dependencies {
267        for site in &dep.imported_from {
268            sarif_results.push(sarif_result(
269                "fallow/unlisted-dependency",
270                severity_to_sarif_level(rules.unlisted_dependencies),
271                &format!(
272                    "Package '{}' is imported but not listed in package.json",
273                    dep.package_name
274                ),
275                &relative_uri(&site.path, root),
276                Some((site.line, site.col + 1)),
277            ));
278        }
279    }
280
281    // Duplicate exports: one result per location (SARIF 2.1.0 section 3.27.12)
282    for dup in &results.duplicate_exports {
283        for loc in &dup.locations {
284            sarif_results.push(sarif_result(
285                "fallow/duplicate-export",
286                severity_to_sarif_level(rules.duplicate_exports),
287                &format!("Export '{}' appears in multiple modules", dup.export_name),
288                &relative_uri(&loc.path, root),
289                Some((loc.line, loc.col + 1)),
290            ));
291        }
292    }
293
294    push_sarif_results(
295        &mut sarif_results,
296        &results.circular_dependencies,
297        |cycle| {
298            let chain: Vec<String> = cycle.files.iter().map(|p| relative_uri(p, root)).collect();
299            let mut display_chain = chain.clone();
300            if let Some(first) = chain.first() {
301                display_chain.push(first.clone());
302            }
303            let first_uri = chain.first().map_or_else(String::new, Clone::clone);
304            SarifFields {
305                rule_id: "fallow/circular-dependency",
306                level: severity_to_sarif_level(rules.circular_dependencies),
307                message: format!("Circular dependency: {}", display_chain.join(" \u{2192} ")),
308                uri: first_uri,
309                region: if cycle.line > 0 {
310                    Some((cycle.line, cycle.col + 1))
311                } else {
312                    None
313                },
314                properties: None,
315            }
316        },
317    );
318
319    serde_json::json!({
320        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
321        "version": "2.1.0",
322        "runs": [{
323            "tool": {
324                "driver": {
325                    "name": "fallow",
326                    "version": env!("CARGO_PKG_VERSION"),
327                    "informationUri": "https://github.com/fallow-rs/fallow",
328                    "rules": [
329                        {
330                            "id": "fallow/unused-file",
331                            "shortDescription": { "text": "File is not reachable from any entry point" },
332                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_files) }
333                        },
334                        {
335                            "id": "fallow/unused-export",
336                            "shortDescription": { "text": "Export is never imported" },
337                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_exports) }
338                        },
339                        {
340                            "id": "fallow/unused-type",
341                            "shortDescription": { "text": "Type export is never imported" },
342                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_types) }
343                        },
344                        {
345                            "id": "fallow/unused-dependency",
346                            "shortDescription": { "text": "Dependency listed but never imported" },
347                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_dependencies) }
348                        },
349                        {
350                            "id": "fallow/unused-dev-dependency",
351                            "shortDescription": { "text": "Dev dependency listed but never imported" },
352                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_dev_dependencies) }
353                        },
354                        {
355                            "id": "fallow/unused-optional-dependency",
356                            "shortDescription": { "text": "Optional dependency listed but never imported" },
357                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_optional_dependencies) }
358                        },
359                        {
360                            "id": "fallow/type-only-dependency",
361                            "shortDescription": { "text": "Production dependency only used via type-only imports" },
362                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.type_only_dependencies) }
363                        },
364                        {
365                            "id": "fallow/unused-enum-member",
366                            "shortDescription": { "text": "Enum member is never referenced" },
367                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_enum_members) }
368                        },
369                        {
370                            "id": "fallow/unused-class-member",
371                            "shortDescription": { "text": "Class member is never referenced" },
372                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unused_class_members) }
373                        },
374                        {
375                            "id": "fallow/unresolved-import",
376                            "shortDescription": { "text": "Import could not be resolved" },
377                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unresolved_imports) }
378                        },
379                        {
380                            "id": "fallow/unlisted-dependency",
381                            "shortDescription": { "text": "Dependency used but not in package.json" },
382                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.unlisted_dependencies) }
383                        },
384                        {
385                            "id": "fallow/duplicate-export",
386                            "shortDescription": { "text": "Export name appears in multiple modules" },
387                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.duplicate_exports) }
388                        },
389                        {
390                            "id": "fallow/circular-dependency",
391                            "shortDescription": { "text": "Circular dependency chain detected" },
392                            "defaultConfiguration": { "level": severity_to_sarif_level(rules.circular_dependencies) }
393                        }
394                    ]
395                }
396            },
397            "results": sarif_results
398        }]
399    })
400}
401
402pub(super) fn print_sarif(results: &AnalysisResults, root: &Path, rules: &RulesConfig) -> ExitCode {
403    let sarif = build_sarif(results, root, rules);
404    match serde_json::to_string_pretty(&sarif) {
405        Ok(json) => {
406            println!("{json}");
407            ExitCode::SUCCESS
408        }
409        Err(e) => {
410            eprintln!("Error: failed to serialize SARIF output: {e}");
411            ExitCode::from(2)
412        }
413    }
414}
415
416pub(super) fn print_duplication_sarif(report: &DuplicationReport, root: &Path) -> ExitCode {
417    let mut sarif_results = Vec::new();
418
419    for (i, group) in report.clone_groups.iter().enumerate() {
420        for instance in &group.instances {
421            sarif_results.push(sarif_result(
422                "fallow/code-duplication",
423                "warning",
424                &format!(
425                    "Code clone group {} ({} lines, {} instances)",
426                    i + 1,
427                    group.line_count,
428                    group.instances.len()
429                ),
430                &relative_uri(&instance.file, root),
431                Some((instance.start_line as u32, (instance.start_col + 1) as u32)),
432            ));
433        }
434    }
435
436    let sarif = serde_json::json!({
437        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
438        "version": "2.1.0",
439        "runs": [{
440            "tool": {
441                "driver": {
442                    "name": "fallow",
443                    "version": env!("CARGO_PKG_VERSION"),
444                    "informationUri": "https://github.com/fallow-rs/fallow",
445                    "rules": [{
446                        "id": "fallow/code-duplication",
447                        "shortDescription": { "text": "Duplicated code block" },
448                        "defaultConfiguration": { "level": "warning" }
449                    }]
450                }
451            },
452            "results": sarif_results
453        }]
454    });
455
456    match serde_json::to_string_pretty(&sarif) {
457        Ok(json) => {
458            println!("{json}");
459            ExitCode::SUCCESS
460        }
461        Err(e) => {
462            eprintln!("Error: failed to serialize SARIF output: {e}");
463            ExitCode::from(2)
464        }
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use fallow_core::extract::MemberKind;
472    use fallow_core::results::*;
473    use std::path::PathBuf;
474
475    /// Helper: build an `AnalysisResults` populated with one issue of every type.
476    fn sample_results(root: &Path) -> AnalysisResults {
477        let mut r = AnalysisResults::default();
478
479        r.unused_files.push(UnusedFile {
480            path: root.join("src/dead.ts"),
481        });
482        r.unused_exports.push(UnusedExport {
483            path: root.join("src/utils.ts"),
484            export_name: "helperFn".to_string(),
485            is_type_only: false,
486            line: 10,
487            col: 4,
488            span_start: 120,
489            is_re_export: false,
490        });
491        r.unused_types.push(UnusedExport {
492            path: root.join("src/types.ts"),
493            export_name: "OldType".to_string(),
494            is_type_only: true,
495            line: 5,
496            col: 0,
497            span_start: 60,
498            is_re_export: false,
499        });
500        r.unused_dependencies.push(UnusedDependency {
501            package_name: "lodash".to_string(),
502            location: DependencyLocation::Dependencies,
503            path: root.join("package.json"),
504            line: 5,
505        });
506        r.unused_dev_dependencies.push(UnusedDependency {
507            package_name: "jest".to_string(),
508            location: DependencyLocation::DevDependencies,
509            path: root.join("package.json"),
510            line: 5,
511        });
512        r.unused_enum_members.push(UnusedMember {
513            path: root.join("src/enums.ts"),
514            parent_name: "Status".to_string(),
515            member_name: "Deprecated".to_string(),
516            kind: MemberKind::EnumMember,
517            line: 8,
518            col: 2,
519        });
520        r.unused_class_members.push(UnusedMember {
521            path: root.join("src/service.ts"),
522            parent_name: "UserService".to_string(),
523            member_name: "legacyMethod".to_string(),
524            kind: MemberKind::ClassMethod,
525            line: 42,
526            col: 4,
527        });
528        r.unresolved_imports.push(UnresolvedImport {
529            path: root.join("src/app.ts"),
530            specifier: "./missing-module".to_string(),
531            line: 3,
532            col: 0,
533        });
534        r.unlisted_dependencies.push(UnlistedDependency {
535            package_name: "chalk".to_string(),
536            imported_from: vec![ImportSite {
537                path: root.join("src/cli.ts"),
538                line: 2,
539                col: 0,
540            }],
541        });
542        r.duplicate_exports.push(DuplicateExport {
543            export_name: "Config".to_string(),
544            locations: vec![
545                DuplicateLocation {
546                    path: root.join("src/config.ts"),
547                    line: 15,
548                    col: 0,
549                },
550                DuplicateLocation {
551                    path: root.join("src/types.ts"),
552                    line: 30,
553                    col: 0,
554                },
555            ],
556        });
557        r.type_only_dependencies.push(TypeOnlyDependency {
558            package_name: "zod".to_string(),
559            path: root.join("package.json"),
560            line: 8,
561        });
562        r.circular_dependencies.push(CircularDependency {
563            files: vec![root.join("src/a.ts"), root.join("src/b.ts")],
564            length: 2,
565            line: 3,
566            col: 0,
567        });
568
569        r
570    }
571
572    #[test]
573    fn sarif_has_required_top_level_fields() {
574        let root = PathBuf::from("/project");
575        let results = AnalysisResults::default();
576        let sarif = build_sarif(&results, &root, &RulesConfig::default());
577
578        assert_eq!(
579            sarif["$schema"],
580            "https://json.schemastore.org/sarif-2.1.0.json"
581        );
582        assert_eq!(sarif["version"], "2.1.0");
583        assert!(sarif["runs"].is_array());
584    }
585
586    #[test]
587    fn sarif_has_tool_driver_info() {
588        let root = PathBuf::from("/project");
589        let results = AnalysisResults::default();
590        let sarif = build_sarif(&results, &root, &RulesConfig::default());
591
592        let driver = &sarif["runs"][0]["tool"]["driver"];
593        assert_eq!(driver["name"], "fallow");
594        assert!(driver["version"].is_string());
595        assert_eq!(
596            driver["informationUri"],
597            "https://github.com/fallow-rs/fallow"
598        );
599    }
600
601    #[test]
602    fn sarif_declares_all_rules() {
603        let root = PathBuf::from("/project");
604        let results = AnalysisResults::default();
605        let sarif = build_sarif(&results, &root, &RulesConfig::default());
606
607        let rules = sarif["runs"][0]["tool"]["driver"]["rules"]
608            .as_array()
609            .expect("rules should be an array");
610        assert_eq!(rules.len(), 13);
611
612        let rule_ids: Vec<&str> = rules.iter().map(|r| r["id"].as_str().unwrap()).collect();
613        assert!(rule_ids.contains(&"fallow/unused-file"));
614        assert!(rule_ids.contains(&"fallow/unused-export"));
615        assert!(rule_ids.contains(&"fallow/unused-type"));
616        assert!(rule_ids.contains(&"fallow/unused-dependency"));
617        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
618        assert!(rule_ids.contains(&"fallow/unused-optional-dependency"));
619        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
620        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
621        assert!(rule_ids.contains(&"fallow/unused-class-member"));
622        assert!(rule_ids.contains(&"fallow/unresolved-import"));
623        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
624        assert!(rule_ids.contains(&"fallow/duplicate-export"));
625        assert!(rule_ids.contains(&"fallow/circular-dependency"));
626    }
627
628    #[test]
629    fn sarif_empty_results_no_results_entries() {
630        let root = PathBuf::from("/project");
631        let results = AnalysisResults::default();
632        let sarif = build_sarif(&results, &root, &RulesConfig::default());
633
634        let sarif_results = sarif["runs"][0]["results"]
635            .as_array()
636            .expect("results should be an array");
637        assert!(sarif_results.is_empty());
638    }
639
640    #[test]
641    fn sarif_unused_file_result() {
642        let root = PathBuf::from("/project");
643        let mut results = AnalysisResults::default();
644        results.unused_files.push(UnusedFile {
645            path: root.join("src/dead.ts"),
646        });
647
648        let sarif = build_sarif(&results, &root, &RulesConfig::default());
649        let entries = sarif["runs"][0]["results"].as_array().unwrap();
650        assert_eq!(entries.len(), 1);
651
652        let entry = &entries[0];
653        assert_eq!(entry["ruleId"], "fallow/unused-file");
654        // Default severity is "error" per RulesConfig::default()
655        assert_eq!(entry["level"], "error");
656        assert_eq!(
657            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
658            "src/dead.ts"
659        );
660    }
661
662    #[test]
663    fn sarif_unused_export_includes_region() {
664        let root = PathBuf::from("/project");
665        let mut results = AnalysisResults::default();
666        results.unused_exports.push(UnusedExport {
667            path: root.join("src/utils.ts"),
668            export_name: "helperFn".to_string(),
669            is_type_only: false,
670            line: 10,
671            col: 4,
672            span_start: 120,
673            is_re_export: false,
674        });
675
676        let sarif = build_sarif(&results, &root, &RulesConfig::default());
677        let entry = &sarif["runs"][0]["results"][0];
678        assert_eq!(entry["ruleId"], "fallow/unused-export");
679
680        let region = &entry["locations"][0]["physicalLocation"]["region"];
681        assert_eq!(region["startLine"], 10);
682        // SARIF columns are 1-based, code adds +1 to the 0-based col
683        assert_eq!(region["startColumn"], 5);
684    }
685
686    #[test]
687    fn sarif_unresolved_import_is_error_level() {
688        let root = PathBuf::from("/project");
689        let mut results = AnalysisResults::default();
690        results.unresolved_imports.push(UnresolvedImport {
691            path: root.join("src/app.ts"),
692            specifier: "./missing".to_string(),
693            line: 1,
694            col: 0,
695        });
696
697        let sarif = build_sarif(&results, &root, &RulesConfig::default());
698        let entry = &sarif["runs"][0]["results"][0];
699        assert_eq!(entry["ruleId"], "fallow/unresolved-import");
700        assert_eq!(entry["level"], "error");
701    }
702
703    #[test]
704    fn sarif_unlisted_dependency_points_to_import_site() {
705        let root = PathBuf::from("/project");
706        let mut results = AnalysisResults::default();
707        results.unlisted_dependencies.push(UnlistedDependency {
708            package_name: "chalk".to_string(),
709            imported_from: vec![ImportSite {
710                path: root.join("src/cli.ts"),
711                line: 3,
712                col: 0,
713            }],
714        });
715
716        let sarif = build_sarif(&results, &root, &RulesConfig::default());
717        let entry = &sarif["runs"][0]["results"][0];
718        assert_eq!(entry["ruleId"], "fallow/unlisted-dependency");
719        assert_eq!(entry["level"], "error");
720        assert_eq!(
721            entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
722            "src/cli.ts"
723        );
724        let region = &entry["locations"][0]["physicalLocation"]["region"];
725        assert_eq!(region["startLine"], 3);
726        assert_eq!(region["startColumn"], 1);
727    }
728
729    #[test]
730    fn sarif_dependency_issues_point_to_package_json() {
731        let root = PathBuf::from("/project");
732        let mut results = AnalysisResults::default();
733        results.unused_dependencies.push(UnusedDependency {
734            package_name: "lodash".to_string(),
735            location: DependencyLocation::Dependencies,
736            path: root.join("package.json"),
737            line: 5,
738        });
739        results.unused_dev_dependencies.push(UnusedDependency {
740            package_name: "jest".to_string(),
741            location: DependencyLocation::DevDependencies,
742            path: root.join("package.json"),
743            line: 5,
744        });
745
746        let sarif = build_sarif(&results, &root, &RulesConfig::default());
747        let entries = sarif["runs"][0]["results"].as_array().unwrap();
748        for entry in entries {
749            assert_eq!(
750                entry["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
751                "package.json"
752            );
753        }
754    }
755
756    #[test]
757    fn sarif_duplicate_export_emits_one_result_per_location() {
758        let root = PathBuf::from("/project");
759        let mut results = AnalysisResults::default();
760        results.duplicate_exports.push(DuplicateExport {
761            export_name: "Config".to_string(),
762            locations: vec![
763                DuplicateLocation {
764                    path: root.join("src/a.ts"),
765                    line: 15,
766                    col: 0,
767                },
768                DuplicateLocation {
769                    path: root.join("src/b.ts"),
770                    line: 30,
771                    col: 0,
772                },
773            ],
774        });
775
776        let sarif = build_sarif(&results, &root, &RulesConfig::default());
777        let entries = sarif["runs"][0]["results"].as_array().unwrap();
778        // One SARIF result per location, not one per DuplicateExport
779        assert_eq!(entries.len(), 2);
780        assert_eq!(entries[0]["ruleId"], "fallow/duplicate-export");
781        assert_eq!(entries[1]["ruleId"], "fallow/duplicate-export");
782        assert_eq!(
783            entries[0]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
784            "src/a.ts"
785        );
786        assert_eq!(
787            entries[1]["locations"][0]["physicalLocation"]["artifactLocation"]["uri"],
788            "src/b.ts"
789        );
790    }
791
792    #[test]
793    fn sarif_all_issue_types_produce_results() {
794        let root = PathBuf::from("/project");
795        let results = sample_results(&root);
796        let sarif = build_sarif(&results, &root, &RulesConfig::default());
797
798        let entries = sarif["runs"][0]["results"].as_array().unwrap();
799        // 12 issues but duplicate_exports has 2 locations => 13 SARIF results
800        assert_eq!(entries.len(), 13);
801
802        let rule_ids: Vec<&str> = entries
803            .iter()
804            .map(|e| e["ruleId"].as_str().unwrap())
805            .collect();
806        assert!(rule_ids.contains(&"fallow/unused-file"));
807        assert!(rule_ids.contains(&"fallow/unused-export"));
808        assert!(rule_ids.contains(&"fallow/unused-type"));
809        assert!(rule_ids.contains(&"fallow/unused-dependency"));
810        assert!(rule_ids.contains(&"fallow/unused-dev-dependency"));
811        assert!(rule_ids.contains(&"fallow/type-only-dependency"));
812        assert!(rule_ids.contains(&"fallow/unused-enum-member"));
813        assert!(rule_ids.contains(&"fallow/unused-class-member"));
814        assert!(rule_ids.contains(&"fallow/unresolved-import"));
815        assert!(rule_ids.contains(&"fallow/unlisted-dependency"));
816        assert!(rule_ids.contains(&"fallow/duplicate-export"));
817    }
818
819    #[test]
820    fn sarif_serializes_to_valid_json() {
821        let root = PathBuf::from("/project");
822        let results = sample_results(&root);
823        let sarif = build_sarif(&results, &root, &RulesConfig::default());
824
825        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
826        let reparsed: serde_json::Value =
827            serde_json::from_str(&json_str).expect("SARIF output should be valid JSON");
828        assert_eq!(reparsed, sarif);
829    }
830
831    #[test]
832    fn sarif_file_write_produces_valid_sarif() {
833        let root = PathBuf::from("/project");
834        let results = sample_results(&root);
835        let sarif = build_sarif(&results, &root, &RulesConfig::default());
836        let json_str = serde_json::to_string_pretty(&sarif).expect("SARIF should serialize");
837
838        let dir = std::env::temp_dir().join("fallow-test-sarif-file");
839        let _ = std::fs::create_dir_all(&dir);
840        let sarif_path = dir.join("results.sarif");
841        std::fs::write(&sarif_path, &json_str).expect("should write SARIF file");
842
843        let contents = std::fs::read_to_string(&sarif_path).expect("should read SARIF file");
844        let parsed: serde_json::Value =
845            serde_json::from_str(&contents).expect("file should contain valid JSON");
846
847        assert_eq!(parsed["version"], "2.1.0");
848        assert_eq!(
849            parsed["$schema"],
850            "https://json.schemastore.org/sarif-2.1.0.json"
851        );
852        let sarif_results = parsed["runs"][0]["results"]
853            .as_array()
854            .expect("results should be an array");
855        assert!(!sarif_results.is_empty());
856
857        // Clean up
858        let _ = std::fs::remove_file(&sarif_path);
859        let _ = std::fs::remove_dir(&dir);
860    }
861}