Skip to main content

verctl_core/workspace/
lockfile.rs

1//! The lockfiles a Version PR may change, read to prove it moved only
2//! workspace versions.
3//!
4//! verctl never writes a lockfile: each moves through its owner
5//! ([`crate::detect::owner`]). `check` parses the merge-base and HEAD copies
6//! and compares them entry by entry with [`Lockfile::compare`].
7//!
8//! A registry entry and a workspace member can share a name, so they differ
9//! by source:
10//!
11//! - `Cargo.lock`: a member has no `source`.
12//! - `bun.lock`: a member sits under a `workspaces` key.
13//! - `package-lock.json`: a member is a path outside `node_modules/`.
14//! - `uv.lock`: a member has an `editable` or `virtual` source.
15
16use std::collections::{BTreeMap, BTreeSet};
17use std::path::{Path, PathBuf};
18use std::{fmt, fs};
19
20use anyhow::{Result, bail};
21use serde_json::Value;
22
23mod parse;
24
25use parse::{parse_bun, parse_cargo, parse_npm, parse_uv};
26
27/// How `check` treats a lockfile on a Version PR.
28///
29/// Not `#[non_exhaustive]`: `verctl-release` matches every variant
30/// exhaustively.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Kind {
33    /// verctl parses it, and only workspace versions may move.
34    Parsed(Format),
35    /// It records no workspace version, so a Version PR leaves it unchanged:
36    /// `pnpm-lock.yaml`, `poetry.lock`, and `pdm.lock`.
37    Unchanged,
38    /// verctl does not read it, so a Version PR that changes it fails:
39    /// `yarn.lock` and the binary `bun.lockb`.
40    Unreadable,
41}
42
43/// A lockfile format verctl parses.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum Format {
47    /// `Cargo.lock`.
48    Cargo,
49    /// The text `bun.lock`, which is JSON with trailing commas.
50    Bun,
51    /// `package-lock.json` or `npm-shrinkwrap.json`, version 2 or 3.
52    Npm,
53    /// `uv.lock`.
54    Uv,
55}
56
57/// How `check` treats the file at `path`, or `None` when it is no lockfile.
58#[must_use]
59pub fn kind(path: &Path) -> Option<Kind> {
60    match path.file_name()?.to_str()? {
61        "Cargo.lock" => Some(Kind::Parsed(Format::Cargo)),
62        "bun.lock" => Some(Kind::Parsed(Format::Bun)),
63        "package-lock.json" | "npm-shrinkwrap.json" => Some(Kind::Parsed(Format::Npm)),
64        "uv.lock" => Some(Kind::Parsed(Format::Uv)),
65        "pnpm-lock.yaml" | "poetry.lock" | "pdm.lock" => Some(Kind::Unchanged),
66        "yarn.lock" | "bun.lockb" => Some(Kind::Unreadable),
67        _ => None,
68    }
69}
70
71/// One locked package.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Entry {
74    /// What an error names: the package name, or the path of a JavaScript
75    /// workspace member (`.` for the root) or of a `node_modules` entry.
76    pub label: String,
77    /// The package name, as its manifest writes it.
78    pub name: String,
79    /// The locked version, when the entry records one.
80    pub version: Option<String>,
81    /// Whether the entry is a workspace member.
82    pub member: bool,
83    /// Every other field, written with sorted keys. A reference to a member
84    /// carries no version, so a member's bump leaves its dependents' entries
85    /// unchanged.
86    rest: String,
87}
88
89/// A parsed lockfile.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct Lockfile {
92    /// Every top-level field but the entries, written with sorted keys.
93    header: String,
94    /// Entries by a key unique within the file.
95    pub(super) entries: BTreeMap<String, Entry>,
96}
97
98impl Entry {
99    /// Whether a bump of the member this entry records changes the entry.
100    ///
101    /// The root workspace of a `bun.lock` records no `version` key, so a
102    /// bump leaves it as it is. Every other member entry follows its
103    /// manifest's version, even one that records none, because the lockfile
104    /// cannot say it never will.
105    #[must_use]
106    pub fn follows_version(&self, format: Format) -> bool {
107        !(format == Format::Bun && self.member && self.label == "." && self.version.is_none())
108    }
109}
110
111/// A workspace member whose version a bump moves.
112///
113/// One rule decides which lockfile entry records it, for `check` when it
114/// explains a lockfile change and for the version step when it decides whether
115/// a lockfile owner has anything to do.
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct Member {
118    /// The member's manifest. It and the lockfile directory passed to
119    /// [`Member::records`] are relative to one root, or absolute under it.
120    manifest: PathBuf,
121    /// The names a lockfile may record it under: the configured name and the
122    /// name its manifest declares.
123    names: BTreeSet<String>,
124}
125
126impl Member {
127    /// The member whose manifest is `manifest`, recorded under any of
128    /// `names`.
129    #[must_use]
130    pub fn new(manifest: impl Into<PathBuf>, names: BTreeSet<String>) -> Self {
131        Self {
132            manifest: manifest.into(),
133            names,
134        }
135    }
136
137    /// The member's manifest.
138    #[must_use]
139    pub fn manifest(&self) -> &Path {
140        &self.manifest
141    }
142
143    /// The directory a JavaScript lockfile at `lock_dir` names this member
144    /// by: `.` for the lockfile's own directory.
145    fn label(&self, lock_dir: &Path) -> Option<String> {
146        let dir = self.manifest.parent()?;
147        let label = dir.strip_prefix(lock_dir).ok()?;
148        Some(if label.as_os_str().is_empty() {
149            ".".to_owned()
150        } else {
151            label.display().to_string()
152        })
153    }
154
155    /// Whether the entry called `name`, labelled `label`, in the `format`
156    /// lockfile at `lock_dir` records this member.
157    ///
158    /// `Cargo.lock` and `uv.lock` name a member, `uv.lock` by its [PEP 503]
159    /// normalised name. `bun.lock` and `package-lock.json` name it by its
160    /// directory.
161    ///
162    /// [PEP 503]: https://peps.python.org/pep-0503/#normalized-names
163    #[must_use]
164    pub fn records(&self, format: Format, lock_dir: &Path, name: &str, label: &str) -> bool {
165        match format {
166            Format::Cargo => self.names.contains(name),
167            Format::Uv => {
168                let name = pep503(name);
169                self.names.iter().any(|known| pep503(known) == name)
170            }
171            Format::Bun | Format::Npm => self.label(lock_dir).as_deref() == Some(label),
172        }
173    }
174}
175
176/// A Python project name as uv writes it in `uv.lock`: lowercase, with each
177/// run of `-`, `_`, and `.` as one `-` ([PEP 503]).
178///
179/// [PEP 503]: https://peps.python.org/pep-0503/#normalized-names
180pub(super) fn pep503(name: &str) -> String {
181    let mut normalized = String::with_capacity(name.len());
182    for character in name.chars() {
183        if matches!(character, '-' | '_' | '.') {
184            if !normalized.ends_with('-') {
185                normalized.push('-');
186            }
187        } else {
188            normalized.extend(character.to_lowercase());
189        }
190    }
191    normalized
192}
193
194/// The package name a manifest declares, when its format has one verctl
195/// reads: `package.name` in `Cargo.toml`, `project.name` in
196/// `pyproject.toml`, and `name` in `package.json`.
197#[must_use]
198pub fn declared_name(manifest: &Path) -> Option<String> {
199    let text = fs::read_to_string(manifest).ok()?;
200    match manifest.file_name()?.to_str()? {
201        "Cargo.toml" => toml_name(&text, "package"),
202        "pyproject.toml" => toml_name(&text, "project"),
203        "package.json" => serde_json::from_str::<Value>(&text)
204            .ok()?
205            .get("name")?
206            .as_str()
207            .map(str::to_owned),
208        _ => None,
209    }
210}
211
212fn toml_name(text: &str, table: &str) -> Option<String> {
213    let document = text.parse::<toml_edit::DocumentMut>().ok()?;
214    document
215        .get(table)?
216        .get("name")?
217        .as_str()
218        .map(str::to_owned)
219}
220
221/// One difference between two copies of a lockfile.
222#[derive(Debug, Clone, PartialEq, Eq)]
223#[non_exhaustive]
224pub enum Change {
225    /// A top-level field changed, such as the format version.
226    Header,
227    /// An entry exists only in the newer copy.
228    Added(String),
229    /// An entry exists only in the older copy.
230    Removed(String),
231    /// An entry changed in a field other than a member's version, or a
232    /// registry entry changed its version.
233    Changed(String),
234    /// A workspace member's version moved and nothing else in its entry did.
235    Member {
236        /// The entry's label.
237        label: String,
238        /// The member's package name.
239        name: String,
240        /// The version in the older copy.
241        from: Option<String>,
242        /// The version in the newer copy.
243        to: Option<String>,
244    },
245}
246
247impl Change {
248    /// Whether the change is a member's version alone, the only change a
249    /// lockfile owner makes for a bump.
250    #[must_use]
251    pub fn is_member_version(&self) -> bool {
252        matches!(
253            self,
254            Self::Member {
255                label: _,
256                name: _,
257                from: _,
258                to: _
259            }
260        )
261    }
262}
263
264impl fmt::Display for Change {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        match self {
267            Self::Header => write!(f, "its header changed"),
268            Self::Added(label) => write!(f, "`{label}` was added"),
269            Self::Removed(label) => write!(f, "`{label}` was removed"),
270            Self::Changed(label) => write!(f, "`{label}` changed"),
271            Self::Member {
272                label,
273                from,
274                to,
275                name: _,
276            } => write!(
277                f,
278                "`{label}` moved from {} to {}",
279                from.as_deref().unwrap_or("no version"),
280                to.as_deref().unwrap_or("no version")
281            ),
282        }
283    }
284}
285
286impl Lockfile {
287    /// Parse `text` as `format`.
288    ///
289    /// # Errors
290    ///
291    /// Returns an error when the text does not parse, or an entry lacks the
292    /// fields its format requires, such as a `Cargo.lock` package without a
293    /// name.
294    pub fn parse(format: Format, text: &str) -> Result<Self> {
295        match format {
296            Format::Cargo => parse_cargo(text),
297            Format::Bun => parse_bun(text),
298            Format::Npm => parse_npm(text),
299            Format::Uv => parse_uv(text),
300        }
301    }
302
303    /// Every entry, in key order.
304    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
305        self.entries.values()
306    }
307
308    /// The workspace members.
309    pub fn members(&self) -> impl Iterator<Item = &Entry> {
310        self.entries().filter(|entry| entry.member)
311    }
312
313    /// Whether a bump of `member` cannot change this `format` lockfile at
314    /// `lock_dir`, so its owner has nothing to do.
315    ///
316    /// That applies only when the lockfile has an entry for the member and no
317    /// such entry follows the member's version. A member with no entry stays
318    /// uncertain in every format, so the owner runs. A `Cargo.lock` or
319    /// `uv.lock` may name it by a name this check does not know. That happens
320    /// when a virtual workspace's bump moves members that inherit its version.
321    /// In a `bun.lock` or `package-lock.json`, a directory that fails to
322    /// match must not skip a needed refresh either.
323    #[must_use]
324    pub fn is_idle_for(&self, format: Format, lock_dir: &Path, member: &Member) -> bool {
325        let mut recorded = self
326            .members()
327            .filter(|entry| member.records(format, lock_dir, &entry.name, &entry.label))
328            .peekable();
329        let found = recorded.peek().is_some();
330        found && recorded.all(|entry| !entry.follows_version(format))
331    }
332
333    /// What changed from `self` to `newer`, in key order. An entry whose key
334    /// carries its version, a registry package's, shows a version move as
335    /// one [`Change::Changed`] instead of a removal and an addition.
336    #[must_use]
337    pub fn compare(&self, newer: &Self) -> Vec<Change> {
338        let mut changes = Vec::new();
339        if self.header != newer.header {
340            changes.push(Change::Header);
341        }
342        let mut removed = BTreeSet::new();
343        let mut added = BTreeSet::new();
344        for (key, old) in &self.entries {
345            match newer.entries.get(key) {
346                None => {
347                    removed.insert(old.label.clone());
348                }
349                Some(new) if new == old => {}
350                Some(new)
351                    if new.member && old.member && new.name == old.name && new.rest == old.rest =>
352                {
353                    changes.push(Change::Member {
354                        label: new.label.clone(),
355                        name: new.name.clone(),
356                        from: old.version.clone(),
357                        to: new.version.clone(),
358                    });
359                }
360                Some(new) => changes.push(Change::Changed(new.label.clone())),
361            }
362        }
363        for (key, new) in &newer.entries {
364            if !self.entries.contains_key(key) {
365                added.insert(new.label.clone());
366            }
367        }
368        for label in removed.intersection(&added) {
369            changes.push(Change::Changed(label.clone()));
370        }
371        changes.extend(removed.difference(&added).cloned().map(Change::Removed));
372        changes.extend(added.difference(&removed).cloned().map(Change::Added));
373        changes
374    }
375
376    fn insert(&mut self, key: String, entry: Entry) -> Result<()> {
377        let label = entry.label.clone();
378        if self.entries.insert(key, entry).is_some() {
379            bail!("`{label}` is locked twice");
380        }
381        Ok(())
382    }
383}