verctl-core 0.9.6

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! The lockfiles a Version PR may change, read to prove it moved only
//! workspace versions.
//!
//! verctl never writes a lockfile: each moves through its owner
//! ([`crate::detect::owner`]). `check` parses the merge-base and HEAD copies
//! and compares them entry by entry with [`Lockfile::compare`].
//!
//! A registry entry and a workspace member can share a name, so they differ
//! by source:
//!
//! - `Cargo.lock`: a member has no `source`.
//! - `bun.lock`: a member sits under a `workspaces` key.
//! - `package-lock.json`: a member is a path outside `node_modules/`.
//! - `uv.lock`: a member has an `editable` or `virtual` source.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::{fmt, fs};

use anyhow::{Result, bail};
use serde_json::Value;

mod parse;

use parse::{parse_bun, parse_cargo, parse_npm, parse_uv};

/// How `check` treats a lockfile on a Version PR.
///
/// Not `#[non_exhaustive]`: `verctl-release` matches every variant
/// exhaustively.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    /// verctl parses it, and only workspace versions may move.
    Parsed(Format),
    /// It records no workspace version, so a Version PR leaves it unchanged:
    /// `pnpm-lock.yaml`, `poetry.lock`, and `pdm.lock`.
    Unchanged,
    /// verctl does not read it, so a Version PR that changes it fails:
    /// `yarn.lock` and the binary `bun.lockb`.
    Unreadable,
}

/// A lockfile format verctl parses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Format {
    /// `Cargo.lock`.
    Cargo,
    /// The text `bun.lock`, which is JSON with trailing commas.
    Bun,
    /// `package-lock.json` or `npm-shrinkwrap.json`, version 2 or 3.
    Npm,
    /// `uv.lock`.
    Uv,
}

/// How `check` treats the file at `path`, or `None` when it is no lockfile.
#[must_use]
pub fn kind(path: &Path) -> Option<Kind> {
    match path.file_name()?.to_str()? {
        "Cargo.lock" => Some(Kind::Parsed(Format::Cargo)),
        "bun.lock" => Some(Kind::Parsed(Format::Bun)),
        "package-lock.json" | "npm-shrinkwrap.json" => Some(Kind::Parsed(Format::Npm)),
        "uv.lock" => Some(Kind::Parsed(Format::Uv)),
        "pnpm-lock.yaml" | "poetry.lock" | "pdm.lock" => Some(Kind::Unchanged),
        "yarn.lock" | "bun.lockb" => Some(Kind::Unreadable),
        _ => None,
    }
}

/// One locked package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// What an error names: the package name, or the path of a JavaScript
    /// workspace member (`.` for the root) or of a `node_modules` entry.
    pub label: String,
    /// The package name, as its manifest writes it.
    pub name: String,
    /// The locked version, when the entry records one.
    pub version: Option<String>,
    /// Whether the entry is a workspace member.
    pub member: bool,
    /// Every other field, written with sorted keys. A reference to a member
    /// carries no version, so a member's bump leaves its dependents' entries
    /// unchanged.
    rest: String,
}

/// A parsed lockfile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lockfile {
    /// Every top-level field but the entries, written with sorted keys.
    header: String,
    /// Entries by a key unique within the file.
    pub(super) entries: BTreeMap<String, Entry>,
}

impl Entry {
    /// Whether a bump of the member this entry records changes the entry.
    ///
    /// The root workspace of a `bun.lock` records no `version` key, so a
    /// bump leaves it as it is. Every other member entry follows its
    /// manifest's version, even one that records none, because the lockfile
    /// cannot say it never will.
    #[must_use]
    pub fn follows_version(&self, format: Format) -> bool {
        !(format == Format::Bun && self.member && self.label == "." && self.version.is_none())
    }
}

/// A workspace member whose version a bump moves.
///
/// One rule decides which lockfile entry records it, for `check` when it
/// explains a lockfile change and for the version step when it decides whether
/// a lockfile owner has anything to do.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Member {
    /// The member's manifest. It and the lockfile directory passed to
    /// [`Member::records`] are relative to one root, or absolute under it.
    manifest: PathBuf,
    /// The names a lockfile may record it under: the configured name and the
    /// name its manifest declares.
    names: BTreeSet<String>,
}

impl Member {
    /// The member whose manifest is `manifest`, recorded under any of
    /// `names`.
    #[must_use]
    pub fn new(manifest: impl Into<PathBuf>, names: BTreeSet<String>) -> Self {
        Self {
            manifest: manifest.into(),
            names,
        }
    }

    /// The member's manifest.
    #[must_use]
    pub fn manifest(&self) -> &Path {
        &self.manifest
    }

    /// The directory a JavaScript lockfile at `lock_dir` names this member
    /// by: `.` for the lockfile's own directory.
    fn label(&self, lock_dir: &Path) -> Option<String> {
        let dir = self.manifest.parent()?;
        let label = dir.strip_prefix(lock_dir).ok()?;
        Some(if label.as_os_str().is_empty() {
            ".".to_owned()
        } else {
            label.display().to_string()
        })
    }

    /// Whether the entry called `name`, labelled `label`, in the `format`
    /// lockfile at `lock_dir` records this member.
    ///
    /// `Cargo.lock` and `uv.lock` name a member, `uv.lock` by its [PEP 503]
    /// normalised name. `bun.lock` and `package-lock.json` name it by its
    /// directory.
    ///
    /// [PEP 503]: https://peps.python.org/pep-0503/#normalized-names
    #[must_use]
    pub fn records(&self, format: Format, lock_dir: &Path, name: &str, label: &str) -> bool {
        match format {
            Format::Cargo => self.names.contains(name),
            Format::Uv => {
                let name = pep503(name);
                self.names.iter().any(|known| pep503(known) == name)
            }
            Format::Bun | Format::Npm => self.label(lock_dir).as_deref() == Some(label),
        }
    }
}

/// A Python project name as uv writes it in `uv.lock`: lowercase, with each
/// run of `-`, `_`, and `.` as one `-` ([PEP 503]).
///
/// [PEP 503]: https://peps.python.org/pep-0503/#normalized-names
pub(super) fn pep503(name: &str) -> String {
    let mut normalized = String::with_capacity(name.len());
    for character in name.chars() {
        if matches!(character, '-' | '_' | '.') {
            if !normalized.ends_with('-') {
                normalized.push('-');
            }
        } else {
            normalized.extend(character.to_lowercase());
        }
    }
    normalized
}

/// The package name a manifest declares, when its format has one verctl
/// reads: `package.name` in `Cargo.toml`, `project.name` in
/// `pyproject.toml`, and `name` in `package.json`.
#[must_use]
pub fn declared_name(manifest: &Path) -> Option<String> {
    let text = fs::read_to_string(manifest).ok()?;
    match manifest.file_name()?.to_str()? {
        "Cargo.toml" => toml_name(&text, "package"),
        "pyproject.toml" => toml_name(&text, "project"),
        "package.json" => serde_json::from_str::<Value>(&text)
            .ok()?
            .get("name")?
            .as_str()
            .map(str::to_owned),
        _ => None,
    }
}

fn toml_name(text: &str, table: &str) -> Option<String> {
    let document = text.parse::<toml_edit::DocumentMut>().ok()?;
    document
        .get(table)?
        .get("name")?
        .as_str()
        .map(str::to_owned)
}

/// One difference between two copies of a lockfile.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Change {
    /// A top-level field changed, such as the format version.
    Header,
    /// An entry exists only in the newer copy.
    Added(String),
    /// An entry exists only in the older copy.
    Removed(String),
    /// An entry changed in a field other than a member's version, or a
    /// registry entry changed its version.
    Changed(String),
    /// A workspace member's version moved and nothing else in its entry did.
    Member {
        /// The entry's label.
        label: String,
        /// The member's package name.
        name: String,
        /// The version in the older copy.
        from: Option<String>,
        /// The version in the newer copy.
        to: Option<String>,
    },
}

impl Change {
    /// Whether the change is a member's version alone, the only change a
    /// lockfile owner makes for a bump.
    #[must_use]
    pub fn is_member_version(&self) -> bool {
        matches!(
            self,
            Self::Member {
                label: _,
                name: _,
                from: _,
                to: _
            }
        )
    }
}

impl fmt::Display for Change {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Header => write!(f, "its header changed"),
            Self::Added(label) => write!(f, "`{label}` was added"),
            Self::Removed(label) => write!(f, "`{label}` was removed"),
            Self::Changed(label) => write!(f, "`{label}` changed"),
            Self::Member {
                label,
                from,
                to,
                name: _,
            } => write!(
                f,
                "`{label}` moved from {} to {}",
                from.as_deref().unwrap_or("no version"),
                to.as_deref().unwrap_or("no version")
            ),
        }
    }
}

impl Lockfile {
    /// Parse `text` as `format`.
    ///
    /// # Errors
    ///
    /// Returns an error when the text does not parse, or an entry lacks the
    /// fields its format requires, such as a `Cargo.lock` package without a
    /// name.
    pub fn parse(format: Format, text: &str) -> Result<Self> {
        match format {
            Format::Cargo => parse_cargo(text),
            Format::Bun => parse_bun(text),
            Format::Npm => parse_npm(text),
            Format::Uv => parse_uv(text),
        }
    }

    /// Every entry, in key order.
    pub fn entries(&self) -> impl Iterator<Item = &Entry> {
        self.entries.values()
    }

    /// The workspace members.
    pub fn members(&self) -> impl Iterator<Item = &Entry> {
        self.entries().filter(|entry| entry.member)
    }

    /// Whether a bump of `member` cannot change this `format` lockfile at
    /// `lock_dir`, so its owner has nothing to do.
    ///
    /// That applies only when the lockfile has an entry for the member and no
    /// such entry follows the member's version. A member with no entry stays
    /// uncertain in every format, so the owner runs. A `Cargo.lock` or
    /// `uv.lock` may name it by a name this check does not know. That happens
    /// when a virtual workspace's bump moves members that inherit its version.
    /// In a `bun.lock` or `package-lock.json`, a directory that fails to
    /// match must not skip a needed refresh either.
    #[must_use]
    pub fn is_idle_for(&self, format: Format, lock_dir: &Path, member: &Member) -> bool {
        let mut recorded = self
            .members()
            .filter(|entry| member.records(format, lock_dir, &entry.name, &entry.label))
            .peekable();
        let found = recorded.peek().is_some();
        found && recorded.all(|entry| !entry.follows_version(format))
    }

    /// What changed from `self` to `newer`, in key order. An entry whose key
    /// carries its version, a registry package's, shows a version move as
    /// one [`Change::Changed`] instead of a removal and an addition.
    #[must_use]
    pub fn compare(&self, newer: &Self) -> Vec<Change> {
        let mut changes = Vec::new();
        if self.header != newer.header {
            changes.push(Change::Header);
        }
        let mut removed = BTreeSet::new();
        let mut added = BTreeSet::new();
        for (key, old) in &self.entries {
            match newer.entries.get(key) {
                None => {
                    removed.insert(old.label.clone());
                }
                Some(new) if new == old => {}
                Some(new)
                    if new.member && old.member && new.name == old.name && new.rest == old.rest =>
                {
                    changes.push(Change::Member {
                        label: new.label.clone(),
                        name: new.name.clone(),
                        from: old.version.clone(),
                        to: new.version.clone(),
                    });
                }
                Some(new) => changes.push(Change::Changed(new.label.clone())),
            }
        }
        for (key, new) in &newer.entries {
            if !self.entries.contains_key(key) {
                added.insert(new.label.clone());
            }
        }
        for label in removed.intersection(&added) {
            changes.push(Change::Changed(label.clone()));
        }
        changes.extend(removed.difference(&added).cloned().map(Change::Removed));
        changes.extend(added.difference(&removed).cloned().map(Change::Added));
        changes
    }

    fn insert(&mut self, key: String, entry: Entry) -> Result<()> {
        let label = entry.label.clone();
        if self.entries.insert(key, entry).is_some() {
            bail!("`{label}` is locked twice");
        }
        Ok(())
    }
}