use std::path::Path;
use anyhow::{Result, bail};
use super::resolver::path_matches_focus;
use super::types::{GraphQuery, GraphReport};
use sephera_core::path_utils;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dependent {
pub file: String,
pub imports: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlastRadius {
pub target: String,
pub dependents: Vec<Dependent>,
pub depth: Option<u32>,
}
pub fn measure(
report: &GraphReport,
requested: &str,
depth: Option<u32>,
) -> Result<BlastRadius> {
measure_scoped(report, requested, depth, &[])
}
pub fn measure_scoped(
report: &GraphReport,
requested: &str,
depth: Option<u32>,
focus: &[String],
) -> Result<BlastRadius> {
let target = target_of(report, requested);
if target != spelled_as_graph(requested) {
bail!(
"this report was built for a reverse query on `{target}`, so it \
describes that file only and has no edges for `{requested}`. \
Build a report over the whole repository to measure it."
);
}
let reachable = reachable_dependents(report, &target, depth);
let mut direct: std::collections::BTreeMap<String, Vec<String>> =
std::collections::BTreeMap::new();
for edge in &report.edges {
if edge.to.as_deref() == Some(target.as_str()) && edge.resolved {
direct
.entry(edge.from.clone())
.or_default()
.push(edge.import_path.clone());
}
}
let dependents = reachable
.into_iter()
.filter(|file| in_scope(file, focus))
.map(|file| {
let mut imports = direct.remove(&file).unwrap_or_default();
imports.sort();
imports.dedup();
Dependent { file, imports }
})
.collect();
Ok(BlastRadius {
target,
dependents,
depth,
})
}
#[must_use]
pub fn dependent_count(radius: &BlastRadius) -> u64 {
u64::try_from(radius.dependents.len()).unwrap_or(u64::MAX)
}
pub fn measure_all(
report: &GraphReport,
requested: &[String],
base_prefix: &str,
depth: Option<u32>,
focus: &[String],
) -> Result<Vec<BlastRadius>> {
let mut matched = Vec::with_capacity(requested.len());
let mut unknown = Vec::new();
for raw in requested {
match match_path(report, raw, base_prefix) {
Some(canonical) => {
matched.push(measure_scoped(report, &canonical, depth, focus)?);
}
None => unknown.push(raw.clone()),
}
}
if !unknown.is_empty() {
let listed: Vec<String> =
unknown.iter().map(|path| format!(" `{path}`")).collect();
bail!(
"{} path(s) did not resolve to a file in the analysed graph:\n{}\n\
Paths are relative to the analysis base{}.",
unknown.len(),
listed.join("\n"),
if base_prefix.is_empty() {
String::new()
} else {
format!(", or to the repository root under `{base_prefix}`")
}
);
}
matched.sort_by(|left, right| {
dependent_count(right)
.cmp(&dependent_count(left))
.then_with(|| left.target.cmp(&right.target))
});
Ok(matched)
}
fn spelled_as_graph(raw: &str) -> String {
path_utils::forward_slashes(raw)
.trim_start_matches("./")
.to_owned()
}
#[must_use]
pub fn match_path(
report: &GraphReport,
raw: &str,
base_prefix: &str,
) -> Option<String> {
let mut normalized = spelled_as_graph(raw);
let prefix = base_prefix.replace('\\', "/");
let prefix = prefix.trim_matches('/');
if !prefix.is_empty()
&& let Some(stripped) = normalized
.strip_prefix(prefix)
.and_then(|rest| rest.strip_prefix('/'))
{
normalized = stripped.to_owned();
}
report
.nodes
.iter()
.find(|node| node.file_path == normalized)
.map(|node| node.file_path.clone())
}
fn target_of(report: &GraphReport, requested: &str) -> String {
match &report.query {
Some(GraphQuery::DependsOn(path)) => path.clone(),
None => requested.to_owned(),
}
}
fn reachable_dependents(
report: &GraphReport,
target: &str,
depth: Option<u32>,
) -> Vec<String> {
let mut imported_by: std::collections::BTreeMap<&str, Vec<&str>> =
std::collections::BTreeMap::new();
for edge in &report.edges {
if !edge.resolved {
continue;
}
if let Some(to) = edge.to.as_deref() {
imported_by.entry(to).or_default().push(edge.from.as_str());
}
}
let mut seen: std::collections::BTreeSet<&str> =
std::collections::BTreeSet::new();
let mut queue: std::collections::VecDeque<(&str, u32)> =
std::collections::VecDeque::new();
queue.push_back((target, 0));
while let Some((current, distance)) = queue.pop_front() {
if depth.is_some_and(|limit| distance >= limit) {
continue;
}
for dependent in imported_by.get(current).into_iter().flatten() {
if *dependent == target {
continue;
}
if seen.insert(dependent) {
queue.push_back((dependent, distance.saturating_add(1)));
}
}
}
seen.into_iter().map(str::to_owned).collect()
}
fn in_scope(path: &str, focus: &[String]) -> bool {
if focus.is_empty() {
return true;
}
focus
.iter()
.any(|scope| path_matches_focus(path, scope.trim_matches('/')))
}
#[must_use]
pub fn base_prefix_for(repo_root: &Path, analysis_path: &Path) -> String {
analysis_path
.strip_prefix(repo_root)
.unwrap_or_else(|_| Path::new(""))
.to_string_lossy()
.replace('\\', "/")
}
#[cfg(test)]
mod tests;