Files
hx/crates/hx-lens/src/deps.rs
T
hermes f4e55c8dd3
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s
M5: affected tests at turn end (closes #35 #36 #37 #38 #39 #40 #41)
2026-09-30 15:03:17 +00:00

370 lines
13 KiB
Rust

//! Import graph + reverse deps for Rust (crate level), TS/JS, Python (file level), Go (package dir level).
//!
//! ponytail: line-based import scanning, not tree-sitter. Misses imports built at runtime and multi-line
//! `use {..}` groups spanning many lines (Rust is crate-level anyway). Upgrade to tree-sitter queries if
//! selection misses show up in practice.
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
const SKIP: &[&str] = &[
"target",
"node_modules",
"dist",
"build",
"vendor",
"__pycache__",
"venv",
];
const JS: &[&str] = &["ts", "tsx", "js", "jsx", "mjs", "cjs"];
#[derive(Default, Debug)]
pub struct Graph {
/// node -> nodes that import it. Nodes: files (py/js), package dirs (go), crate roots (rust).
pub rev: HashMap<PathBuf, HashSet<PathBuf>>,
}
pub fn walk(ws: &Path) -> Vec<PathBuf> {
let mut out = vec![];
let mut stack = vec![ws.to_path_buf()];
while let Some(d) = stack.pop() {
for e in std::fs::read_dir(&d).into_iter().flatten().flatten() {
let p = e.path();
let n = e.file_name();
let n = n.to_string_lossy();
if n.starts_with('.') || SKIP.contains(&n.as_ref()) {
continue;
}
match e.file_type() {
Ok(t) if t.is_dir() => stack.push(p),
Ok(t) if t.is_file() => out.push(p),
_ => {}
}
}
}
out.sort();
out
}
/// Graph node for a file: the crate root for .rs, the dir for .go, the file itself otherwise.
pub fn node(file: &Path, ws: &Path) -> PathBuf {
match file.extension().and_then(|e| e.to_str()) {
Some("rs") => crate::runners::marker_root(file, &["Cargo.toml"], ws).unwrap_or(ws.into()),
Some("go") => file.parent().unwrap_or(ws).into(),
_ => file.into(),
}
}
fn quoted(l: &str) -> Vec<&str> {
let mut v = vec![];
for q in ['"', '\''] {
let mut s = l;
while let Some(i) = s.find(q) {
let r = &s[i + 1..];
let Some(j) = r.find(q) else { break };
v.push(&r[..j]);
s = &r[j + 1..];
}
}
v
}
fn resolve_js(from: &Path, spec: &str) -> Option<PathBuf> {
if !spec.starts_with('.') {
return None;
}
let base = from.parent()?.join(spec);
let mut cands = vec![base.clone()];
// TS allows importing "./x.js" for x.ts
let stripped = base.with_extension("");
for e in JS {
cands.push(stripped.with_extension(e));
cands.push(base.join(format!("index.{e}")));
}
cands.into_iter().find(|p| p.is_file()).map(|p| norm(&p))
}
fn norm(p: &Path) -> PathBuf {
let mut out = PathBuf::new();
for c in p.components() {
match c {
std::path::Component::ParentDir => {
out.pop();
}
std::path::Component::CurDir => {}
c => out.push(c),
}
}
out
}
fn resolve_py(from: &Path, module: &str, roots: &[PathBuf]) -> Vec<PathBuf> {
let dots = module.chars().take_while(|c| *c == '.').count();
let rest = &module[dots..];
let bases: Vec<PathBuf> = if dots > 0 {
let mut b = from.parent().map(Path::to_path_buf).unwrap_or_default();
for _ in 1..dots {
b.pop();
}
vec![b]
} else {
roots.to_vec()
};
let rel: PathBuf = rest.split('.').filter(|s| !s.is_empty()).collect();
let mut out = vec![];
for b in bases {
let p = b.join(&rel);
for c in [p.with_extension("py"), p.join("__init__.py")] {
if c.is_file() {
out.push(c);
}
}
}
out
}
fn cargo_name(toml: &str) -> Option<String> {
let pkg = toml.split("[package]").nth(1)?;
pkg.lines()
.find_map(|l| l.trim().strip_prefix("name").map(|r| r.trim_start()))
.and_then(|r| r.strip_prefix('='))
.map(|r| r.trim().trim_matches('"').to_string())
}
pub fn build(ws: &Path) -> Graph {
let files = walk(ws);
let mut g = Graph::default();
let mut add = |dep: PathBuf, user: PathBuf| {
if dep != user {
g.rev.entry(dep).or_default().insert(user);
}
};
// python import roots: workspace, dirs with a pyproject/setup, and `src/` layouts
let mut py_roots: Vec<PathBuf> = vec![ws.into(), ws.join("src")];
// rust crates: name -> root; go modules: module path -> root
let mut crates: HashMap<String, PathBuf> = HashMap::new();
let mut gomods: Vec<(String, PathBuf)> = vec![];
for f in &files {
let dir = f.parent().unwrap_or(ws).to_path_buf();
match f.file_name().and_then(|n| n.to_str()) {
Some("Cargo.toml") => {
if let Some(n) = std::fs::read_to_string(f)
.ok()
.as_deref()
.and_then(cargo_name)
{
crates.insert(n.replace('-', "_"), dir);
}
}
Some("go.mod") => {
let s = std::fs::read_to_string(f).unwrap_or_default();
if let Some(m) = s.lines().find_map(|l| l.strip_prefix("module ")) {
gomods.push((m.trim().to_string(), dir));
}
}
Some("pyproject.toml" | "setup.py" | "setup.cfg") => {
py_roots.push(dir.join("src"));
py_roots.push(dir);
}
_ => {}
}
}
for f in &files {
let ext = f.extension().and_then(|e| e.to_str()).unwrap_or_default();
if !(ext == "py" || ext == "go" || JS.contains(&ext) || f.ends_with("Cargo.toml")) {
continue;
}
let Ok(src) = std::fs::read_to_string(f) else {
continue;
};
if f.ends_with("Cargo.toml") {
// path dependencies: `x = { path = "../x" }`
let me = f.parent().unwrap_or(ws).to_path_buf();
for l in src.lines().filter(|l| l.contains("path")) {
for q in quoted(l) {
let d = norm(&me.join(q));
if d.join("Cargo.toml").is_file() {
add(d, me.clone());
}
}
}
// workspace deps by name: `hx-core.workspace = true` / `hx-core = { workspace = true }`
for l in src.lines() {
let name = l.split(['=', '.']).next().unwrap_or_default().trim();
if let Some(d) = crates.get(&name.replace('-', "_"))
&& l.contains("workspace")
&& *d != me
{
add(d.clone(), me.clone());
}
}
continue;
}
let me = node(f, ws);
for l in src.lines() {
let t = l.trim_start();
match ext {
"py" => {
let m = if let Some(r) = t.strip_prefix("from ") {
r.split_whitespace().next().map(|m| {
// `from . import a, b` -> modules .a, .b
if m.chars().all(|c| c == '.') {
let names = r.split(" import ").nth(1).unwrap_or_default();
names
.split(',')
.map(|n| {
format!(
"{m}{}",
n.split_whitespace().next().unwrap_or_default()
)
})
.collect()
} else {
vec![m.to_string()]
}
})
} else {
t.strip_prefix("import ").map(|r| {
r.split(',')
.filter_map(|x| x.split_whitespace().next())
.map(String::from)
.collect()
})
};
for m in m.unwrap_or_default() {
for d in resolve_py(f, &m, &py_roots) {
add(d, me.clone());
}
}
}
"go" => {
for q in quoted(t) {
for (m, root) in &gomods {
if let Some(r) = q.strip_prefix(m.as_str()) {
add(root.join(r.trim_start_matches('/')), me.clone());
}
}
}
}
_ => {
if t.starts_with("import")
|| t.starts_with("export")
|| t.contains("require(")
|| t.contains("import(")
|| t.starts_with("} from")
{
for q in quoted(t) {
if let Some(d) = resolve_js(f, q) {
add(d, me.clone());
}
}
}
}
}
}
}
g
}
impl Graph {
/// Transitive reverse deps of `node` (excluding itself), breadth-first, capped at `depth`.
pub fn users(&self, node: &Path, depth: usize) -> Vec<PathBuf> {
let mut seen: HashSet<PathBuf> = HashSet::from([node.to_path_buf()]);
let mut frontier = vec![node.to_path_buf()];
let mut out = vec![];
for _ in 0..depth {
let mut next = vec![];
for n in &frontier {
for u in self.rev.get(n).into_iter().flatten() {
if seen.insert(u.clone()) {
out.push(u.clone());
next.push(u.clone());
}
}
}
frontier = next;
}
out.sort();
out
}
}
#[cfg(test)]
mod t {
use super::*;
fn w(ws: &Path, p: &str, s: &str) {
let p = ws.join(p);
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
std::fs::write(p, s).unwrap();
}
#[test]
fn reverse_deps() {
let d = tempfile::tempdir().unwrap();
let ws = &std::fs::canonicalize(d.path()).unwrap();
// ts: util <- api <- api.test
w(ws, "web/src/util.ts", "export const x = 1\n");
w(ws, "web/src/api.ts", "import { x } from './util'\n");
w(
ws,
"web/src/api.test.ts",
"import {\n a,\n} from \"./api.js\"\n",
);
w(
ws,
"web/node_modules/z/index.ts",
"import './../../src/util'\n",
);
// py: pkg/core <- pkg/svc (relative) <- tests/test_svc (absolute)
w(ws, "py/pyproject.toml", "");
w(ws, "py/pkg/__init__.py", "");
w(ws, "py/pkg/core.py", "X = 1\n");
w(ws, "py/pkg/svc.py", "from . import core\n");
w(ws, "py/tests/test_svc.py", "import os, pkg.svc\n");
// go: m/a <- m/b
w(ws, "go/go.mod", "module example.com/m\n\ngo 1.22\n");
w(ws, "go/a/a.go", "package a\n");
w(
ws,
"go/b/b.go",
"package b\nimport (\n\t\"fmt\"\n\t\"example.com/m/a\"\n)\n",
);
// rust: core <- app (workspace dep), core <- tool (path dep)
w(ws, "rs/core/Cargo.toml", "[package]\nname = \"my-core\"\n");
w(
ws,
"rs/app/Cargo.toml",
"[package]\nname = \"app\"\n[dependencies]\nmy-core.workspace = true\n",
);
w(
ws,
"rs/tool/Cargo.toml",
"[package]\nname = \"tool\"\n[dependencies]\nx = { path = \"../core\" }\n",
);
let g = build(ws);
assert_eq!(
g.users(&ws.join("web/src/util.ts"), 3),
vec![ws.join("web/src/api.test.ts"), ws.join("web/src/api.ts")]
);
assert_eq!(
g.users(&ws.join("web/src/util.ts"), 1),
vec![ws.join("web/src/api.ts")]
);
assert_eq!(
g.users(&ws.join("py/pkg/core.py"), 3),
vec![ws.join("py/pkg/svc.py"), ws.join("py/tests/test_svc.py")]
);
assert_eq!(
g.users(&node(&ws.join("go/a/a.go"), ws), 3),
vec![ws.join("go/b")]
);
assert_eq!(
g.users(&node(&ws.join("rs/core/src/lib.rs"), ws), 3),
vec![ws.join("rs/app"), ws.join("rs/tool")]
);
assert!(g.users(&ws.join("web/src/api.test.ts"), 3).is_empty());
}
}