rustquty-core 0.2.0

Core library for rustquty, a local-first quality scanner for Rust projects
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
//! JSON schemas for rustquty data structures.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ------------------------------------------------------------------------------------------------
// MetricsSummary
// ------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MetricsSummary {
    pub schema_version: String,
    pub generated_at: String,
    pub rustquty_version: String,
    pub project: ProjectInfo,
    pub collectors: CollectorsSummary,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ProjectInfo {
    pub name: String,
    pub rust_edition: String,
    pub workspace_root: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CollectorsSummary {
    pub fmt: FmtResult,
    pub clippy: ClippyResult,
    pub tests: TestResult,
    pub coverage: CoverageResult,
    pub deny: DenyResult,
    pub audit: AuditResult,
    pub hack: HackResult,
    pub mutants: MutantsResult,
    pub duplicates: DuplicatesResult,
    pub loc: LocResult,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FmtResult {
    pub status: CollectorStatus,
    #[serde(default)]
    pub details: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ClippyResult {
    pub status: CollectorStatus,
    pub warning_count: u32,
    #[serde(default)]
    pub details: Vec<ClippyLint>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ClippyLint {
    pub code: String,
    pub message: String,
    pub file: Option<String>,
    pub line: Option<u32>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TestResult {
    pub status: CollectorStatus,
    pub passed: u32,
    pub failed: u32,
    pub ignored: u32,
    #[serde(default)]
    pub runner: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CoverageResult {
    pub status: CollectorStatus,
    pub line_percent: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DenyResult {
    pub status: CollectorStatus,
    pub banned_count: u32,
    pub license_violations: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuditResult {
    pub status: CollectorStatus,
    pub vulnerability_count: u32,
    pub critical_count: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HackResult {
    pub status: CollectorStatus,
    pub feature_combinations_tested: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MutantsResult {
    pub status: CollectorStatus,
    pub mutation_score: f64,
    pub caught: u32,
    pub missed: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DuplicatesResult {
    pub status: CollectorStatus,
    pub total_lines: u32,
    pub duplicate_lines: u32,
    #[serde(default)]
    pub files_with_duplicates: u32,
    #[serde(default)]
    pub duplicate_files: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LocResult {
    pub status: CollectorStatus,
    pub total_lines: u32,
    pub code_lines: u32,
    pub comment_lines: u32,
    pub blank_lines: u32,
    pub long_lines: u32,
    pub max_line_length_found: usize,
    pub max_line_length_allowed: usize,
    pub files: u32,
    #[serde(default)]
    pub files_with_long_lines: u32,
    #[serde(default)]
    pub long_line_files: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CollectorStatus {
    Pass,
    Fail,
    Skipped,
    Error,
}

// ------------------------------------------------------------------------------------------------
// Baseline
// ------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Baseline {
    pub schema_version: String,
    pub created_at: String,
    pub rustquty_version: String,
    pub thresholds: Thresholds,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Thresholds {
    pub fmt: FmtThreshold,
    pub clippy: ClippyThreshold,
    pub tests: TestThreshold,
    pub coverage: CoverageThreshold,
    pub deny: DenyThreshold,
    pub audit: AuditThreshold,
    pub hack: HackThreshold,
    pub mutants: MutantsThreshold,
    pub duplicates: DuplicatesThreshold,
    pub loc: LocThreshold,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FmtThreshold {
    pub must_pass: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ClippyThreshold {
    pub max_warnings: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TestThreshold {
    pub max_failures: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CoverageThreshold {
    pub min_line_percent: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DenyThreshold {
    pub max_banned: u32,
    pub max_license_violations: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct AuditThreshold {
    pub max_vulnerabilities: u32,
    pub max_critical: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HackThreshold {
    pub must_pass: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct MutantsThreshold {
    pub min_score: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DuplicatesThreshold {
    pub max_duplicate_lines: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LocThreshold {
    pub max_line_length: usize,
}

// ------------------------------------------------------------------------------------------------
// QualityReport
// ------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct QualityReport {
    pub schema_version: String,
    pub generated_at: String,
    pub gate_result: GateResult,
    #[serde(default)]
    pub violations: Vec<Violation>,
    pub summary: ReportSummary,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum GateResult {
    Pass,
    Fail,
    Error,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Violation {
    pub collector: String,
    pub metric: String,
    pub baseline_value: serde_json::Value,
    pub current_value: serde_json::Value,
    pub message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ReportSummary {
    pub collectors_run: u32,
    pub collectors_passed: u32,
    pub collectors_failed: u32,
    pub collectors_skipped: u32,
}

// ------------------------------------------------------------------------------------------------
// Schema version errors
// ------------------------------------------------------------------------------------------------

#[derive(Debug, thiserror::Error)]
pub enum SchemaVersionError {
    #[error("unknown schema version: {0}")]
    UnknownVersion(String),
}

impl MetricsSummary {
    pub fn check_version(&self) -> Result<(), SchemaVersionError> {
        if &self.schema_version != "1" {
            return Err(SchemaVersionError::UnknownVersion(
                self.schema_version.clone(),
            ));
        }
        Ok(())
    }
}

impl Baseline {
    pub fn check_version(&self) -> Result<(), SchemaVersionError> {
        if &self.schema_version != "1" {
            return Err(SchemaVersionError::UnknownVersion(
                self.schema_version.clone(),
            ));
        }
        Ok(())
    }
}

impl QualityReport {
    pub fn check_version(&self) -> Result<(), SchemaVersionError> {
        if &self.schema_version != "1" {
            return Err(SchemaVersionError::UnknownVersion(
                self.schema_version.clone(),
            ));
        }
        Ok(())
    }
}

// ------------------------------------------------------------------------------------------------
// Round-trip tests
// ------------------------------------------------------------------------------------------------

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

    #[test]
    fn test_metrics_summary_roundtrip() {
        let json = r#"{
          "schemaVersion": "1",
          "generatedAt": "2026-05-04T12:00:00Z",
          "rustqutyVersion": "0.1.0",
          "project": {
            "name": "test-project",
            "rustEdition": "2021",
            "workspaceRoot": "/path/to/project"
          },
          "collectors": {
            "fmt": { "status": "pass", "details": {} },
            "clippy": { "status": "pass", "warningCount": 0, "details": [] },
            "tests": { "status": "pass", "passed": 10, "failed": 0, "ignored": 0 },
            "coverage": { "status": "skipped", "linePercent": 0.0 },
            "deny": { "status": "skipped", "bannedCount": 0, "licenseViolations": 0 },
            "audit": { "status": "skipped", "vulnerabilityCount": 0, "criticalCount": 0 },
            "hack": { "status": "skipped", "featureCombinationsTested": 0 },
            "mutants": { "status": "skipped", "mutationScore": 0.0, "caught": 0, "missed": 0 },
            "duplicates": { "status": "skipped", "totalLines": 0, "duplicateLines": 0, "filesWithDuplicates": 0, "duplicateFiles": [] },
            "loc": { "status": "skipped", "totalLines": 0, "codeLines": 0, "commentLines": 0, "blankLines": 0, "longLines": 0, "maxLineLengthFound": 0, "maxLineLengthAllowed": 120, "files": 0, "filesWithLongLines": 0, "longLineFiles": [] }
          }
        }"#;
        let summary: MetricsSummary = serde_json::from_str(json).unwrap();
        assert_eq!(summary.schema_version, "1");
        let output = serde_json::to_string(&summary).unwrap();
        assert!(output.contains("\"schemaVersion\":\"1\""));
    }

    #[test]
    fn test_baseline_roundtrip() {
        let json = r#"{
          "schemaVersion": "1",
          "createdAt": "2026-05-04T00:00:00Z",
          "rustqutyVersion": "0.1.0",
          "thresholds": {
            "fmt": { "mustPass": true },
            "clippy": { "maxWarnings": 0 },
            "tests": { "maxFailures": 0 },
            "coverage": { "minLinePercent": 80.0 },
            "deny": { "maxBanned": 0, "maxLicenseViolations": 0 },
            "audit": { "maxVulnerabilities": 0, "maxCritical": 0 },
            "hack": { "mustPass": true },
            "mutants": { "minScore": 0.8 },
            "duplicates": { "maxDuplicateLines": 100 },
            "loc": { "maxLineLength": 120 }
          }
        }"#;
        let baseline: Baseline = serde_json::from_str(json).unwrap();
        assert_eq!(baseline.thresholds.coverage.min_line_percent, 80.0);
        let output = serde_json::to_string(&baseline).unwrap();
        assert!(output.contains("\"minLinePercent\":80.0"));
    }

    #[test]
    fn test_quality_report_roundtrip() {
        let json = r#"{
          "schemaVersion": "1",
          "generatedAt": "2026-05-04T12:00:00Z",
          "gateResult": "fail",
          "violations": [
            {
              "collector": "clippy",
              "metric": "warningCount",
              "baselineValue": "0",
              "currentValue": "5",
              "message": "clippy warning count exceeded baseline"
            }
          ],
          "summary": {
            "collectorsRun": 8,
            "collectorsPassed": 7,
            "collectorsFailed": 1,
            "collectorsSkipped": 0
          }
        }"#;
        let report: QualityReport = serde_json::from_str(json).unwrap();
        assert_eq!(report.violations.len(), 1);
        let output = serde_json::to_string(&report).unwrap();
        assert!(output.contains("\"gateResult\":\"fail\""));
    }

    #[test]
    fn test_unknown_schema_version_error() {
        let json = r#"{
          "schemaVersion": "99",
          "generatedAt": "2026-05-04T12:00:00Z",
          "rustqutyVersion": "0.1.0",
          "project": {
            "name": "test",
            "rustEdition": "2021",
            "workspaceRoot": "/path"
          },
          "collectors": {
            "fmt": { "status": "pass", "details": {} },
            "clippy": { "status": "pass", "warningCount": 0, "details": [] },
            "tests": { "status": "pass", "passed": 0, "failed": 0, "ignored": 0 },
            "coverage": { "status": "pass", "linePercent": 0.0 },
            "deny": { "status": "pass", "bannedCount": 0, "licenseViolations": 0 },
            "audit": { "status": "pass", "vulnerabilityCount": 0, "criticalCount": 0 },
            "hack": { "status": "pass", "featureCombinationsTested": 0 },
            "mutants": { "status": "pass", "mutationScore": 0.0, "caught": 0, "missed": 0 },
            "duplicates": { "status": "pass", "totalLines": 1000, "duplicateLines": 0, "filesWithDuplicates": 0, "duplicateFiles": [] },
            "loc": { "status": "pass", "totalLines": 1000, "codeLines": 800, "commentLines": 100, "blankLines": 100, "longLines": 0, "maxLineLengthFound": 100, "maxLineLengthAllowed": 120, "files": 10, "filesWithLongLines": 0, "longLineFiles": [] }
          }
        }"#;
        let summary: MetricsSummary = serde_json::from_str(json).unwrap();
        let err = summary.check_version().unwrap_err();
        assert!(matches!(err, SchemaVersionError::UnknownVersion(v) if v == "99"));
    }
}