big-code-analysis 1.1.0

Tool to compute and export code metrics
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
//! SARIF 2.1.0 writer for [`OffenderRecord`] batches.
//!
//! SARIF (Static Analysis Results Interchange Format) is the OASIS
//! standard ingested natively by GitHub Code Scanning and most modern
//! IDE/security tooling. Lizard does not have a SARIF output, so this
//! is the obvious modern target for `big-code-analysis` integrations.
//!
//! We model only the subset of SARIF we actually emit as a small set
//! of `Serialize` structs (no `sarif` crate dependency). The shape:
//!
//! ```json
//! {
//!   "version": "2.1.0",
//!   "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
//!   "runs": [{
//!     "tool": { "driver": { "name": "big-code-analysis", "version": "...",
//!                            "rules": [ { "id": "cyclomatic", ... } ] } },
//!     "results": [ { "ruleId": "...", "level": "warning", ... } ]
//!   }]
//! }
//! ```

use std::collections::BTreeSet;
use std::io::{self, Write};

use serde::Serialize;

#[cfg(test)]
use crate::output::offenders::Severity;
use crate::output::offenders::{OffenderRecord, TOOL_ID, warn_non_utf8_path};

/// SARIF schema URL — pinned to 2.1.0 (the version GitHub Code
/// Scanning ingests).
const SARIF_SCHEMA: &str = "https://json.schemastore.org/sarif-2.1.0.json";
const SARIF_VERSION: &str = "2.1.0";

/// Short rule descriptions used in `tool.driver.rules[]`. Metrics not
/// listed fall back to the metric name itself — never fail.
const RULE_DESCRIPTIONS: &[(&str, &str)] = &[
    (
        "cyclomatic",
        "Cyclomatic Complexity exceeds the configured threshold.",
    ),
    (
        "cognitive",
        "Cognitive Complexity exceeds the configured threshold.",
    ),
    (
        "loc.sloc",
        "Source lines of code exceed the configured threshold.",
    ),
    (
        "loc.ploc",
        "Physical lines of code exceed the configured threshold.",
    ),
    (
        "loc.lloc",
        "Logical lines of code exceed the configured threshold.",
    ),
    (
        "loc.cloc",
        "Comment lines of code exceed the configured threshold.",
    ),
    (
        "loc.blank",
        "Blank lines of code exceed the configured threshold.",
    ),
    (
        "halstead.volume",
        "Halstead volume exceeds the configured threshold.",
    ),
    (
        "halstead.difficulty",
        "Halstead difficulty exceeds the configured threshold.",
    ),
    (
        "halstead.effort",
        "Halstead effort exceeds the configured threshold.",
    ),
    (
        "halstead.bugs",
        "Estimated Halstead bugs exceed the configured threshold.",
    ),
    (
        "nargs.total",
        "Number of function arguments exceeds the configured threshold.",
    ),
    (
        "nexits.sum",
        "Number of exit points exceeds the configured threshold.",
    ),
    (
        "nom.total",
        "Number of methods/functions exceeds the configured threshold.",
    ),
    (
        "npa.total",
        "Number of public attributes exceeds the configured threshold.",
    ),
    (
        "npm.total",
        "Number of public methods exceeds the configured threshold.",
    ),
    (
        "abc.magnitude",
        "ABC magnitude exceeds the configured threshold.",
    ),
    (
        "wmc.total",
        "Weighted Methods per Class exceeds the configured threshold.",
    ),
    (
        "mi.mi_original",
        "Maintainability Index falls below the configured threshold.",
    ),
    (
        "mi.mi_sei",
        "Maintainability Index (SEI) falls below the configured threshold.",
    ),
    (
        "mi.mi_visual_studio",
        "Maintainability Index (Visual Studio) falls below the configured threshold.",
    ),
];

fn rule_description(metric: &str) -> &str {
    RULE_DESCRIPTIONS
        .iter()
        .find_map(|(name, desc)| (*name == metric).then_some(*desc))
        .unwrap_or(metric)
}

/// Convert an OS path string into a SARIF `artifactLocation.uri`
/// value (an RFC 3986 URI reference).
///
/// SARIF 2.1.0 §3.4.4 requires `artifactLocation.uri` be a valid URI
/// reference. Backslash separators (Windows paths) and characters
/// outside the URI unreserved/reserved sets break that — the
/// json-schema validator GitHub Code Scanning uses rejects them
/// under the `uri-reference` format. We:
///
/// - Normalize separators to `/`.
/// - Percent-encode any byte outside the URI unreserved set + `/`
///   so spaces and other path characters survive validation.
/// - For absolute Windows paths beginning with a drive letter
///   (`C:\…` → `C:/…`), prefix with `file:///` so the leading `C:`
///   is not interpreted as a URI scheme.
fn path_to_uri_reference(path: &str) -> String {
    let bytes = path.as_bytes();
    let is_windows_drive_abs = bytes.len() >= 2
        && bytes[0].is_ascii_alphabetic()
        && bytes[1] == b':'
        && (bytes.len() == 2 || bytes[2] == b'/' || bytes[2] == b'\\');

    let mut out = String::with_capacity(path.len() + if is_windows_drive_abs { 8 } else { 0 });
    if is_windows_drive_abs {
        out.push_str("file:///");
    }
    for &b in bytes {
        match b {
            b'\\' => out.push('/'),
            // RFC 3986 unreserved + path separator + segment-safe sub-delims +
            // ':' '@' (allowed in path) + '%' would need its own escaping but
            // raw paths from the OS will not contain it pre-encoded.
            b'A'..=b'Z'
            | b'a'..=b'z'
            | b'0'..=b'9'
            | b'-'
            | b'.'
            | b'_'
            | b'~'
            | b'/'
            | b':'
            | b'@' => out.push(b as char),
            _ => {
                let hi = b >> 4;
                let lo = b & 0xF;
                out.push('%');
                out.push(hex_digit(hi));
                out.push(hex_digit(lo));
            }
        }
    }
    out
}

fn hex_digit(nibble: u8) -> char {
    match nibble {
        0..=9 => (b'0' + nibble) as char,
        10..=15 => (b'A' + nibble - 10) as char,
        _ => '0',
    }
}

/// Write a SARIF 2.1.0 document for `offenders` to `writer`.
///
/// Offenders whose path is not valid UTF-8 are skipped with a warning
/// to stderr (SARIF `artifactLocation.uri` requires a UTF-8 string).
/// The empty case emits a well-formed run with empty `results: []` and
/// `rules: []` so snapshots are stable and CI consumers can already
/// integrate before the threshold engine (#96) lands.
///
/// # Errors
///
/// Returns any [`io::Error`] produced by `writer` while emitting the
/// SARIF JSON document, or a `serde_json::Error` (mapped to `io::Error`
/// via `io::Error::other`) if a record cannot be serialised.
pub fn write_sarif<W: Write>(offenders: &[OffenderRecord], mut writer: W) -> io::Result<()> {
    let mut results: Vec<SarifResult<'_>> = Vec::with_capacity(offenders.len());
    // BTreeSet so the rules array is deterministic (alphabetical by id).
    let mut rule_ids: BTreeSet<&str> = BTreeSet::new();

    for record in offenders {
        let Some(path_str) = warn_non_utf8_path("SARIF", &record.path) else {
            continue;
        };
        rule_ids.insert(record.metric.as_str());

        let logical_locations = record.function.as_deref().map(|name| {
            vec![LogicalLocation {
                fully_qualified_name: name,
            }]
        });

        results.push(SarifResult {
            rule_id: &record.metric,
            level: record.severity.as_str(),
            message: Message {
                text: record.default_message(),
            },
            locations: vec![Location {
                physical_location: PhysicalLocation {
                    artifact_location: ArtifactLocation {
                        uri: path_to_uri_reference(path_str),
                    },
                    region: Region {
                        start_line: record.start_line.max(1),
                        end_line: Some(record.end_line.max(record.start_line.max(1))),
                        start_column: record.start_col,
                    },
                },
                logical_locations,
            }],
        });
    }

    let rules: Vec<Rule<'_>> = rule_ids
        .iter()
        .map(|id| Rule {
            id,
            short_description: Description {
                text: rule_description(id),
            },
        })
        .collect();

    let log = SarifLog {
        schema: SARIF_SCHEMA,
        version: SARIF_VERSION,
        runs: vec![Run {
            tool: Tool {
                driver: Driver {
                    name: TOOL_ID,
                    version: env!("CARGO_PKG_VERSION"),
                    rules,
                },
            },
            results,
        }],
    };

    serde_json::to_writer_pretty(&mut writer, &log)
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    // `serde_json::to_writer_pretty` does not append a trailing
    // newline; add one so the output is POSIX-friendly and snapshot
    // diffs stay clean.
    writer.write_all(b"\n")
}

#[derive(Serialize)]
struct SarifLog<'a> {
    #[serde(rename = "$schema")]
    schema: &'a str,
    version: &'a str,
    runs: Vec<Run<'a>>,
}

#[derive(Serialize)]
struct Run<'a> {
    tool: Tool<'a>,
    results: Vec<SarifResult<'a>>,
}

#[derive(Serialize)]
struct Tool<'a> {
    driver: Driver<'a>,
}

#[derive(Serialize)]
struct Driver<'a> {
    name: &'a str,
    version: &'a str,
    rules: Vec<Rule<'a>>,
}

#[derive(Serialize)]
struct Rule<'a> {
    id: &'a str,
    #[serde(rename = "shortDescription")]
    short_description: Description<'a>,
}

#[derive(Serialize)]
struct Description<'a> {
    text: &'a str,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct SarifResult<'a> {
    rule_id: &'a str,
    level: &'static str,
    message: Message,
    locations: Vec<Location<'a>>,
}

#[derive(Serialize)]
struct Message {
    text: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Location<'a> {
    physical_location: PhysicalLocation,
    #[serde(skip_serializing_if = "Option::is_none")]
    logical_locations: Option<Vec<LogicalLocation<'a>>>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PhysicalLocation {
    artifact_location: ArtifactLocation,
    region: Region,
}

#[derive(Serialize)]
struct ArtifactLocation {
    uri: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Region {
    start_line: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    end_line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    start_column: Option<u32>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct LogicalLocation<'a> {
    fully_qualified_name: &'a str,
}

#[cfg(test)]
#[allow(
    clippy::float_cmp,
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::similar_names,
    clippy::doc_markdown,
    clippy::needless_raw_string_hashes,
    clippy::too_many_lines
)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    fn rec(path: &str, metric: &str, value: f64, limit: f64) -> OffenderRecord {
        OffenderRecord {
            path: PathBuf::from(path),
            function: Some("f".into()),
            start_line: 42,
            end_line: 50,
            start_col: Some(5),
            metric: metric.into(),
            value,
            limit,
            severity: Severity::Warning,
        }
    }

    fn render(offenders: &[OffenderRecord]) -> String {
        let mut buf = Vec::new();
        write_sarif(offenders, &mut buf).expect("writing to Vec is infallible");
        String::from_utf8(buf).expect("output is UTF-8")
    }

    #[test]
    fn empty_emits_minimal_valid_run() {
        let out = render(&[]);
        // Round-trips cleanly through serde_json so we know it parses.
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["version"], "2.1.0");
        assert_eq!(v["runs"][0]["tool"]["driver"]["name"], "big-code-analysis");
        assert!(
            v["runs"][0]["results"]
                .as_array()
                .expect("array")
                .is_empty()
        );
        assert!(
            v["runs"][0]["tool"]["driver"]["rules"]
                .as_array()
                .expect("array")
                .is_empty()
        );
    }

    #[test]
    fn single_offender_includes_rule_and_result() {
        let offenders = vec![rec("src/foo.rs", "cyclomatic", 17.0, 15.0)];
        let out = render(&offenders);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        let result = &v["runs"][0]["results"][0];
        assert_eq!(result["ruleId"], "cyclomatic");
        assert_eq!(result["level"], "warning");
        assert_eq!(result["message"]["text"], "cyclomatic 17 exceeds limit 15");
        let loc = &result["locations"][0];
        assert_eq!(
            loc["physicalLocation"]["artifactLocation"]["uri"],
            "src/foo.rs"
        );
        assert_eq!(loc["physicalLocation"]["region"]["startLine"], 42);
        assert_eq!(loc["physicalLocation"]["region"]["endLine"], 50);
        assert_eq!(loc["physicalLocation"]["region"]["startColumn"], 5);
        assert_eq!(loc["logicalLocations"][0]["fullyQualifiedName"], "f");

        let rule = &v["runs"][0]["tool"]["driver"]["rules"][0];
        assert_eq!(rule["id"], "cyclomatic");
        assert!(rule["shortDescription"]["text"].is_string());
    }

    #[test]
    fn error_severity_maps_to_error_level() {
        let mut r = rec("a.rs", "cyclomatic", 99.0, 15.0);
        r.severity = Severity::Error;
        let out = render(&[r]);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(v["runs"][0]["results"][0]["level"], "error");
    }

    #[test]
    fn missing_column_omits_field() {
        let mut r = rec("a.rs", "cyclomatic", 17.0, 15.0);
        r.start_col = None;
        let out = render(&[r]);
        assert!(!out.contains("startColumn"), "{out}");
    }

    #[test]
    fn missing_function_omits_logical_locations() {
        let mut r = rec("a.rs", "cyclomatic", 17.0, 15.0);
        r.function = None;
        let out = render(&[r]);
        assert!(!out.contains("logicalLocations"), "{out}");
    }

    #[test]
    fn rules_deduplicate_per_metric() {
        let offenders = vec![
            rec("a.rs", "cyclomatic", 17.0, 15.0),
            rec("b.rs", "cyclomatic", 20.0, 15.0),
            rec("a.rs", "loc.lloc", 250.0, 100.0),
        ];
        let out = render(&offenders);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        let rules = v["runs"][0]["tool"]["driver"]["rules"]
            .as_array()
            .expect("array");
        assert_eq!(rules.len(), 2);
        // BTreeSet iteration order: alphabetical.
        assert_eq!(rules[0]["id"], "cyclomatic");
        assert_eq!(rules[1]["id"], "loc.lloc");
    }

    #[test]
    fn unknown_metric_falls_back_to_metric_name_as_description() {
        let r = rec("a.rs", "made.up.metric", 1.0, 0.0);
        let out = render(&[r]);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(
            v["runs"][0]["tool"]["driver"]["rules"][0]["shortDescription"]["text"],
            "made.up.metric"
        );
    }

    #[test]
    fn start_line_zero_is_clamped_to_one() {
        let mut r = rec("a.rs", "cyclomatic", 17.0, 15.0);
        r.start_line = 0;
        r.end_line = 0;
        let out = render(&[r]);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(
            v["runs"][0]["results"][0]["locations"][0]["physicalLocation"]["region"]["startLine"],
            1
        );
    }

    #[test]
    fn driver_version_matches_pkg_version() {
        let out = render(&[]);
        let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        assert_eq!(
            v["runs"][0]["tool"]["driver"]["version"],
            env!("CARGO_PKG_VERSION")
        );
    }

    #[test]
    fn windows_drive_path_becomes_file_uri() {
        // Windows absolute path: backslashes flip to /, drive letter
        // gets wrapped in `file:///` so it isn't parsed as a scheme.
        assert_eq!(
            path_to_uri_reference(r"C:\Users\RUNNER~1\AppData\Local\Temp\fixture.rs"),
            "file:///C:/Users/RUNNER~1/AppData/Local/Temp/fixture.rs"
        );
    }

    #[test]
    fn posix_relative_path_is_unchanged() {
        assert_eq!(path_to_uri_reference("src/foo.rs"), "src/foo.rs");
    }

    #[test]
    fn posix_absolute_path_keeps_leading_slash() {
        assert_eq!(path_to_uri_reference("/tmp/foo.rs"), "/tmp/foo.rs");
    }

    #[test]
    fn space_is_percent_encoded() {
        assert_eq!(path_to_uri_reference("src/my file.rs"), "src/my%20file.rs");
    }

    #[test]
    fn empty_snapshot_is_stable() {
        insta::assert_snapshot!("sarif_empty", render(&[]));
    }

    #[test]
    fn multi_offender_snapshot_is_stable() {
        let mut err = rec("src/zeta.rs", "cognitive", 30.0, 15.0);
        err.severity = Severity::Error;
        err.start_col = None;
        err.function = None;
        let offenders = vec![
            rec("src/alpha.rs", "cyclomatic", 17.0, 15.0),
            rec("src/alpha.rs", "loc.lloc", 250.0, 100.0),
            err,
        ];
        insta::assert_snapshot!("sarif_multi", render(&offenders));
    }
}