Skip to main content

verctl_core/
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 {
162    use std::fs;
163    use std::path::Path;
164    use std::process::Command;
165
166    use tempfile::TempDir;
167
168    use super::follow_up;
169
170    /// `files` are workspace-relative; parents are created.
171    fn tree(files: &[&str]) -> TempDir {
172        let root = TempDir::new().unwrap();
173        for rel in files {
174            let path = root.path().join(rel);
175            fs::create_dir_all(path.parent().unwrap()).unwrap();
176            fs::write(&path, "").unwrap();
177        }
178        root
179    }
180
181    fn repo_at(dir: &Path) {
182        assert!(
183            Command::new("git")
184                .current_dir(dir)
185                .args(["init", "-q", "-b", "main"])
186                .status()
187                .unwrap()
188                .success()
189        );
190    }
191
192    #[test]
193    fn a_cargo_lock_beside_the_manifest_asks_for_the_narrowest_refresh() {
194        let root = tree(&["Cargo.toml", "Cargo.lock"]);
195        assert_eq!(
196            follow_up(&root.path().join("Cargo.toml")),
197            Some("cargo update --workspace".into())
198        );
199    }
200
201    #[test]
202    fn a_workspace_member_finds_the_lock_at_the_repository_root() {
203        let root = tree(&["Cargo.lock", "crates/member/Cargo.toml"]);
204        repo_at(root.path());
205        assert_eq!(
206            follow_up(&root.path().join("crates/member/Cargo.toml")),
207            Some("cargo update --workspace".into())
208        );
209    }
210
211    #[test]
212    fn a_workspace_member_runs_its_owner_beside_the_lock() {
213        let root = tree(&["Cargo.lock", "crates/member/Cargo.toml"]);
214        repo_at(root.path());
215        let owner = super::owner(&root.path().join("crates/member/Cargo.toml")).unwrap();
216        let top = root.path().canonicalize().unwrap();
217        assert_eq!(owner.dir, top);
218        assert_eq!(owner.lockfile, Some(top.join("Cargo.lock")));
219    }
220
221    #[test]
222    fn a_cargo_lock_above_the_repository_is_not_ours() {
223        let root = tree(&["Cargo.lock", "checkout/Cargo.toml"]);
224        repo_at(&root.path().join("checkout"));
225        assert_eq!(follow_up(&root.path().join("checkout/Cargo.toml")), None);
226    }
227
228    #[test]
229    fn without_a_repository_the_search_stays_in_the_directory() {
230        let root = tree(&["Cargo.lock", "member/Cargo.toml"]);
231        assert_eq!(follow_up(&root.path().join("member/Cargo.toml")), None);
232    }
233
234    #[test]
235    fn a_bun_lock_at_the_repository_root_serves_a_package() {
236        let root = tree(&["bun.lock", "packages/pkg/package.json"]);
237        repo_at(root.path());
238        assert_eq!(
239            follow_up(&root.path().join("packages/pkg/package.json")),
240            Some("bun install".into())
241        );
242    }
243
244    #[test]
245    fn a_bun_lock_above_the_repository_is_not_ours() {
246        let root = tree(&["bun.lock", "checkout/package.json"]);
247        repo_at(&root.path().join("checkout"));
248        assert_eq!(follow_up(&root.path().join("checkout/package.json")), None);
249    }
250
251    #[test]
252    fn a_uv_lock_at_the_repository_root_serves_a_python_package() {
253        let root = tree(&["uv.lock", "tools/cli/pyproject.toml"]);
254        repo_at(root.path());
255        assert_eq!(
256            follow_up(&root.path().join("tools/cli/pyproject.toml")),
257            Some("uv lock".into())
258        );
259    }
260
261    #[test]
262    fn a_python_package_without_a_uv_lock_has_no_follow_up() {
263        let root = tree(&["pyproject.toml"]);
264        assert_eq!(follow_up(&root.path().join("pyproject.toml")), None);
265    }
266
267    #[test]
268    fn the_package_manager_field_outranks_the_lockfile() {
269        let root = TempDir::new().unwrap();
270        fs::write(root.path().join("bun.lock"), "").unwrap();
271        fs::write(
272            root.path().join("package.json"),
273            r#"{"packageManager":"pnpm@10.0.0"}"#,
274        )
275        .unwrap();
276        assert_eq!(
277            follow_up(&root.path().join("package.json")),
278            Some("pnpm install".into())
279        );
280    }
281}