use std::path::Path;
use serde::Serialize;
use lean_ctx_ext::core::hotspots::{self, Action, Entry, Loaded, Report, Source, Window};
use super::routes::{Method, Param, Project, Route, Shape};
use super::{Answer, Code, Failure, Via};
pub(crate) const KIND: &str = "hotspots.report";
pub(crate) const ROUTES: &[Route] = &[Route {
kind: KIND,
method: Method::Get,
path: "/v1/local/hotspots",
cli: &["hotspots", "--json"],
action: &[],
params: &[
Param {
name: "project_root",
flag: "--project-root",
shape: Shape::Value,
},
Param {
name: "limit",
flag: "--limit",
shape: Shape::Value,
},
],
project: Project::Required,
names: None,
}];
pub(crate) const KINDS: &[&str] = &[KIND];
pub(crate) const COMMANDS: &[(&str, &[&str])] = &[("hotspots", &[])];
#[derive(Debug, Serialize)]
pub(crate) struct PlanItem {
pub path: String,
pub score: u32,
pub actions: Vec<Action>,
}
#[derive(Debug, Serialize)]
pub(crate) struct HotspotsDoc {
pub project_root: String,
pub source: Source,
pub weave_file: &'static str,
pub window: Option<Window>,
pub report: Report,
pub plan: Vec<PlanItem>,
}
fn plan(entries: &[Entry]) -> Vec<PlanItem> {
entries
.iter()
.map(|e| PlanItem {
path: e.path.clone(),
score: e.score,
actions: hotspots::plan_for(e),
})
.collect()
}
pub(crate) fn hotspots_doc(project_root: &str, loaded: Loaded) -> HotspotsDoc {
HotspotsDoc {
project_root: project_root.to_owned(),
source: loaded.source,
weave_file: loaded.weave_file.as_str(),
window: loaded.window,
plan: plan(&loaded.report.entries),
report: loaded.report,
}
}
fn build(root: &str, limit: usize) -> Result<HotspotsDoc, Failure> {
let work_tree = hotspots::repo_root(Path::new(root)).ok_or_else(|| {
Failure::new(Code::NoProject, format!("{root} is not in a git work tree"))
})?;
let loaded = hotspots::load(&work_tree, Window::default(), limit)
.map_err(|reason| Failure::new(Code::Unavailable, reason))?;
Ok(hotspots_doc(root, loaded))
}
fn request(args: &[String]) -> Result<(String, usize), Failure> {
let root = super::project_root(args)?;
let limit = super::limit(args, hotspots::DEFAULT_LIMIT, hotspots::MAX_LIMIT)?;
Ok((root, limit))
}
pub(crate) fn answer(kind: &str, args: &[String], via: Via) -> Answer {
match kind {
KIND => {
let (root, limit) = match request(args) {
Ok(parts) => parts,
Err(failure) => return Answer::failure(&failure),
};
super::answer_released("ctx_read", &root, kind, via, || build(&root, limit))
}
other => Answer::failure(&Failure::invalid(format!("unknown kind {other}"))),
}
}
pub(crate) fn try_run(command: &str, rest: &[String]) -> bool {
if command != "hotspots" || !super::wants_json(rest) || has_help(rest) {
return false;
}
super::print(&answer(KIND, rest, Via::Cli));
true
}
const USAGE: &str = "Usage: lean-ctx hotspots [--limit N] [--project-root P] [--json]
Files that change most, are changed by merges and reverted, and are large,
with a refactor plan per file. Uses Weave's .leanctx/hotspots.json
(hotspots-v1) when present, else the last 1000 commits and 200 merges.
--limit N files to list (1-200, default 20)
--project-root P the project (default: the current one)
--json the Local Read document (kind hotspots.report)";
fn has_help(rest: &[String]) -> bool {
rest.iter().any(|a| a == "--help" || a == "-h")
}
pub(crate) fn render(doc: &HotspotsDoc) -> String {
let mut out = String::new();
let from = match (doc.source, &doc.report.generated_from) {
(Source::Weave, Some(sha)) => format!("Weave report at {}", &sha[..12.min(sha.len())]),
(Source::Weave, None) => "Weave report".to_owned(),
(Source::Git, Some(sha)) => format!(
"local git history at {} (last {} commits, {} merges)",
&sha[..12.min(sha.len())],
hotspots::DEFAULT_COMMITS,
hotspots::DEFAULT_MERGES
),
(Source::Git, None) => "local git history".to_owned(),
};
out.push_str(&format!("Hotspots from {from}\n"));
if doc.weave_file == "invalid" {
out.push_str(&format!(
"Note: {} is not a valid {} report and was ignored\n",
hotspots::WEAVE_FILE,
hotspots::SCHEMA
));
}
if doc.report.entries.is_empty() {
out.push_str("No hotspots: no file changed often enough.\n");
return out;
}
for (entry, item) in doc.report.entries.iter().zip(&doc.plan) {
out.push_str(&format!(
"\n{:>3} {}\n {} commits · {} merge changes · {} reverts · {} lines\n",
entry.score, entry.path, entry.churn, entry.conflicts, entry.reverts, entry.size
));
if doc.source == Source::Weave
&& let Some(hint) = &entry.refactor_hint
{
out.push_str(&format!(
" hint (from {}): {hint}\n",
hotspots::WEAVE_FILE
));
}
for action in &item.actions {
out.push_str(&format!(" - {}: {}\n", action.action, action.reason));
}
}
out
}
pub(crate) fn run(rest: &[String]) {
if has_help(rest) {
println!("{USAGE}");
return;
}
if try_run("hotspots", rest) {
return;
}
match request(rest).and_then(|(root, limit)| build(&root, limit)) {
Ok(doc) => print!("{}", render(&doc)),
Err(failure) => {
eprintln!("lean-ctx hotspots: {}", failure.message);
std::process::exit(1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
fn words(w: &[&str]) -> Vec<String> {
w.iter().map(|s| (*s).to_owned()).collect()
}
fn git(dir: &Path, args: &[&str]) {
let out = Command::new("git")
.args([
"-c",
"commit.gpgsign=false",
"-c",
"init.defaultBranch=main",
])
.args(args)
.current_dir(dir)
.env("GIT_AUTHOR_NAME", "t")
.env("GIT_AUTHOR_EMAIL", "t@example.invalid")
.env("GIT_COMMITTER_NAME", "t")
.env("GIT_COMMITTER_EMAIL", "t@example.invalid")
.output()
.expect("git runs");
assert!(out.status.success(), "git {args:?}");
}
#[test]
fn report_is_dispatched_routed_and_listed() {
assert!(super::super::part_of(KIND).is_some(), "{KIND} has no part");
let text = super::super::routes::table_json().to_string();
assert!(text.contains("/v1/local/hotspots"), "{text}");
let route = super::super::routes::all()
.find(|r| r.kind == KIND)
.expect("routed");
assert!(matches!(route.method, Method::Get));
assert!(matches!(route.project, Project::Required));
}
#[test]
fn the_document_carries_the_report_and_its_plan() {
let repo = tempfile::tempdir().unwrap();
let d = repo.path();
git(d, &["init", "-q"]);
for i in 0..4 {
std::fs::write(d.join("hot.rs"), format!("{i}\n")).unwrap();
git(d, &["add", "-A"]);
git(d, &["commit", "-q", "-m", &format!("edit {i}")]);
}
let root = d.to_string_lossy().into_owned();
let doc = build(&root, 5).expect("report");
let text = super::super::document(KIND, &doc);
let value: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(value["contract"], "local-read/1");
assert_eq!(value["kind"], KIND);
assert_eq!(value["source"], "git");
assert_eq!(value["weave_file"], "absent");
assert_eq!(value["window"]["commits"], 1000);
assert_eq!(value["report"]["schema"], "hotspots-v1");
let entry = &value["report"]["entries"][0];
assert_eq!(entry["path"], "hot.rs");
assert_eq!(entry["churn"], 4);
assert_eq!(entry["score"], 100);
assert_eq!(
value["plan"][0]["actions"][0]["action"],
"keep_changes_small"
);
assert_eq!(
text,
super::super::document(KIND, &build(&root, 5).unwrap())
);
let human = render(&doc);
assert!(human.contains("100 hot.rs"), "{human}");
}
#[test]
fn outside_a_work_tree_the_answer_is_no_project() {
let dir = tempfile::tempdir().unwrap();
let failure = build(&dir.path().to_string_lossy(), 5).expect_err("no repo");
assert_eq!(failure.code, Code::NoProject);
}
#[test]
fn only_the_json_command_line_is_taken() {
assert!(
!try_run("hotspots", &words(&["--limit", "3"])),
"needs --json"
);
assert!(!try_run("hotspots", &words(&["--json", "--help"])));
assert!(!try_run("heatmap", &words(&["--json"])));
}
}