covguard-reporting 0.1.0

Report construction for covguard (standard + sensor schemas)
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
//! Report assembly and schema composition for covguard.

use chrono::{DateTime, Utc};

use covguard_domain::EvalOutput;
use covguard_output::truncate_findings;
use covguard_types::{
    CHECK_ID_RUNTIME, CODE_COVERAGE_BELOW_THRESHOLD, CODE_RUNTIME_ERROR, Capabilities, Finding,
    InputCapability, InputStatus, Inputs, InputsCapability, REASON_BELOW_THRESHOLD,
    REASON_DIFF_COVERED, REASON_MISSING_DIFF, REASON_MISSING_LCOV, REASON_NO_CHANGED_LINES,
    REASON_SKIPPED, REASON_TOOL_ERROR, REASON_TRUNCATED, REASON_UNCOVERED_LINES, Report,
    ReportData, SCHEMA_ID, SENSOR_SCHEMA_ID, Scope, Severity, Tool, Verdict, VerdictCounts,
    VerdictStatus, compute_fingerprint,
};

/// Context needed to materialize reports from `EvalOutput`.
#[derive(Debug, Clone)]
pub struct ReportContext {
    /// Coverage threshold used for the run.
    pub threshold_pct: f64,
    /// Evaluation scope (`added` or `touched`).
    pub scope: Scope,
    /// Emit `sensor.report.v1` with capability metadata.
    pub sensor_schema: bool,
    /// Optional findings cap for standard-mode reports.
    pub max_findings: Option<usize>,
    /// Path to a diff file, if available.
    pub diff_file_path: Option<String>,
    /// Base ref in git-diff mode.
    pub base_ref: Option<String>,
    /// Head ref in git-diff mode.
    pub head_ref: Option<String>,
    /// LCOV paths to include in report metadata.
    pub lcov_paths: Vec<String>,
}

impl ReportContext {
    fn diff_source(&self) -> &'static str {
        if self.diff_file_path.is_some() {
            "diff-file"
        } else if self.base_ref.is_some() && self.head_ref.is_some() {
            "git-refs"
        } else {
            "stdin"
        }
    }

    fn scope(&self) -> &str {
        self.scope.as_str()
    }

    fn inputs(&self) -> Inputs {
        Inputs {
            diff_source: self.diff_source().to_string(),
            diff_file: self.diff_file_path.clone(),
            base: self.base_ref.clone(),
            head: self.head_ref.clone(),
            lcov_paths: self.lcov_paths.clone(),
        }
    }
}

fn report_run(started_at: DateTime<Utc>, ended_at: DateTime<Utc>) -> covguard_types::Run {
    covguard_types::Run {
        started_at: started_at.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
        ended_at: Some(ended_at.format("%Y-%m-%dT%H:%M:%SZ").to_string()),
        duration_ms: Some((ended_at - started_at).num_milliseconds().max(0) as u64),
        capabilities: None,
    }
}

fn finding_counts(eval: &EvalOutput) -> VerdictCounts {
    VerdictCounts {
        info: eval
            .findings
            .iter()
            .filter(|finding| finding.severity == Severity::Info)
            .count() as u32,
        warn: eval
            .findings
            .iter()
            .filter(|finding| finding.severity == Severity::Warn)
            .count() as u32,
        error: eval
            .findings
            .iter()
            .filter(|finding| finding.severity == Severity::Error)
            .count() as u32,
    }
}

/// Build a pair of reports: domain and optional cockpit receipt.
pub fn build_report_pair(
    eval: EvalOutput,
    context: &ReportContext,
    started_at: DateTime<Utc>,
    ended_at: DateTime<Utc>,
    excluded_files_count: u32,
    debug: Option<serde_json::Value>,
) -> (Report, Option<Report>) {
    let inputs = context.inputs();
    let run = report_run(started_at, ended_at);
    let counts = finding_counts(&eval);
    let reasons = build_reasons(&eval);
    let scope = context.scope().to_string();
    let tool = Tool {
        name: "covguard".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        commit: None,
    };

    let cockpit_receipt = if context.sensor_schema {
        let capabilities = Some(Capabilities {
            inputs: InputsCapability {
                diff: InputCapability {
                    status: InputStatus::Available,
                    reason: None,
                },
                coverage: InputCapability {
                    status: InputStatus::Available,
                    reason: None,
                },
            },
        });

        let (cockpit_findings, cockpit_truncation) =
            truncate_findings(eval.findings.clone(), context.max_findings);

        let mut cockpit_reasons = reasons.clone();
        if cockpit_truncation.is_some() {
            cockpit_reasons.push(REASON_TRUNCATED.to_string());
        }

        Some(Report {
            schema: SENSOR_SCHEMA_ID.to_string(),
            tool: tool.clone(),
            run: covguard_types::Run {
                capabilities,
                ..run.clone()
            },
            verdict: Verdict {
                status: eval.verdict,
                counts: counts.clone(),
                reasons: cockpit_reasons,
            },
            findings: cockpit_findings,
            data: ReportData {
                scope: scope.clone(),
                threshold_pct: context.threshold_pct,
                changed_lines_total: eval.metrics.changed_lines_total,
                covered_lines: eval.metrics.covered_lines,
                uncovered_lines: eval.metrics.uncovered_lines,
                missing_lines: eval.metrics.missing_lines,
                ignored_lines_count: eval.metrics.ignored_lines,
                excluded_files_count,
                diff_coverage_pct: eval.metrics.diff_coverage_pct,
                inputs: inputs.clone(),
                debug: debug.clone(),
                truncation: cockpit_truncation,
            },
        })
    } else {
        None
    };

    let (domain_findings, domain_truncation) = if context.sensor_schema {
        (eval.findings, None)
    } else {
        truncate_findings(eval.findings, context.max_findings)
    };

    let mut domain_reasons = reasons;
    if domain_truncation.is_some() {
        domain_reasons.push(REASON_TRUNCATED.to_string());
    }

    let domain_report = Report {
        schema: SCHEMA_ID.to_string(),
        tool,
        run: covguard_types::Run {
            capabilities: None,
            ..run
        },
        verdict: Verdict {
            status: eval.verdict,
            counts,
            reasons: domain_reasons,
        },
        findings: domain_findings,
        data: ReportData {
            scope,
            threshold_pct: context.threshold_pct,
            changed_lines_total: eval.metrics.changed_lines_total,
            covered_lines: eval.metrics.covered_lines,
            uncovered_lines: eval.metrics.uncovered_lines,
            missing_lines: eval.metrics.missing_lines,
            ignored_lines_count: eval.metrics.ignored_lines,
            excluded_files_count,
            diff_coverage_pct: eval.metrics.diff_coverage_pct,
            inputs,
            debug,
            truncation: domain_truncation,
        },
    };

    (domain_report, cockpit_receipt)
}

/// Build only the domain report from evaluation output.
pub fn build_report(
    eval: EvalOutput,
    context: &ReportContext,
    started_at: DateTime<Utc>,
    ended_at: DateTime<Utc>,
    excluded_files_count: u32,
    debug: Option<serde_json::Value>,
) -> Report {
    let (report, _) = build_report_pair(
        eval,
        context,
        started_at,
        ended_at,
        excluded_files_count,
        debug,
    );
    report
}

/// Build both domain report and optional cockpit receipt for runtime error cases.
pub fn build_error_report_pair(
    context: &ReportContext,
    started_at: DateTime<Utc>,
    ended_at: DateTime<Utc>,
    code: &str,
    message: &str,
    diff_available: bool,
    coverage_available: bool,
) -> (Report, Option<Report>) {
    let inputs = context.inputs();

    let input_fp = compute_fingerprint(&[code, "covguard"]);
    let runtime_fp = compute_fingerprint(&[CODE_RUNTIME_ERROR, "covguard"]);

    let findings = vec![
        Finding {
            severity: Severity::Error,
            check_id: "input.invalid".to_string(),
            code: code.to_string(),
            message: message.to_string(),
            location: None,
            data: None,
            fingerprint: Some(input_fp),
        },
        Finding {
            severity: Severity::Error,
            check_id: CHECK_ID_RUNTIME.to_string(),
            code: CODE_RUNTIME_ERROR.to_string(),
            message: "covguard failed due to a runtime error.".to_string(),
            location: None,
            data: None,
            fingerprint: Some(runtime_fp),
        },
    ];

    let counts = VerdictCounts {
        info: 0,
        warn: 0,
        error: findings.len() as u32,
    };

    let scope = context.scope().to_string();
    let tool = Tool {
        name: "covguard".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        commit: None,
    };
    let run = report_run(started_at, ended_at);

    let data = ReportData {
        scope,
        threshold_pct: context.threshold_pct,
        changed_lines_total: 0,
        covered_lines: 0,
        uncovered_lines: 0,
        missing_lines: 0,
        ignored_lines_count: 0,
        excluded_files_count: 0,
        diff_coverage_pct: 0.0,
        inputs,
        debug: None,
        truncation: None,
    };

    let cockpit_receipt = if context.sensor_schema {
        let capabilities = Some(Capabilities {
            inputs: InputsCapability {
                diff: InputCapability {
                    status: if diff_available {
                        InputStatus::Available
                    } else {
                        InputStatus::Unavailable
                    },
                    reason: if diff_available {
                        None
                    } else {
                        Some(REASON_MISSING_DIFF.to_string())
                    },
                },
                coverage: InputCapability {
                    status: if coverage_available {
                        InputStatus::Available
                    } else {
                        InputStatus::Unavailable
                    },
                    reason: if coverage_available {
                        None
                    } else {
                        Some(REASON_MISSING_LCOV.to_string())
                    },
                },
            },
        });

        Some(Report {
            schema: SENSOR_SCHEMA_ID.to_string(),
            tool: tool.clone(),
            run: covguard_types::Run {
                capabilities,
                ..run.clone()
            },
            verdict: Verdict {
                status: VerdictStatus::Fail,
                counts: counts.clone(),
                reasons: vec![REASON_TOOL_ERROR.to_string()],
            },
            findings: findings.clone(),
            data: data.clone(),
        })
    } else {
        None
    };

    let domain_report = Report {
        schema: SCHEMA_ID.to_string(),
        tool,
        run: covguard_types::Run {
            capabilities: None,
            ..run
        },
        verdict: Verdict {
            status: VerdictStatus::Fail,
            counts,
            reasons: vec![REASON_TOOL_ERROR.to_string()],
        },
        findings,
        data,
    };

    (domain_report, cockpit_receipt)
}

/// Build both domain report and optional cockpit receipt for skip cases.
pub fn build_skip_report_pair(
    context: &ReportContext,
    started_at: DateTime<Utc>,
    ended_at: DateTime<Utc>,
    diff_available: bool,
    coverage_available: bool,
    reason: &str,
) -> (Report, Option<Report>) {
    let inputs = context.inputs();
    let capabilities = Capabilities {
        inputs: InputsCapability {
            diff: InputCapability {
                status: if diff_available {
                    InputStatus::Available
                } else {
                    InputStatus::Unavailable
                },
                reason: if diff_available {
                    None
                } else {
                    Some(REASON_MISSING_DIFF.to_string())
                },
            },
            coverage: InputCapability {
                status: if coverage_available {
                    InputStatus::Available
                } else {
                    InputStatus::Unavailable
                },
                reason: if coverage_available {
                    None
                } else {
                    Some(REASON_MISSING_LCOV.to_string())
                },
            },
        },
    };

    let run = report_run(started_at, ended_at);
    let scope = context.scope().to_string();
    let tool = Tool {
        name: "covguard".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
        commit: None,
    };

    let data = ReportData {
        scope,
        threshold_pct: context.threshold_pct,
        changed_lines_total: 0,
        covered_lines: 0,
        uncovered_lines: 0,
        missing_lines: 0,
        ignored_lines_count: 0,
        excluded_files_count: 0,
        diff_coverage_pct: 0.0,
        inputs,
        debug: None,
        truncation: None,
    };

    let cockpit_receipt = if context.sensor_schema {
        Some(Report {
            schema: SENSOR_SCHEMA_ID.to_string(),
            tool: tool.clone(),
            run: covguard_types::Run {
                capabilities: Some(capabilities),
                ..run.clone()
            },
            verdict: Verdict {
                status: VerdictStatus::Skip,
                counts: VerdictCounts {
                    info: 0,
                    warn: 0,
                    error: 0,
                },
                reasons: vec![reason.to_string()],
            },
            findings: vec![],
            data: data.clone(),
        })
    } else {
        None
    };

    let domain_report = Report {
        schema: SCHEMA_ID.to_string(),
        tool,
        run: covguard_types::Run {
            capabilities: None,
            ..run
        },
        verdict: Verdict {
            status: VerdictStatus::Skip,
            counts: VerdictCounts {
                info: 0,
                warn: 0,
                error: 0,
            },
            reasons: vec![reason.to_string()],
        },
        findings: vec![],
        data,
    };

    (domain_report, cockpit_receipt)
}

/// Check if diff input looks invalid at a basic marker level.
pub fn is_invalid_diff(diff_text: &str) -> bool {
    let trimmed = diff_text.trim();
    if trimmed.is_empty() {
        return false;
    }

    let has_marker = trimmed.contains("diff --git")
        || trimmed.contains("@@")
        || trimmed.contains("+++ ")
        || trimmed.contains("--- ")
        || trimmed.contains("rename from ")
        || trimmed.contains("rename to ");
    !has_marker
}

/// Build report-level reasons from verdict metrics and findings.
pub fn build_reasons(output: &EvalOutput) -> Vec<String> {
    let mut reasons = Vec::new();

    match output.verdict {
        VerdictStatus::Pass => {
            if output.metrics.changed_lines_total == 0 {
                reasons.push(REASON_NO_CHANGED_LINES.to_string());
            } else {
                reasons.push(REASON_DIFF_COVERED.to_string());
            }
        }
        VerdictStatus::Warn | VerdictStatus::Fail => {
            if output.metrics.uncovered_lines > 0 {
                reasons.push(REASON_UNCOVERED_LINES.to_string());
            }
            if output
                .findings
                .iter()
                .any(|finding| finding.code == CODE_COVERAGE_BELOW_THRESHOLD)
            {
                reasons.push(REASON_BELOW_THRESHOLD.to_string());
            }
        }
        VerdictStatus::Skip => {
            reasons.push(REASON_SKIPPED.to_string());
        }
    }

    reasons
}

/// Build debug payload for binary file lists.
pub fn build_debug(binary_files: &[String]) -> Option<serde_json::Value> {
    if binary_files.is_empty() {
        None
    } else {
        Some(serde_json::json!({
            "binary_files_count": binary_files.len(),
            "binary_files": binary_files,
        }))
    }
}