Skip to main content

verctl_core/workspace/
detect.rs

1//! Infer a lockfile follow-up from the tree. Same signals mise/corepack use.
2
3use std::fs;
4use std::path::{Path, PathBuf};
5
6/// The command that owns a manifest's lockfile: what to run, where, and the
7/// lockfile it rewrites.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Owner {
10    /// The command, such as `cargo update --workspace`.
11    pub argv: Vec<String>,
12    /// Where it runs: the directory containing the lockfile, or the manifest's
13    /// when no lockfile exists yet.
14    pub dir: PathBuf,
15    /// The lockfile the command rewrites, when the tree has one.
16    pub lockfile: Option<PathBuf>,
17}
18
19impl Owner {
20    /// The argv joined by spaces, as a report and a driver's `after` show it.
21    #[must_use]
22    pub fn command(&self) -> String {
23        self.argv.join(" ")
24    }
25
26    fn new(command: &str, dir: &Path, lockfile: Option<PathBuf>) -> Self {
27        let dir = lockfile
28            .as_deref()
29            .and_then(Path::parent)
30            .map_or_else(|| dir.to_path_buf(), Path::to_path_buf);
31        Self {
32            argv: command.split_whitespace().map(str::to_owned).collect(),
33            dir,
34            lockfile,
35        }
36    }
37}
38
39/// The command that refreshes the lockfile after `manifest`'s version moves,
40/// when the tree has one.
41#[must_use]
42pub fn follow_up(manifest: &Path) -> Option<String> {
43    owner(manifest).map(|owner| owner.command())
44}
45
46/// The command that owns `manifest`'s lockfile, found by the signals of
47/// [`follow_up`].
48#[must_use]
49pub fn owner(manifest: &Path) -> Option<Owner> {
50    let dir = manifest.parent().unwrap_or(manifest);
51    let file_name = manifest.file_name()?.to_str()?;
52    match file_name {
53        "Cargo.toml" => cargo_owner(dir),
54        "package.json" => javascript_owner(dir),
55        "pyproject.toml" => python_owner(dir),
56        _ => None,
57    }
58}
59
60fn cargo_owner(dir: &Path) -> Option<Owner> {
61    // Not `generate-lockfile`: that re-resolves every dependency, so a bump
62    // would carry unrelated moves. Only this package's version went stale.
63    let lockfile = find(dir, "Cargo.lock")?;
64    Some(Owner::new("cargo update --workspace", dir, Some(lockfile)))
65}
66
67/// `uv.lock` records the project's own version, so a bump leaves it stale.
68/// `uv lock` keeps every locked dependency it can ([uv: upgrading locked
69/// package versions]), so only that version moves.
70///
71/// [uv: upgrading locked package versions]: https://docs.astral.sh/uv/concepts/projects/sync/#upgrading-locked-package-versions
72fn python_owner(dir: &Path) -> Option<Owner> {
73    let lockfile = find(dir, "uv.lock")?;
74    Some(Owner::new("uv lock", dir, Some(lockfile)))
75}
76
77/// The lockfiles each JavaScript package manager writes, in the order the
78/// tree is searched.
79const JAVASCRIPT_LOCKFILES: [(&str, &str); 6] = [
80    ("bun", "bun.lock"),
81    ("bun", "bun.lockb"),
82    ("pnpm", "pnpm-lock.yaml"),
83    ("yarn", "yarn.lock"),
84    ("npm", "package-lock.json"),
85    ("npm", "npm-shrinkwrap.json"),
86];
87
88fn javascript_owner(dir: &Path) -> Option<Owner> {
89    if let Some(name) = package_manager_field(&dir.join("package.json")) {
90        let lockfile = JAVASCRIPT_LOCKFILES
91            .iter()
92            .filter(|(manager, _)| *manager == name)
93            .find_map(|(_, file_name)| find(dir, file_name));
94        return Some(Owner::new(&install_command(&name), dir, lockfile));
95    }
96    for ancestor in scope(dir) {
97        for (manager, file_name) in JAVASCRIPT_LOCKFILES {
98            let lockfile = ancestor.join(file_name);
99            if lockfile.is_file() {
100                return Some(Owner::new(&install_command(manager), dir, Some(lockfile)));
101            }
102        }
103    }
104    None
105}
106
107/// `dir` and every ancestor up to the working tree that contains it.
108///
109/// The repository root is the ceiling: a lockfile above it belongs to
110/// some other project that happens to contain this one on disk. Without
111/// a repository the search never leaves `dir` at all, so a lockfile in a
112/// parent directory is never matched to this manifest.
113fn scope(dir: &Path) -> Vec<PathBuf> {
114    let dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
115    let ceiling = workdir_covering(&dir);
116    let mut dirs = Vec::new();
117    for ancestor in dir.ancestors() {
118        dirs.push(ancestor.to_path_buf());
119        if ceiling.as_deref().is_none_or(|ceiling| ancestor == ceiling) {
120            break;
121        }
122    }
123    dirs
124}
125
126/// The nearest `file_name` in [`scope`].
127fn find(dir: &Path, file_name: &str) -> Option<PathBuf> {
128    scope(dir)
129        .into_iter()
130        .map(|ancestor| ancestor.join(file_name))
131        .find(|path| path.is_file())
132}
133
134fn package_manager_field(package_json: &Path) -> Option<String> {
135    let raw = fs::read_to_string(package_json).ok()?;
136    let value: serde_json::Value = serde_json::from_str(&raw).ok()?;
137    let field = value.get("packageManager")?.as_str()?;
138    let name = field.split('@').next()?.trim();
139    (!name.is_empty()).then(|| name.to_owned())
140}
141
142fn install_command(manager: &str) -> String {
143    match manager {
144        "bun" => "bun install".into(),
145        "pnpm" => "pnpm install".into(),
146        "yarn" => "yarn install".into(),
147        other => format!("{other} install"),
148    }
149}
150
151/// Nearest ancestor of `dir` containing a `.git` entry, canonicalized.
152fn workdir_covering(dir: &Path) -> Option<PathBuf> {
153    let start = dir.canonicalize().ok()?;
154    start
155        .ancestors()
156        .find(|ancestor| ancestor.join(".git").exists())
157        .map(Path::to_path_buf)
158}
159
160#[cfg(test)]
161mod tests;