Skip to main content

dev_prune/
workspace.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Workspace discovery — finds every package-manager project inside a repository.
5//
6// A repository is not necessarily one project. A monorepo can carry `frontend/` on
7// pnpm, `services/api/` on uv, and `cli/` on cargo, or hold all three manifests side
8// by side in the root. This module walks the repo once and reports every directory
9// where at least one adapter applies, so the engine can prune, verify and restore each
10// of them independently.
11//
12// The walk deliberately never descends into the directories it is looking for. A
13// `node_modules` tree contains thousands of nested `package.json` files, each of which
14// would otherwise register as its own project.
15
16use std::path::{Path, PathBuf};
17
18use walkdir::{DirEntry, WalkDir};
19
20use crate::adapters::{self, PackageManager};
21
22/// The depth [`discover`] uses when no configuration says otherwise.
23///
24/// Re-exported from [`crate::constants`] so callers that only need the default do not
25/// have to reach past this module for it.
26pub const MAX_DEPTH: usize = crate::constants::DEFAULT_SCAN_DEPTH;
27
28/// The depth to walk `repo_root` with, given the global setting.
29///
30/// Resolution order is the same one every other tunable follows: the repository's own
31/// `.devprune.json` wins over the global setting, which wins over the default. A config
32/// that will not parse is *not* consulted — the caller reports that repository as a
33/// `config_error` and never gets here — so this deliberately looks only at a config it
34/// could read.
35pub fn resolve_depth(repo_root: &Path, global: usize) -> usize {
36    let configured = crate::config::PerRepoConfig::load_with_diagnostics(repo_root)
37        .ok()
38        .flatten()
39        .and_then(|c| c.scan_depth)
40        .unwrap_or(global);
41    clamp_depth(configured)
42}
43
44/// Hold a requested depth inside the range the walk can afford.
45///
46/// A zero would find nothing at all — not even the repository root, which is depth 0 in
47/// `WalkDir` terms but only yields projects because the walk includes it — so it is
48/// raised to 1 rather than silently pruning nothing. The ceiling keeps a mistyped
49/// `scan_depth: 900` from turning a background pass into a full-disk crawl.
50pub fn clamp_depth(requested: usize) -> usize {
51    requested.clamp(1, crate::constants::MAX_SCAN_DEPTH_LIMIT)
52}
53
54/// Directory names that are never descended into.
55///
56/// Hidden directories, virtual environments and nested repositories are excluded
57/// separately in [`is_scannable`] because they cannot be matched by name alone.
58/// Several of these hold whole projects of their own: `deps/` is full of Elixir
59/// packages with their own `mix.exs`, `.build/` of Swift checkouts with their own
60/// `Package.swift`. Descending would register a dependency as a project and offer to
61/// prune inside something the parent repository rebuilds wholesale.
62const SKIP_DIRS: &[&str] = &[
63    "node_modules",
64    "target",
65    "vendor",
66    "bower_components",
67    "__pypackages__",
68    "Pods",
69    "deps",
70    "_build",
71    ".build",
72];
73
74/// A directory inside a repository that at least one package manager owns.
75pub struct Project {
76    /// Absolute path to the project directory.
77    pub path: PathBuf,
78    /// Path relative to the repository root, `/`-separated. `"."` for the root itself.
79    pub relative: String,
80    /// Adapters that apply here. More than one is normal — cargo and npm in the same
81    /// directory own `target` and `node_modules` respectively.
82    pub adapters: Vec<Box<dyn PackageManager>>,
83}
84
85/// Find every package-manager project in `repo_root`, including the root itself.
86///
87/// Walks to the default depth. Callers that have the user's settings to hand should use
88/// [`discover_to_depth`] with [`resolve_depth`] instead.
89///
90/// Returns an empty vector when nothing in the tree is recognised.
91pub fn discover(repo_root: &Path) -> Vec<Project> {
92    discover_to_depth(repo_root, MAX_DEPTH)
93}
94
95/// [`discover`], to an explicit depth.
96///
97/// `depth` is clamped, so a caller cannot hand this an unbounded or useless walk even by
98/// reading a hand-edited config straight off disk.
99pub fn discover_to_depth(repo_root: &Path, depth: usize) -> Vec<Project> {
100    WalkDir::new(repo_root)
101        .follow_links(false)
102        .max_depth(clamp_depth(depth))
103        // Directory order otherwise comes from the filesystem, so the same repository
104        // lists its projects in a different order on different machines — and so does
105        // every prune summary and JSON document built from them.
106        .sort_by_file_name()
107        .into_iter()
108        .filter_entry(|entry| entry.depth() == 0 || is_scannable(entry))
109        .flatten()
110        .filter(|entry| entry.file_type().is_dir())
111        .filter_map(|entry| {
112            let adapters = adapters::detect_adapters(entry.path());
113            if adapters.is_empty() {
114                return None;
115            }
116            Some(Project {
117                relative: relative_label(repo_root, entry.path()),
118                path: entry.path().to_path_buf(),
119                adapters,
120            })
121        })
122        .collect()
123}
124
125/// Whether the walk should descend into this entry.
126fn is_scannable(entry: &DirEntry) -> bool {
127    // Symlinked directories report as symlinks with `follow_links(false)` and are never
128    // descended, so only real directories need filtering. Files pass through untouched.
129    if !entry.file_type().is_dir() {
130        return true;
131    }
132
133    let name = entry.file_name().to_string_lossy();
134
135    // `.git`, `.venv`, `.tox`, `.next`, `.turbo`, editor state — none of them hold
136    // projects worth pruning, and all of them are expensive to walk.
137    if name.starts_with('.') {
138        return false;
139    }
140
141    if SKIP_DIRS.contains(&name.as_ref()) {
142        return false;
143    }
144
145    let path = entry.path();
146
147    // A virtual environment can be called anything; `pyvenv.cfg` is the marker. It is
148    // pruneable output, not a project, and it contains a full package tree.
149    if path.join("pyvenv.cfg").exists() {
150        return false;
151    }
152
153    // Submodules and nested clones are separate repositories with their own activity
154    // history and their own `.devprune.json`. They are registered and pruned in their
155    // own right, never as part of their parent.
156    if path.join(".git").exists() {
157        return false;
158    }
159
160    true
161}
162
163/// Render `path` relative to `root` with forward slashes; `"."` when they are equal.
164///
165/// Used for every user-facing directory label so that `frontend/node_modules` reads the
166/// same on Windows as on Linux, and so the interactive selector can address a specific
167/// nested directory unambiguously.
168pub fn relative_label(root: &Path, path: &Path) -> String {
169    match path.strip_prefix(root) {
170        Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(),
171        Ok(rel) => rel.to_string_lossy().replace('\\', "/"),
172        Err(_) => path.display().to_string(),
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use std::fs;
180    use tempfile::TempDir;
181
182    /// Create `dir` and drop the given files into it.
183    fn project(root: &Path, rel: &str, files: &[&str]) -> PathBuf {
184        let dir = if rel == "." {
185            root.to_path_buf()
186        } else {
187            root.join(rel)
188        };
189        fs::create_dir_all(&dir).unwrap();
190        for file in files {
191            fs::write(dir.join(file), "{}").unwrap();
192        }
193        dir
194    }
195
196    fn names(projects: &[Project]) -> Vec<(String, Vec<&'static str>)> {
197        let mut out: Vec<(String, Vec<&'static str>)> = projects
198            .iter()
199            .map(|p| {
200                let mut adapters: Vec<&'static str> = p.adapters.iter().map(|a| a.name()).collect();
201                adapters.sort_unstable();
202                (p.relative.clone(), adapters)
203            })
204            .collect();
205        out.sort();
206        out
207    }
208
209    #[test]
210    fn discovers_nothing_in_an_empty_tree() {
211        let tmp = TempDir::new().unwrap();
212        assert!(discover(tmp.path()).is_empty());
213    }
214
215    #[test]
216    fn discovers_three_ecosystems_in_one_root() {
217        let tmp = TempDir::new().unwrap();
218        project(
219            tmp.path(),
220            ".",
221            &["package.json", "package-lock.json", "uv.lock", "go.mod"],
222        );
223
224        assert_eq!(
225            names(&discover(tmp.path())),
226            vec![(".".to_string(), vec!["go", "npm", "uv"])]
227        );
228    }
229
230    #[test]
231    fn discovers_ecosystems_at_different_depths() {
232        let tmp = TempDir::new().unwrap();
233        project(tmp.path(), "frontend", &["pnpm-lock.yaml"]);
234        project(tmp.path(), "services/api", &["uv.lock"]);
235        project(tmp.path(), "tools/cli", &["go.mod"]);
236
237        assert_eq!(
238            names(&discover(tmp.path())),
239            vec![
240                ("frontend".to_string(), vec!["pnpm"]),
241                ("services/api".to_string(), vec!["uv"]),
242                ("tools/cli".to_string(), vec!["go"]),
243            ]
244        );
245    }
246
247    #[test]
248    fn combines_a_root_project_with_nested_ones() {
249        let tmp = TempDir::new().unwrap();
250        project(tmp.path(), ".", &["go.mod"]);
251        project(tmp.path(), "web", &["package.json", "package-lock.json"]);
252
253        assert_eq!(
254            names(&discover(tmp.path())),
255            vec![
256                (".".to_string(), vec!["go"]),
257                ("web".to_string(), vec!["npm"]),
258            ]
259        );
260    }
261
262    #[test]
263    fn never_descends_into_node_modules() {
264        let tmp = TempDir::new().unwrap();
265        project(tmp.path(), ".", &["package.json", "package-lock.json"]);
266        // A dependency that ships its own lockfile must not become a project.
267        project(
268            tmp.path(),
269            "node_modules/some-dep",
270            &["package.json", "package-lock.json"],
271        );
272
273        assert_eq!(names(&discover(tmp.path())).len(), 1);
274    }
275
276    #[test]
277    fn never_descends_into_target_or_vendor() {
278        let tmp = TempDir::new().unwrap();
279        project(tmp.path(), ".", &["go.mod"]);
280        project(tmp.path(), "target/debug/build/x", &["go.mod"]);
281        project(tmp.path(), "vendor/dep", &["go.mod"]);
282
283        assert_eq!(
284            names(&discover(tmp.path())),
285            vec![(".".to_string(), vec!["go"])]
286        );
287    }
288
289    #[test]
290    fn never_descends_into_a_virtual_environment() {
291        let tmp = TempDir::new().unwrap();
292        project(tmp.path(), ".", &["uv.lock"]);
293        let venv = project(tmp.path(), "my_env", &["pyvenv.cfg"]);
294        project(&venv, "lib/site-packages/dep", &["go.mod"]);
295
296        assert_eq!(
297            names(&discover(tmp.path())),
298            vec![(".".to_string(), vec!["uv"])]
299        );
300    }
301
302    #[test]
303    fn never_descends_into_a_nested_repository() {
304        let tmp = TempDir::new().unwrap();
305        project(tmp.path(), ".", &["go.mod"]);
306        let sub = project(tmp.path(), "submodule", &["package-lock.json"]);
307        fs::create_dir(sub.join(".git")).unwrap();
308
309        assert_eq!(
310            names(&discover(tmp.path())),
311            vec![(".".to_string(), vec!["go"])]
312        );
313    }
314
315    #[test]
316    fn never_descends_into_hidden_directories() {
317        let tmp = TempDir::new().unwrap();
318        project(tmp.path(), ".github/actions/thing", &["package-lock.json"]);
319        assert!(discover(tmp.path()).is_empty());
320    }
321
322    #[test]
323    fn stops_at_the_depth_cap() {
324        let tmp = TempDir::new().unwrap();
325        let deep = "a/b/c/d/e/f/g/h";
326        project(tmp.path(), deep, &["Cargo.toml"]);
327        assert!(discover(tmp.path()).is_empty());
328    }
329
330    #[test]
331    fn relative_label_is_slash_separated() {
332        let root = Path::new("/repo");
333        assert_eq!(relative_label(root, Path::new("/repo")), ".");
334        assert_eq!(
335            relative_label(root, Path::new("/repo/a/b/node_modules")),
336            "a/b/node_modules"
337        );
338    }
339}