repotoire 0.7.1

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Output and formatting functions for the analyze command
//!
//! This module contains all output-related logic:
//! - Formatting reports (text, JSON, SARIF, etc.)
//! - Filtering and pagination
//! - Caching results
//! - Threshold checks for CI/CD

use crate::models::{Finding, FindingsSummary, HealthReport, Severity};
use crate::reporters;
use anyhow::Result;
use console::style;
use std::path::{Path, PathBuf};

/// Normalize a path to be relative
fn normalize_path(path: &Path) -> String {
    let path_str = path.display().to_string();
    if let Some(stripped) = path_str.strip_prefix("/tmp/") {
        if let Some(pos) = stripped.find('/') {
            return stripped[pos + 1..].to_string();
        }
    }
    if let Ok(home) = std::env::var("HOME") {
        if let Some(stripped) = path_str.strip_prefix(&home) {
            return stripped.trim_start_matches('/').to_string();
        }
    }
    path_str
}

/// Filter findings by severity and limit
pub(crate) fn filter_findings(
    findings: &mut Vec<Finding>,
    severity: Option<Severity>,
    top: Option<usize>,
) {
    if let Some(min) = severity {
        findings.retain(|f| f.severity >= min);
    }

    findings.sort_by_key(|f| std::cmp::Reverse(f.severity));

    if let Some(n) = top {
        findings.truncate(n);
    }
}

/// Paginate findings
pub(crate) fn paginate_findings(
    mut findings: Vec<Finding>,
    page: usize,
    per_page: usize,
) -> (Vec<Finding>, Option<(usize, usize, usize, usize)>) {
    // Sort for deterministic output: severity (desc), then file, then line (#47)
    findings.sort_by(|a, b| {
        (b.severity as u8)
            .cmp(&(a.severity as u8))
            .then_with(|| {
                let a_file = a
                    .affected_files
                    .first()
                    .map(|f| f.to_string_lossy().to_string())
                    .unwrap_or_default();
                let b_file = b
                    .affected_files
                    .first()
                    .map(|f| f.to_string_lossy().to_string())
                    .unwrap_or_default();
                a_file.cmp(&b_file)
            })
            .then_with(|| a.line_start.cmp(&b.line_start))
            .then_with(|| a.detector.cmp(&b.detector))
            .then_with(|| a.title.cmp(&b.title))
    });

    let displayed_findings = findings.len();

    if per_page > 0 {
        let total_pages = displayed_findings.div_ceil(per_page);
        let page = page.max(1).min(total_pages.max(1));
        let start = (page - 1) * per_page;
        let end = (start + per_page).min(displayed_findings);
        let paginated: Vec<_> = findings[start..end].to_vec();
        (
            paginated,
            Some((page, total_pages, per_page, displayed_findings)),
        )
    } else {
        (findings, None)
    }
}

/// Inputs for [`format_and_output`]: bundles the report, finding list, and
/// the renderer-specific knobs (format, output path, pagination flags).
pub(crate) struct FormatAndOutputArgs<'a> {
    pub report: &'a HealthReport,
    pub all_findings: &'a [Finding],
    pub format: reporters::OutputFormat,
    pub output_path: Option<&'a Path>,
    pub repotoire_dir: &'a Path,
    /// Optional pagination metadata: `(page, per_page, total_pages, total_findings)`.
    pub pagination_info: Option<(usize, usize, usize, usize)>,
    /// Number of findings actually displayed on the current page. Currently
    /// reserved; consumers compute their own counts from the slice.
    pub displayed_findings: usize,
    pub no_emoji: bool,
}

/// Format and output results
pub(crate) fn format_and_output(args: FormatAndOutputArgs<'_>) -> Result<()> {
    let FormatAndOutputArgs {
        report,
        all_findings,
        format,
        output_path,
        repotoire_dir,
        pagination_info,
        displayed_findings: _displayed_findings,
        no_emoji,
    } = args;
    use reporters::OutputFormat;

    // For file-based export formats (SARIF, HTML, Markdown), use ALL findings
    // to avoid truncating to page size. Pagination is for terminal display only.
    // Use all findings for file-based exports; JSON only when writing to file (#58)
    let use_all = matches!(
        format,
        OutputFormat::Sarif | OutputFormat::Html | OutputFormat::Markdown
    ) || (format == OutputFormat::Json && output_path.is_some());
    let report_for_output = if use_all && !all_findings.is_empty() {
        let mut full_report = report.clone();
        full_report.findings = all_findings.to_vec();
        full_report.findings_summary = FindingsSummary::from_findings(all_findings);
        full_report
    } else {
        // For JSON stdout / text: ensure findings_summary matches the
        // actual findings array (which may be paginated)
        let mut r = report.clone();
        r.findings_summary = FindingsSummary::from_findings(&r.findings);
        r
    };

    let output_str = reporters::report_with_format(&report_for_output, format)?;

    // Only write to file if --output was explicitly provided (#59)
    let write_to_file = output_path.is_some();

    if write_to_file {
        let out_path = if let Some(p) = output_path {
            p.to_path_buf()
        } else {
            let ext = reporters::file_extension(format);
            repotoire_dir.join(format!("report.{}", ext))
        };

        std::fs::write(&out_path, &output_str)?;
        let file_icon = if no_emoji { "" } else { "📄 " };
        // Use stderr for machine-readable formats to keep stdout clean
        eprintln!(
            "\n{}Report written to: {}",
            style(file_icon).bold(),
            style(out_path.display()).cyan()
        );
    } else {
        // For machine-readable formats, skip leading newline to keep stdout clean
        if !matches!(format, OutputFormat::Json | OutputFormat::Sarif) {
            println!();
        }
        println!("{}", output_str);
    }

    // Cache results
    cache_results(repotoire_dir, report, all_findings)?;

    // Show pagination info (suppress for machine-readable and file-based formats)
    let quiet_mode = matches!(
        format,
        OutputFormat::Json | OutputFormat::Sarif | OutputFormat::Html | OutputFormat::Markdown
    ) || output_path.is_some();
    if let Some((current_page, total_pages, per_page, total)) =
        pagination_info.filter(|_| !quiet_mode)
    {
        let page_icon = if no_emoji { "" } else { "📑 " };
        println!(
            "\n{}Showing page {} of {} ({} findings per page, {} total)",
            style(page_icon).bold(),
            style(current_page).cyan(),
            style(total_pages).cyan(),
            style(per_page).dim(),
            style(total).cyan(),
        );
        if current_page < total_pages {
            println!(
                "   Use {} to see more",
                style(format!("--page {}", current_page + 1)).yellow()
            );
        }
    }

    Ok(())
}

/// Check if fail threshold is met
pub(crate) fn check_fail_threshold(fail_on: Option<Severity>, report: &HealthReport) -> Result<()> {
    if let Some(threshold) = fail_on {
        let should_fail = match threshold {
            Severity::Critical => report.findings_summary.critical > 0,
            Severity::High => {
                report.findings_summary.critical > 0 || report.findings_summary.high > 0
            }
            Severity::Medium => {
                report.findings_summary.critical > 0
                    || report.findings_summary.high > 0
                    || report.findings_summary.medium > 0
            }
            Severity::Low => {
                report.findings_summary.critical > 0
                    || report.findings_summary.high > 0
                    || report.findings_summary.medium > 0
                    || report.findings_summary.low > 0
            }
            Severity::Info => {
                report.findings_summary.critical > 0
                    || report.findings_summary.high > 0
                    || report.findings_summary.medium > 0
                    || report.findings_summary.low > 0
            }
        };
        if should_fail {
            // Return error instead of process::exit to allow cleanup (#19)
            anyhow::bail!("Failing due to --fail-on={} threshold", threshold);
        }
    }
    Ok(())
}

/// Load findings from a specific JSON file path.
/// Returns None if the file doesn't exist or can't be parsed.
pub fn load_cached_findings_from(path: &Path) -> Option<Vec<Finding>> {
    load_findings_from_file(path)
}

/// Load post-processed findings from last_findings.json cache
/// Returns None if the cache file doesn't exist or can't be parsed
pub fn load_cached_findings(repotoire_dir: &Path) -> Option<Vec<Finding>> {
    load_findings_from_file(&repotoire_dir.join("last_findings.json"))
}

/// Load findings from a specific JSON file path.
/// Shared implementation for both `load_cached_findings` and `load_cached_findings_from`.
fn load_findings_from_file(path: &Path) -> Option<Vec<Finding>> {
    let data = std::fs::read_to_string(path).ok()?;
    let json: serde_json::Value = serde_json::from_str(&data).ok()?;

    // Version check: reject stale findings from different binary version
    let cached_version = json.get("version").and_then(|v| v.as_str()).unwrap_or("");
    if cached_version != env!("CARGO_PKG_VERSION") {
        tracing::debug!(
            "Findings cache version mismatch ({} vs {}), ignoring",
            cached_version,
            env!("CARGO_PKG_VERSION")
        );
        return None;
    }

    let findings_arr = json.get("findings")?.as_array()?;

    let mut findings = Vec::new();
    for f in findings_arr {
        let severity = f
            .get("severity")?
            .as_str()?
            .parse::<Severity>()
            .unwrap_or(Severity::Info);

        let affected_files: Vec<PathBuf> = f
            .get("affected_files")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(PathBuf::from))
                    .collect()
            })
            .unwrap_or_default();

        findings.push(Finding {
            id: f
                .get("id")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            detector: f
                .get("detector")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            title: f
                .get("title")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            description: f
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            severity,
            affected_files,
            line_start: f
                .get("line_start")
                .and_then(|v| v.as_u64())
                .map(|v| v as u32),
            line_end: f.get("line_end").and_then(|v| v.as_u64()).map(|v| v as u32),
            suggested_fix: f
                .get("suggested_fix")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            category: f
                .get("category")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            cwe_id: f
                .get("cwe_id")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            why_it_matters: f
                .get("why_it_matters")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            confidence: f.get("confidence").and_then(|v| v.as_f64()),
            ..Default::default()
        });
    }

    tracing::debug!(
        "Loaded {} post-processed findings from {}",
        findings.len(),
        path.display()
    );
    Some(findings)
}

/// Cache analysis results for other commands.
///
/// Before writing new results, snapshots the current cache as baseline
/// for `repotoire diff` to compare against.
pub fn cache_results(
    repotoire_dir: &Path,
    report: &HealthReport,
    all_findings: &[Finding],
) -> Result<()> {
    use std::fs;

    // Snapshot current cache as diff baseline (before overwriting)
    let findings_cache = repotoire_dir.join("last_findings.json");
    let health_cache = repotoire_dir.join("last_health.json");
    if findings_cache.exists() {
        let _ = fs::copy(
            &findings_cache,
            repotoire_dir.join("baseline_findings.json"),
        );
    }
    if health_cache.exists() {
        let _ = fs::copy(&health_cache, repotoire_dir.join("baseline_health.json"));
    }

    let health_cache = repotoire_dir.join("last_health.json");
    // Write both `health_score` (read by `repotoire diff` score delta) and
    // `overall_score` (read by `repotoire benchmark`) so either consumer finds
    // what it expects without a second writer.
    let health_json = serde_json::json!({
        "health_score": report.overall_score,
        "overall_score": report.overall_score,
        "structure_score": report.structure_score,
        "quality_score": report.quality_score,
        "architecture_score": report.architecture_score,
        "grade": report.grade,
        "total_files": report.total_files,
        "total_functions": report.total_functions,
        "total_classes": report.total_classes,
        "total_loc": report.total_loc,
    });
    fs::write(&health_cache, serde_json::to_string_pretty(&health_json)?)?;

    let findings_cache = repotoire_dir.join("last_findings.json");
    let findings_json = serde_json::json!({
        "version": env!("CARGO_PKG_VERSION"),
        "findings": all_findings.iter().map(|f| {
            serde_json::json!({
                "id": f.id,
                "detector": f.detector,
                "title": f.title,
                "description": f.description,
                "severity": f.severity.to_string(),
                "affected_files": f.affected_files.iter().map(|p| normalize_path(p)).collect::<Vec<_>>(),
                "line_start": f.line_start,
                "line_end": f.line_end,
                "suggested_fix": f.suggested_fix,
                "category": f.category,
                "cwe_id": f.cwe_id,
                "why_it_matters": f.why_it_matters,
                "confidence": f.confidence,
                "threshold_metadata": &f.threshold_metadata,
            })
        }).collect::<Vec<_>>()
    });
    fs::write(&findings_cache, serde_json::to_string(&findings_json)?)?;

    tracing::debug!("Cached analysis results to {}", repotoire_dir.display());
    Ok(())
}