crap-core 0.1.0

Language-agnostic foundation for the CRAP analyzer family — domain types, port traits, and shared invariants for crap4rs / future crap4ts.
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
//! Baseline-envelope loader — reads a previously-emitted crap4rs JSON
//! envelope from disk and extracts the `result` block, plus the
//! envelope metadata (tool_version, timestamp) needed for delta
//! reporting.
//!
//! The on-the-wire JSON envelope (see `adapters::reporters::json`)
//! includes far more than `result`: `view`, `diagnostics`, `delta` (in
//! the future), etc. The baseline loader ignores everything except
//! `schema_version`, `result`, `tool_version`, `timestamp`, and
//! optionally `diagnostics` so that consumers can produce baseline
//! envelopes that contain extra fields without breaking us.
//!
//! Schema version validation: `schema_version` 1 and 2 are both
//! accepted (#107 bumped the current emit version 1 → 2 in 0.4.0; v1
//! baselines remain loadable because delta matching is identity-keyed,
//! not column-keyed). Future schema bumps will need an explicit
//! migration path.

use crate::domain::types::{AnalysisDiagnostics, AnalysisResult};
use crate::ports::ParseDiagnostic;
use serde::Deserialize;
use std::fs::File;
use std::io::{BufReader, ErrorKind};
use std::path::Path;

/// Currently-emitted envelope schema version. Lockstep with
/// `adapters::reporters::json::JsonEnvelope::schema_version`.
pub const CURRENT_SCHEMA_VERSION: u32 = 2;

/// Envelope schema versions accepted by the baseline loader. v1 stays
/// loadable across the v0.3.x → v0.4.x boundary so users can keep their
/// committed baseline JSON; the column-convention shift in v2 doesn't
/// affect delta calculations (identity-keyed matching).
pub const SUPPORTED_SCHEMA_VERSIONS: &[u32] = &[1, 2];

/// On-disk shape we read. Mirrors the relevant subset of
/// `JsonEnvelope`. `serde(default)` on optional fields keeps us
/// forward-compatible with envelopes that omit fields we don't need.
///
/// `P: ParseDiagnostic` carries the adapter-specific parse-diagnostic
/// type through `AnalysisDiagnostics<P>` (S2's decomposition); crap4rs
/// concretizes to `LcovParseDiagnostic` via the v0.4 shim alias.
/// `serde(bound = "")` suppresses the auto-generated `P: Serialize` /
/// `P: Deserialize<'de>` bounds — `P: ParseDiagnostic` already provides
/// `Serialize + DeserializeOwned`, and the auto-bounds conflict with
/// the owned-deserialize requirement.
#[derive(Debug, Deserialize)]
#[serde(bound = "")]
struct BaselineEnvelope<P: ParseDiagnostic> {
    schema_version: u32,
    #[serde(default)]
    tool_version: String,
    #[serde(default)]
    timestamp: String,
    result: AnalysisResult,
    #[serde(default)]
    diagnostics: Option<AnalysisDiagnostics<P>>,
}

/// What the loader returns to callers. The fields are all the metadata
/// the delta envelope's `delta.baseline_*` keys ultimately surface.
///
/// Generic over `P: ParseDiagnostic` so the loader works for any
/// adapter that supplies a concrete parse-diagnostic type. The crap4rs
/// shim concretizes this to `BaselineSnapshot<LcovParseDiagnostic>`.
#[derive(Debug, Clone)]
pub struct BaselineSnapshot<P: ParseDiagnostic> {
    pub result: AnalysisResult,
    pub tool_version: String,
    pub timestamp: String,
    pub diagnostics: Option<AnalysisDiagnostics<P>>,
}

/// Errors raised while loading a baseline envelope.
///
/// Tag-only — variants carry numeric / string context but no
/// pre-formatted prose. The CLI translates these into user-facing
/// stderr messages (keeps the adapter language-neutral for future
/// `crap-core` extraction).
///
/// `#[non_exhaustive]` reserves namespace for future variants (e.g.,
/// `MissingRequiredField`, `IncompatibleToolVersion`) without forcing a
/// downstream major-version bump on every adapter error addition.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BaselineError {
    #[error("baseline file not found: {path}")]
    NotFound { path: String },
    #[error("baseline file is not readable: {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to parse baseline JSON ({path}): {source}")]
    Parse {
        path: String,
        #[source]
        source: serde_json::Error,
    },
    #[error(
        "unsupported baseline schema_version: {found} (this build of crap4rs accepts {supported:?})"
    )]
    UnsupportedSchemaVersion {
        found: u32,
        supported: &'static [u32],
    },
}

/// Load a crap4rs JSON envelope from disk and return the baseline
/// snapshot. Streams the file through a `BufReader` rather than
/// reading the whole envelope into memory — large codebases produce
/// envelopes in the multi-MB range and there's no reason to allocate
/// that twice.
///
/// Generic over `P: ParseDiagnostic` so each adapter (LCOV, Istanbul,
/// …) supplies its own concrete diagnostic shape. The crap4rs shim
/// `crap4rs::adapters::baseline::load` instantiates `P =
/// LcovParseDiagnostic` so v0.4 callers' import paths stay byte-
/// identical.
pub fn load<P: ParseDiagnostic>(path: &Path) -> Result<BaselineSnapshot<P>, BaselineError> {
    let path_str = path.display().to_string();

    let file = File::open(path).map_err(|source| match source.kind() {
        ErrorKind::NotFound => BaselineError::NotFound {
            path: path_str.clone(),
        },
        _ => BaselineError::Io {
            path: path_str.clone(),
            source,
        },
    })?;

    let envelope: BaselineEnvelope<P> =
        serde_json::from_reader(BufReader::new(file)).map_err(|source| BaselineError::Parse {
            path: path_str.clone(),
            source,
        })?;

    if !SUPPORTED_SCHEMA_VERSIONS.contains(&envelope.schema_version) {
        return Err(BaselineError::UnsupportedSchemaVersion {
            found: envelope.schema_version,
            supported: SUPPORTED_SCHEMA_VERSIONS,
        });
    }

    Ok(BaselineSnapshot {
        result: envelope.result,
        tool_version: envelope.tool_version,
        timestamp: envelope.timestamp,
        diagnostics: envelope.diagnostics,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_strategies::DummyParseDiagnostic;
    use std::io::Write;
    use tempfile::NamedTempFile;

    /// Concrete `P` for tests in this module — the loader's behavior is
    /// `P`-agnostic for the cases we test (none reach into per-variant
    /// fields), so the dummy stub keeps the assertions byte-identical
    /// to crap4rs's pre-S3 unit suite.
    type TestSnapshot = BaselineSnapshot<DummyParseDiagnostic>;

    /// Wrapper that pins `P = DummyParseDiagnostic`. Keeps the original
    /// test bodies untouched (they were written before `load` was
    /// generic over `P`).
    fn load_test(path: &Path) -> Result<TestSnapshot, BaselineError> {
        load::<DummyParseDiagnostic>(path)
    }

    fn write_envelope(content: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().expect("create temp file");
        write!(file, "{content}").expect("write temp file");
        file.flush().expect("flush temp file");
        file
    }

    fn minimal_envelope_json() -> &'static str {
        r#"{
            "schema_version": 1,
            "tool_version": "0.2.0",
            "language": "rust",
            "timestamp": "2026-04-26T10:00:00Z",
            "metric": "cognitive",
            "threshold": 25.0,
            "diff_ref": null,
            "result": {
                "functions": [],
                "summary": {
                    "total_functions": 0,
                    "total_files": 0,
                    "exceeding_threshold": 0,
                    "average_crap": 0.0,
                    "median_crap": 0.0,
                    "max_crap": null,
                    "worst_function": null,
                    "distribution": {
                        "low": 0,
                        "acceptable": 0,
                        "moderate": 0,
                        "high": 0
                    }
                },
                "passed": true
            }
        }"#
    }

    #[test]
    fn load_minimal_envelope_extracts_result_and_metadata() {
        let file = write_envelope(minimal_envelope_json());
        let snapshot = load_test(file.path()).expect("load minimal envelope");
        assert_eq!(snapshot.tool_version, "0.2.0");
        assert_eq!(snapshot.timestamp, "2026-04-26T10:00:00Z");
        assert_eq!(snapshot.result.functions.len(), 0);
        assert!(snapshot.result.passed);
        assert!(snapshot.diagnostics.is_none());
    }

    #[test]
    fn load_envelope_with_function_round_trips_verdict_fields() {
        let json = r#"{
            "schema_version": 1,
            "tool_version": "0.2.0",
            "language": "rust",
            "timestamp": "2026-04-26T10:00:00Z",
            "metric": "cognitive",
            "threshold": 25.0,
            "diff_ref": null,
            "result": {
                "functions": [
                    {
                        "scored": {
                            "identity": {
                                "file_path": "src/foo.rs",
                                "qualified_name": "foo::bar",
                                "span": { "start_line": 10, "end_line": 20 }
                            },
                            "complexity": 5,
                            "complexity_metric": "cognitive",
                            "coverage_percent": 75.0,
                            "crap": { "value": 8.0, "risk_level": "acceptable" },
                            "contributors": []
                        },
                        "threshold": 25.0,
                        "exceeds": false
                    }
                ],
                "summary": {
                    "total_functions": 1,
                    "total_files": 1,
                    "exceeding_threshold": 0,
                    "average_crap": 8.0,
                    "median_crap": 8.0,
                    "max_crap": { "value": 8.0, "risk_level": "acceptable" },
                    "worst_function": {
                        "file_path": "src/foo.rs",
                        "qualified_name": "foo::bar",
                        "span": { "start_line": 10, "end_line": 20 }
                    },
                    "distribution": { "low": 0, "acceptable": 1, "moderate": 0, "high": 0 }
                },
                "passed": true
            }
        }"#;
        let file = write_envelope(json);
        let snapshot = load_test(file.path()).expect("load function envelope");
        assert_eq!(snapshot.result.functions.len(), 1);
        let v = &snapshot.result.functions[0];
        assert_eq!(v.scored.identity.qualified_name, "foo::bar");
        assert_eq!(v.scored.identity.file_path, "src/foo.rs");
        assert_eq!(v.scored.crap.value, 8.0);
        assert!(!v.exceeds);
    }

    #[test]
    fn load_nonexistent_path_returns_not_found() {
        let result = load_test(Path::new("/tmp/definitely-does-not-exist-xyzzy.json"));
        match result {
            Err(BaselineError::NotFound { .. }) => {}
            other => panic!("expected NotFound, got {other:?}"),
        }
    }

    #[test]
    fn load_malformed_json_returns_parse_error() {
        let file = write_envelope("{ not valid JSON");
        let err = load_test(file.path()).unwrap_err();
        match err {
            BaselineError::Parse { .. } => {}
            other => panic!("expected Parse, got {other:?}"),
        }
    }

    #[test]
    fn load_unsupported_schema_version_rejects() {
        // Use a future-unsupported version (99) — both 1 and 2 are
        // accepted today after the #107 column-convention bump.
        let json = r#"{
            "schema_version": 99,
            "result": {
                "functions": [],
                "summary": {
                    "total_functions": 0, "total_files": 0, "exceeding_threshold": 0,
                    "average_crap": 0.0, "median_crap": 0.0,
                    "max_crap": null, "worst_function": null,
                    "distribution": { "low": 0, "acceptable": 0, "moderate": 0, "high": 0 }
                },
                "passed": true
            }
        }"#;
        let file = write_envelope(json);
        let err = load_test(file.path()).unwrap_err();
        match err {
            BaselineError::UnsupportedSchemaVersion {
                found: 99,
                supported,
            } => {
                assert_eq!(supported, &[1, 2]);
            }
            other => panic!("expected UnsupportedSchemaVersion {{ found: 99, .. }}, got {other:?}"),
        }
    }

    #[test]
    fn load_v2_schema_version_accepted() {
        // Post-#107: v2 baselines (1-based contributor columns) load
        // alongside v1 baselines.
        let json = r#"{
            "schema_version": 2,
            "tool_version": "0.4.0",
            "result": {
                "functions": [],
                "summary": {
                    "total_functions": 0, "total_files": 0, "exceeding_threshold": 0,
                    "average_crap": 0.0, "median_crap": 0.0,
                    "max_crap": null, "worst_function": null,
                    "distribution": { "low": 0, "acceptable": 0, "moderate": 0, "high": 0 }
                },
                "passed": true
            }
        }"#;
        let file = write_envelope(json);
        let snapshot = load_test(file.path()).expect("v2 envelope should load");
        assert_eq!(snapshot.tool_version, "0.4.0");
    }

    #[test]
    fn load_envelope_propagates_diagnostics_when_present() {
        let json = r#"{
            "schema_version": 1,
            "result": {
                "functions": [],
                "summary": {
                    "total_functions": 0, "total_files": 0, "exceeding_threshold": 0,
                    "average_crap": 0.0, "median_crap": 0.0,
                    "max_crap": null, "worst_function": null,
                    "distribution": { "low": 0, "acceptable": 0, "moderate": 0, "high": 0 }
                },
                "passed": true
            },
            "diagnostics": {
                "parse_diagnostics": [],
                "files_found": 5,
                "files_unparseable": 0,
                "functions_extracted": 12,
                "functions_matched": 10,
                "functions_no_coverage": 2,
                "files_analyzed": 5,
                "files_zero_coverage": 0
            }
        }"#;
        let file = write_envelope(json);
        let snapshot = load_test(file.path()).expect("load envelope with diagnostics");
        let diag = snapshot.diagnostics.expect("diagnostics should be present");
        assert_eq!(diag.files_found, 5);
        assert_eq!(diag.functions_matched, 10);
    }

    #[test]
    fn load_envelope_with_extra_unknown_fields_is_forward_compatible() {
        // We don't deny_unknown_fields — future envelopes may add keys we
        // don't care about (e.g. delta-on-delta, future view shapes).
        let json = r#"{
            "schema_version": 1,
            "tool_version": "0.99.0",
            "result": {
                "functions": [],
                "summary": {
                    "total_functions": 0, "total_files": 0, "exceeding_threshold": 0,
                    "average_crap": 0.0, "median_crap": 0.0,
                    "max_crap": null, "worst_function": null,
                    "distribution": { "low": 0, "acceptable": 0, "moderate": 0, "high": 0 }
                },
                "passed": true
            },
            "future_field": { "unknown": "shape" }
        }"#;
        let file = write_envelope(json);
        let snapshot = load_test(file.path()).expect("forward-compat load");
        assert_eq!(snapshot.tool_version, "0.99.0");
    }
}