Repository navigation
Expand file tree
/
Copy pathgraph.rs
More file actions
564 lines (516 loc) · 19.3 KB
/
Copy pathgraph.rs
File metadata and controls
564 lines (516 loc) · 19.3 KB
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Reference/impact graph — the research core of Diskern.
//!
//! Goal: answer "what breaks if I remove X?" with evidence. Nodes are
//! filesystem artifacts (files, dirs, SDKs, projects); edges are typed
//! references (lockfile pins, symlinks, PATH entries, project configs).
//!
//! v0 scope: detect project roots (Cargo.toml, package.json, etc.) and
//! link them to the dependency stores they reference. Everything else
//! (dynamic linking, registry, plists) comes later.
use crate::FileEntry;
use petgraph::graph::{DiGraph, NodeIndex};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
/// A file whose presence makes the directory holding it a project root,
/// and the stores a project of that kind owns.
///
/// Root-level stores only, in v0. `__pycache__` and nested `node_modules`
/// exist at every depth and belong to whatever encloses them, which is a
/// containment question rather than a reference one.
const PROJECTS: &[(&str, ProjectKind, &[&str])] = &[
("cargo.toml", ProjectKind::Cargo, &["target"]),
("package.json", ProjectKind::Npm, &["node_modules"]),
("pyproject.toml", ProjectKind::Python, &[".venv", "venv"]),
("go.mod", ProjectKind::Go, &["vendor"]),
("pom.xml", ProjectKind::Maven, &["target"]),
("build.gradle", ProjectKind::Gradle, &["build", ".gradle"]),
(
"build.gradle.kts",
ProjectKind::Gradle,
&["build", ".gradle"],
),
("gemfile", ProjectKind::Ruby, &["vendor/bundle"]),
("composer.json", ProjectKind::Php, &["vendor"]),
("pubspec.yaml", ProjectKind::Dart, &[".dart_tool", "build"]),
];
/// Directory names or relative paths that are dependency stores wherever they appear.
const STORE_NAMES: &[&str] = &[
"target",
"node_modules",
".venv",
"venv",
"vendor",
"vendor/bundle",
"build",
".gradle",
".dart_tool",
];
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Node {
File(PathBuf),
ProjectRoot { path: PathBuf, kind: ProjectKind },
DependencyStore(PathBuf), // e.g. a node_modules dir, ~/.cargo/registry
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum ProjectKind {
Cargo,
Npm,
Python,
Go,
Maven,
Gradle,
Ruby,
Php,
Dart,
Unknown,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum Edge {
/// Project depends on this store/file (from lockfile or config).
References,
/// Filesystem containment.
Contains,
/// Symlink or hard link.
LinksTo,
}
#[derive(Default)]
pub struct ImpactGraph {
pub graph: DiGraph<Node, Edge>,
index: HashMap<PathBuf, NodeIndex>,
}
impl ImpactGraph {
/// Build the graph from one pass over the scanned entries.
///
/// Two things come out of that pass: which directories are project
/// roots (they hold a marker file), and which are dependency stores
/// (an entry lives under one). A `References` edge is added for each
/// project to the store it owns.
///
/// A project whose own store wasn't scanned is linked to the nearest
/// enclosing project's store of the same kind instead. That is not a
/// guess: npm workspaces hoist dependencies to the repository root and
/// Cargo workspaces share one `target/`, so the members really do
/// reference it — and it is where the "referenced by 3 projects"
/// number comes from rather than always being 1.
pub fn from_entries(entries: &[FileEntry]) -> Self {
static NEVER: AtomicBool = AtomicBool::new(false);
Self::from_entries_cancellable(entries, &NEVER)
.expect("a run that cannot be cancelled cannot stop early")
}
/// [`from_entries`], abandoned as soon as `cancelled` is set.
///
/// This walks every entry's ancestors, which is a second or so per
/// million entries — long enough that a Cancel arriving during it
/// would otherwise do nothing until the stage after it started. The
/// walk and the hashing pass both stop promptly; this has to as well,
/// or it just moves the dead spot.
pub fn from_entries_cancellable(entries: &[FileEntry], cancelled: &AtomicBool) -> Option<Self> {
// A set of kinds per root, not one: a directory holding both a
// `Cargo.toml` and a `package.json` is both projects, and it is a
// shape that turns up constantly — any Rust binary with a web
// front end, this repository's own `app/` among them. Keeping one
// kind meant whichever marker the walk happened to yield last
// won, so one of `target/` and `node_modules/` came back
// unreferenced, and *which* one changed with directory order.
//
// Ordered maps, so the graph a given scan produces is the same
// graph every time. Verdicts are meant to be deterministic, and a
// reference count feeds straight into one.
let mut roots: BTreeMap<PathBuf, BTreeSet<ProjectKind>> = BTreeMap::new();
let mut stores: HashSet<PathBuf> = HashSet::new();
for entry in entries {
if cancelled.load(Ordering::Relaxed) {
return None;
}
let entry_stores = enclosing_stores(&entry.path);
stores.extend(entry_stores.iter().cloned());
// A marker inside a dependency store marks nothing: every npm
// package ships a package.json, and there are tens of
// thousands of them under one node_modules.
if !entry_stores.is_empty() {
continue;
}
let Some(kind) = marker_kind(&entry.path) else {
continue;
};
if let Some(dir) = entry.path.parent() {
roots.entry(dir.to_path_buf()).or_default().insert(kind);
}
}
let mut graph = Self::default();
for (root, kinds) in &roots {
if cancelled.load(Ordering::Relaxed) {
return None;
}
for kind in kinds {
let owned = stores_of(root, *kind, &stores);
let targets = if owned.is_empty() {
shared_store(root, *kind, &roots, &stores)
} else {
owned
};
for store in targets {
// Keyed by path, so a root that is two kinds is still
// one node with one edge per store — and one project
// for anything counting references.
let from = graph.node(Node::ProjectRoot {
path: root.clone(),
kind: *kind,
});
let to = graph.node(Node::DependencyStore(store));
if graph.graph.find_edge(from, to).is_none() {
graph.graph.add_edge(from, to, Edge::References);
}
}
}
}
Some(graph)
}
pub fn node(&mut self, node: Node) -> NodeIndex {
let key = match &node {
Node::File(p) | Node::DependencyStore(p) => p.clone(),
Node::ProjectRoot { path, .. } => path.clone(),
};
if let Some(&ix) = self.index.get(&key) {
return ix;
}
let ix = self.graph.add_node(node);
self.index.insert(key, ix);
ix
}
/// How many project roots reference this path (directly, v0)?
/// This number feeds risk::downgrade — the "breaks 17 projects" number.
///
/// Answers for the nearest enclosing node as well as for the path
/// itself, because findings are files and the thing projects reference
/// is the store above them: nothing points at
/// `proj/node_modules/react/index.js`, but three projects may well
/// point at the `proj/node_modules` it sits in.
pub fn referencing_projects(&self, path: &std::path::Path) -> usize {
let mut projects = HashSet::new();
for ancestor in path.ancestors() {
let Some(&ix) = self.index.get(ancestor) else {
continue;
};
projects.extend(
self.graph
.neighbors_directed(ix, petgraph::Direction::Incoming)
.filter_map(|n| match &self.graph[n] {
Node::ProjectRoot { path, .. } => Some(path.clone()),
_ => None,
}),
);
}
projects.len()
}
}
/// Dependency stores this path sits inside, if any.
///
/// This returns every matching store ancestor. That keeps broad stores like
/// PHP's `vendor` visible even when a package path also matches Ruby's more
/// specific `vendor/bundle` store.
fn enclosing_stores(path: &Path) -> Vec<PathBuf> {
let mut stores = Vec::new();
let mut current = path.parent();
while let Some(dir) = current {
if matching_store_len(dir).is_some() {
stores.push(dir.to_path_buf());
}
current = dir.parent();
}
stores
}
fn matching_store_len(path: &Path) -> Option<usize> {
STORE_NAMES
.iter()
.filter_map(|store| {
let store_path = Path::new(store);
path.ends_with(store_path)
.then(|| store_path.components().count())
})
.max()
}
/// Which kind of project a file marks, if it marks one.
fn marker_kind(path: &Path) -> Option<ProjectKind> {
let name = path.file_name()?.to_str()?.to_ascii_lowercase();
PROJECTS
.iter()
.find(|(marker, _, _)| *marker == name)
.map(|(_, kind, _)| *kind)
}
/// The stores this project owns that the scan actually saw.
fn stores_of(root: &Path, kind: ProjectKind, seen: &HashSet<PathBuf>) -> Vec<PathBuf> {
PROJECTS
.iter()
.filter(|(_, k, _)| *k == kind)
.flat_map(|(_, _, names)| names.iter())
.map(|name| root.join(name))
.filter(|store| seen.contains(store))
.collect()
}
/// The store an enclosing project of the same kind owns — what a workspace
/// member uses when the dependencies were hoisted above it.
fn shared_store(
root: &Path,
kind: ProjectKind,
roots: &BTreeMap<PathBuf, BTreeSet<ProjectKind>>,
seen: &HashSet<PathBuf>,
) -> Vec<PathBuf> {
for ancestor in root.ancestors().skip(1) {
if !roots
.get(ancestor)
.is_some_and(|kinds| kinds.contains(&kind))
{
continue;
}
let stores = stores_of(ancestor, kind, seen);
if !stores.is_empty() {
return stores;
}
}
vec![]
}
#[cfg(test)]
mod tests {
use super::*;
fn entries(paths: &[&str]) -> Vec<FileEntry> {
paths
.iter()
.map(|p| FileEntry {
path: PathBuf::from(p),
size: 1,
modified: None,
accessed: None,
is_symlink: false,
identity: None,
hash: None,
})
.collect()
}
#[test]
fn a_project_references_the_store_beside_it() {
let graph = ImpactGraph::from_entries(&entries(&[
"/home/u/proj/package.json",
"/home/u/proj/src/index.js",
"/home/u/proj/node_modules/react/index.js",
]));
assert_eq!(
graph.referencing_projects(Path::new("/home/u/proj/node_modules/react/index.js")),
1
);
// The project's own source is referenced by nothing.
assert_eq!(
graph.referencing_projects(Path::new("/home/u/proj/src/index.js")),
0
);
}
/// An abandoned store — no project alongside it — is the case this
/// whole module exists to tell apart from the one above.
#[test]
fn an_unreferenced_store_is_referenced_by_nobody() {
let graph =
ImpactGraph::from_entries(&entries(&["/home/u/old-thing/node_modules/react/index.js"]));
assert_eq!(
graph.referencing_projects(Path::new("/home/u/old-thing/node_modules/react/index.js")),
0
);
}
/// Every npm package ships a package.json. Treating those as project
/// roots would make one node_modules look like ten thousand projects.
#[test]
fn a_package_json_inside_node_modules_is_not_a_project() {
let graph = ImpactGraph::from_entries(&entries(&[
"/home/u/proj/package.json",
"/home/u/proj/node_modules/react/package.json",
"/home/u/proj/node_modules/react/node_modules/loose/package.json",
]));
assert_eq!(
graph.referencing_projects(Path::new("/home/u/proj/node_modules/react/package.json")),
1
);
}
/// The README's headline evidence. npm workspaces hoist dependencies
/// to the repository root, so all three members really do reference
/// the one store.
#[test]
fn hoisted_workspace_members_all_reference_the_shared_store() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/package.json",
"/repo/packages/a/package.json",
"/repo/packages/b/package.json",
"/repo/node_modules/react/index.js",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/node_modules/react/index.js")),
3
);
}
/// A member with its own store uses that one, not the root's.
#[test]
fn a_member_with_its_own_store_does_not_borrow_the_roots() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/package.json",
"/repo/packages/a/package.json",
"/repo/packages/a/node_modules/x/index.js",
"/repo/node_modules/react/index.js",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/packages/a/node_modules/x/index.js")),
1
);
assert_eq!(
graph.referencing_projects(Path::new("/repo/node_modules/react/index.js")),
1
);
}
#[test]
fn cargo_workspace_members_share_one_target() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/Cargo.toml",
"/repo/crates/core/Cargo.toml",
"/repo/crates/cli/Cargo.toml",
"/repo/target/debug/app",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/target/debug/app")),
3
);
}
/// A directory can be more than one kind of project, and both of its
/// stores are then referenced. Keeping a single kind per root meant
/// whichever marker the walk yielded last won, so one store came back
/// unreferenced — and which one depended on directory order, which
/// makes the verdict non-deterministic. Both orders are asserted.
#[test]
fn a_root_that_is_two_projects_references_both_of_its_stores() {
let both = [
"/proj/Cargo.toml",
"/proj/package.json",
"/proj/target/debug/app",
"/proj/node_modules/react/index.js",
];
let reversed: Vec<&str> = both.iter().copied().rev().collect();
for order in [both.to_vec(), reversed] {
let graph = ImpactGraph::from_entries(&entries(&order));
assert_eq!(
graph.referencing_projects(Path::new("/proj/target/debug/app")),
1,
"target/ in order {order:?}"
);
assert_eq!(
graph.referencing_projects(Path::new("/proj/node_modules/react/index.js")),
1,
"node_modules/ in order {order:?}"
);
}
}
/// A root that is two kinds is still one project, so a store it shares
/// with siblings must not be counted twice for it.
#[test]
fn a_two_kind_root_counts_once_against_a_shared_store() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/Cargo.toml",
"/repo/package.json",
"/repo/node_modules/react/index.js",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/node_modules/react/index.js")),
1
);
}
#[test]
fn additional_project_markers_reference_their_stores() {
for (marker, stores) in [
("go.mod", vec!["vendor/pkg/mod.go"]),
("pom.xml", vec!["target/classes/app.class"]),
(
"build.gradle",
vec!["build/classes/App.class", ".gradle/caches/modules.lock"],
),
(
"build.gradle.kts",
vec!["build/classes/App.class", ".gradle/caches/modules.lock"],
),
("Gemfile", vec!["vendor/bundle/ruby/3.3.0/gems/rack.rb"]),
(
"composer.json",
vec!["vendor/monolog/monolog/src/Logger.php"],
),
(
"pubspec.yaml",
vec![".dart_tool/package_config.json", "build/app.dill"],
),
] {
for store_file in stores {
let marker_path = format!("/repo/app/{marker}");
let store_path = format!("/repo/app/{store_file}");
let graph = ImpactGraph::from_entries(&entries(&[
marker_path.as_str(),
store_path.as_str(),
]));
assert_eq!(
graph.referencing_projects(Path::new(&store_path)),
1,
"{marker} should reference {store_file}"
);
}
}
}
#[test]
fn shared_store_names_count_one_root_once() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/Cargo.toml",
"/repo/pom.xml",
"/repo/target/debug/app",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/target/debug/app")),
1
);
}
#[test]
fn nested_store_names_stay_specific() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/Gemfile",
"/repo/vendor/bundle/ruby/3.3.0/gems/rack.rb",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/vendor/bundle/ruby/3.3.0/gems/rack.rb")),
1
);
}
#[test]
fn broad_vendor_stores_still_cover_bundle_named_packages() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/composer.json",
"/repo/vendor/bundle/package/src/lib.php",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/vendor/bundle/package/src/lib.php")),
1
);
}
#[test]
fn parent_and_child_store_references_count_one_root_once() {
let graph = ImpactGraph::from_entries(&entries(&[
"/repo/Gemfile",
"/repo/composer.json",
"/repo/vendor/bundle/ruby/3.3.0/gems/rack.rb",
]));
assert_eq!(
graph.referencing_projects(Path::new("/repo/vendor/bundle/ruby/3.3.0/gems/rack.rb")),
1
);
}
#[test]
fn a_cancelled_build_stops_instead_of_finishing() {
let cancelled = AtomicBool::new(true);
assert!(ImpactGraph::from_entries_cancellable(
&entries(&["/repo/package.json", "/repo/node_modules/react/index.js"]),
&cancelled,
)
.is_none());
}
}