hotspots-cli 2.0.0

CLI that finds the riskiest code in your codebase by combining complexity with git change history (Local Risk Score) across TypeScript, JavaScript, Go, Python, Rust, and Java
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
use crate::cmd::analyze::analyze_and_persist_at_ref;
use crate::util::{find_repo_root, write_html_report};
use crate::OutputFormat;
use anyhow::Context;
use hotspots_core::delta::Delta;
use hotspots_core::git;
use hotspots_core::snapshot;
use std::path::PathBuf;

/// Structured error from [`load_snapshot_or_report`] so that the caller can
/// map each variant to a distinct exit code.
enum LoadError {
    /// Snapshot not yet generated — user needs to run `hotspots analyze`.
    Missing(String),
    /// Auto-analysis was attempted but failed (real execution error).
    Failed(String),
}

pub(crate) struct DiffArgs {
    pub base: String,
    pub head: String,
    pub format: OutputFormat,
    pub output: Option<PathBuf>,
    pub policy: bool,
    pub top: Option<usize>,
    pub config_path: Option<PathBuf>,
    pub auto_analyze: bool,
}

pub(crate) fn handle_diff(args: DiffArgs) -> anyhow::Result<()> {
    let DiffArgs {
        base,
        head,
        format,
        output,
        policy,
        top,
        config_path,
        auto_analyze,
    } = args;

    let repo_root = find_repo_root(&std::env::current_dir()?)?;

    let resolved_config =
        hotspots_core::config::load_and_resolve(&repo_root, config_path.as_deref())
            .context("failed to load configuration")?;

    // Resolve both refs to full SHAs
    let base_sha = git::resolve_ref_to_sha(&repo_root, &base)
        .with_context(|| format!("failed to resolve base ref '{base}'"))?;
    let head_sha = git::resolve_ref_to_sha(&repo_root, &head)
        .with_context(|| format!("failed to resolve head ref '{head}'"))?;

    // Load (or auto-analyze) both snapshots before bailing, so the user sees
    // all problems at once. Auto-analysis failures exit immediately with code 2
    // so CI can distinguish them from retriable "snapshot missing" conditions
    // (exit 3).
    let base_snapshot =
        load_snapshot_or_report(&repo_root, &base, &base_sha, auto_analyze, &resolved_config);
    let head_snapshot =
        load_snapshot_or_report(&repo_root, &head, &head_sha, auto_analyze, &resolved_config);

    let (base_snapshot, head_snapshot) = match (base_snapshot, head_snapshot) {
        (Ok(b), Ok(h)) => (b, h),
        (base_result, head_result) => {
            let mut any_failed = false;
            for result in [base_result, head_result] {
                match result {
                    Ok(_) => {}
                    Err(LoadError::Failed(msg)) => {
                        eprintln!("{msg}");
                        any_failed = true;
                    }
                    Err(LoadError::Missing(msg)) => {
                        eprintln!("{msg}");
                    }
                }
            }
            if any_failed {
                std::process::exit(2);
            }
            eprintln!("\nOnce both snapshots exist, re-run: hotspots diff {base} {head}");
            std::process::exit(3);
        }
    };

    // Compute delta
    let mut delta_val = Delta::new(&head_snapshot, Some(&base_snapshot))
        .context("failed to compute delta between snapshots")?;

    // Attach delta aggregates (file-level summaries used by HTML renderer)
    let current_co_change = head_snapshot
        .aggregates
        .as_ref()
        .map(|a| a.co_change.as_slice())
        .unwrap_or(&[]);
    let prev_co_change = base_snapshot
        .aggregates
        .as_ref()
        .map(|a| a.co_change.as_slice())
        .unwrap_or(&[]);
    // hotspots-research F132/F159/F161: fn_changed_lines (diff-changed lines inside touched
    // functions) is the strongest tested predictor of PR defect risk, beating every
    // LRS-weighted composite tried, including pr_risk_score itself. Best-effort — an
    // empty/failed git diff (e.g. shallow clone) degrades to an empty line-set map, giving 0,
    // not an error, matching extract_commit_churn_at's convention.
    let diff_lines = git::diff_line_sets_at(&repo_root, &base_sha, &head_sha).unwrap_or_default();
    let fn_changed_lines = git::compute_fn_changed_lines(
        &repo_root,
        &delta_val.deltas,
        &head_snapshot,
        &base_snapshot,
        &diff_lines,
    );
    delta_val.aggregates = Some(hotspots_core::aggregates::compute_delta_aggregates(
        &delta_val,
        current_co_change,
        prev_co_change,
        fn_changed_lines,
        &resolved_config.change_size_thresholds,
    ));

    // Filter out Unchanged, then optionally keep top N by risk magnitude
    {
        use hotspots_core::delta::FunctionStatus;
        delta_val
            .deltas
            .retain(|e| e.status != FunctionStatus::Unchanged);
    }
    if let Some(n) = top {
        use hotspots_core::delta::FunctionStatus;
        delta_val.deltas.sort_by(|a, b| {
            // New: rank by after.lrs; Deleted: rank by before.lrs; Modified: rank by |Δlrs|
            let score = |e: &hotspots_core::delta::FunctionDeltaEntry| match e.status {
                FunctionStatus::New => e.after.as_ref().map(|s| s.lrs).unwrap_or(0.0),
                FunctionStatus::Deleted => e.before.as_ref().map(|s| s.lrs).unwrap_or(0.0),
                FunctionStatus::Modified => e.delta.as_ref().map(|d| d.lrs.abs()).unwrap_or(0.0),
                FunctionStatus::Unchanged => 0.0,
            };
            score(b)
                .partial_cmp(&score(a))
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        delta_val.deltas.truncate(n);
    }

    // Evaluate policy if requested
    if policy {
        let policy_results = hotspots_core::policy::evaluate_policies(
            &delta_val,
            &head_snapshot,
            &repo_root,
            &resolved_config,
        )
        .context("failed to evaluate policies")?;
        if let Some(results) = policy_results {
            delta_val.policy = Some(results);
        }
    }

    // Render output
    let has_blocking_failures = emit_diff_output(&delta_val, format, policy, output)?;
    if has_blocking_failures {
        std::process::exit(1);
    }

    Ok(())
}

/// Try to load a snapshot. When `auto_analyze` is true and the snapshot is
/// missing, runs a full analysis at `sha` and persists the result.
///
/// Returns [`LoadError::Missing`] when the snapshot does not exist and
/// auto-analyze is off, or [`LoadError::Failed`] when auto-analysis was
/// attempted but encountered a real execution error.
fn load_snapshot_or_report(
    repo_root: &std::path::Path,
    git_ref: &str,
    sha: &str,
    auto_analyze: bool,
    resolved_config: &hotspots_core::config::ResolvedConfig,
) -> Result<hotspots_core::snapshot::Snapshot, LoadError> {
    match snapshot::load_snapshot(repo_root, sha) {
        Ok(Some(s)) => Ok(s),
        Ok(None) => {
            if auto_analyze {
                eprintln!("[hotspots] auto-analyzing '{}' ({})...", git_ref, &sha[..8]);
                analyze_and_persist_at_ref(repo_root, sha, resolved_config).map_err(|e| {
                    LoadError::Failed(format!(
                        "error: auto-analysis failed for '{git_ref}' ({}): {e}",
                        &sha[..8]
                    ))
                })
            } else {
                Err(LoadError::Missing(format!(
                    "error: no snapshot found for ref '{git_ref}' ({})\n  → run: git checkout {git_ref} && hotspots analyze --mode snapshot",
                    &sha[..8]
                )))
            }
        }
        Err(e) => Err(LoadError::Missing(format!(
            "error: failed to load snapshot for '{git_ref}' ({}): {e}",
            &sha[..8]
        ))),
    }
}

/// Render diff output. Returns true if there are blocking policy failures.
fn emit_diff_output(
    delta_val: &Delta,
    format: OutputFormat,
    with_policy: bool,
    output: Option<PathBuf>,
) -> anyhow::Result<bool> {
    let has_blocking_failures = delta_val
        .policy
        .as_ref()
        .map(|p| p.has_blocking_failures())
        .unwrap_or(false);

    match format {
        OutputFormat::Text => {
            let text = render_diff_text(delta_val, with_policy)?;
            write_or_print(output, &text)?;
        }
        OutputFormat::Json => {
            let json = delta_val.to_json()?;
            write_or_print(output, &json)?;
        }
        OutputFormat::Jsonl => {
            let jsonl = delta_val.to_jsonl()?;
            write_or_print(output, &jsonl)?;
        }
        OutputFormat::Html => {
            let html = hotspots_core::html::render_html_delta(delta_val, None);
            let output_path =
                output.unwrap_or_else(|| PathBuf::from(".hotspots/delta-report.html"));
            write_html_report(&output_path, &html)?;
            eprintln!("HTML report written to: {}", output_path.display());
        }
        OutputFormat::Sarif => {
            anyhow::bail!(
                "--format sarif is not supported for diff (use --format json or --format html)"
            );
        }
        OutputFormat::Csv => {
            anyhow::bail!(
                "--format csv is not supported for diff (use --format json or --format html)"
            );
        }
        OutputFormat::Xlsx => {
            anyhow::bail!(
                "--format xlsx is not supported for diff (use --format json or --format html)"
            );
        }
    }

    Ok(has_blocking_failures)
}

/// Write content to a file if `output` is Some, otherwise print to stdout.
fn write_or_print(output: Option<PathBuf>, content: &str) -> anyhow::Result<()> {
    match output {
        Some(path) => {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("failed to create directory: {}", parent.display()))?;
            }
            std::fs::write(&path, content)
                .with_context(|| format!("failed to write output to {}", path.display()))?;
            eprintln!("Output written to: {}", path.display());
        }
        None => print!("{content}"),
    }
    Ok(())
}

fn render_diff_text(delta_val: &Delta, with_policy: bool) -> anyhow::Result<String> {
    use hotspots_core::delta::FunctionStatus;
    use std::fmt::Write;

    let mut out = String::new();

    // Exclude pure renames (identical before/after, linked via `rename_hint`) from
    // new/deleted counts, matching `aggregates.rs`'s `compute_pr_risk_summary` — see
    // `pure_rename_function_ids`'s doc comment. Without this, this text summary
    // disagreed with the aggregate/risk-score surface, which already nets these out.
    let pure_renames = hotspots_core::delta::pure_rename_function_ids(&delta_val.deltas);
    let new_count = delta_val
        .deltas
        .iter()
        .filter(|e| e.status == FunctionStatus::New && !pure_renames.contains(&e.function_id))
        .count();
    let modified_count = delta_val
        .deltas
        .iter()
        .filter(|e| e.status == FunctionStatus::Modified)
        .count();
    let deleted_count = delta_val
        .deltas
        .iter()
        .filter(|e| e.status == FunctionStatus::Deleted && !pure_renames.contains(&e.function_id))
        .count();

    writeln!(
        out,
        "{modified_count} modified, {new_count} new, {deleted_count} deleted"
    )?;
    if let Some(summary) = delta_val.aggregates.as_ref().map(|a| &a.pr_summary) {
        writeln!(
            out,
            "Changed lines in touched functions: {} · {} (strongest tested predictor of \
             defect risk — hotspots-research F132/F159/F161; size band is a display \
             convenience, not itself research-derived — see docs/REFERENCE.md)",
            summary.fn_changed_lines, summary.size_band
        )?;
        writeln!(
            out,
            "PR risk score: {:+.2} (band: {}) — structural signal, not validated as beating \
             the line-count measure above",
            summary.pr_risk_score,
            summary.band.as_str()
        )?;
    }
    writeln!(out, "{}", "=".repeat(100))?;

    if delta_val.deltas.is_empty() {
        writeln!(out, "No changes.")?;
        return Ok(out);
    }

    writeln!(
        out,
        "{:<12} {:<40} {:<30} {:<14}  {:<14}  BAND",
        "STATUS", "FUNCTION", "FILE", "LRS", "CC"
    )?;
    writeln!(out, "{}", "-".repeat(100))?;

    for entry in &delta_val.deltas {
        let status_label = match entry.status {
            FunctionStatus::New => "new",
            FunctionStatus::Deleted => "deleted",
            FunctionStatus::Modified => "modified",
            FunctionStatus::Unchanged => continue,
        };

        let lrs_str = match (&entry.before, &entry.after) {
            (Some(b), Some(a)) => format!("{:.2} → {:.2}", b.lrs, a.lrs),
            (None, Some(a)) => format!("— → {:.2}", a.lrs),
            (Some(b), None) => format!("{:.2} → —", b.lrs),
            (None, None) => "—".to_string(),
        };

        let cc_str = match (&entry.before, &entry.after) {
            (Some(b), Some(a)) => format!("{} → {}", b.metrics.cc, a.metrics.cc),
            (None, Some(a)) => format!("— → {}", a.metrics.cc),
            (Some(b), None) => format!("{} → —", b.metrics.cc),
            (None, None) => "—".to_string(),
        };

        let band_str = match entry.band_transition.as_ref() {
            Some(t) => format!("{} → {}", t.from, t.to),
            None => entry
                .after
                .as_ref()
                .or(entry.before.as_ref())
                .map(|s| s.band.as_str().to_string())
                .unwrap_or_else(|| "-".to_string()),
        };

        // function_id is "file::function"; split for display
        let (file_display, fn_display) = entry
            .function_id
            .split_once("::")
            .unwrap_or(("", &entry.function_id));

        writeln!(
            out,
            "{:<12} {:<40} {:<30} {:<14}  {:<14}  {}",
            status_label,
            crate::util::truncate_string(fn_display, 40),
            crate::util::truncate_string(file_display, 30),
            lrs_str,
            cc_str,
            band_str,
        )?;
    }

    if with_policy {
        if let Some(ref policy_results) = delta_val.policy {
            writeln!(out)?;
            write!(
                out,
                "{}",
                crate::output::policy::render_policy_text_output(delta_val, policy_results)?
            )?;
        }
    }

    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use hotspots_core::delta::{
        DeltaCommitInfo, FunctionDeltaEntry, FunctionState, FunctionStatus,
    };
    use hotspots_core::report::MetricsReport;
    use hotspots_core::risk::RiskBand;

    fn state() -> FunctionState {
        FunctionState {
            metrics: MetricsReport {
                cc: 1,
                nd: 1,
                fo: 1,
                ns: 1,
                loc: 5,
            },
            lrs: 5.4,
            band: RiskBand::Moderate,
        }
    }

    #[test]
    fn test_render_diff_text_nets_out_pure_rename_from_headline_counts() {
        // Regression for #223: the headline "N modified, N new, N deleted" line
        // is computed independently from `aggregates.rs`'s PR-risk-summary path
        // (which already nets out pure renames) — without applying the same
        // `pure_rename_function_ids` filter here, this line disagreed with the
        // aggregate/risk-score surface for the exact same delta.
        let mut deleted = FunctionDeltaEntry {
            function_id: "old/path.go::Foo".to_string(),
            status: FunctionStatus::Deleted,
            before: Some(state()),
            after: None,
            delta: None,
            band_transition: None,
            suppression_reason: None,
            rename_hint: Some("new/path.go::Foo".to_string()),
        };
        deleted.before = Some(state());

        let created = FunctionDeltaEntry {
            function_id: "new/path.go::Foo".to_string(),
            status: FunctionStatus::New,
            before: None,
            after: Some(state()),
            delta: None,
            band_transition: None,
            suppression_reason: None,
            rename_hint: None,
        };

        let delta_val = Delta {
            commit: DeltaCommitInfo {
                sha: "head".to_string(),
                parent: "base".to_string(),
            },
            baseline: false,
            deltas: vec![deleted, created],
            policy: None,
            aggregates: None,
        };

        let text = render_diff_text(&delta_val, false).expect("render");
        assert!(
            text.starts_with("0 modified, 0 new, 0 deleted"),
            "pure rename should net to zero, got: {text}"
        );
    }
}