verctl-core 0.9.6

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! Rewrite collocated tool pins when a package version changes.

use std::fs;
use std::path::{Component, Path, PathBuf};

use anyhow::{Context, Result, bail};
use regex::{NoExpand, Regex, escape};
use toml_edit::{DocumentMut, Formatted, Item, Value};

use crate::config::{Config, PLACEHOLDER, Pin, PinPattern};

/// A version as verctl writes one: digits and dots, then an optional
/// candidate prerelease, `-<tag>.<count>`, such as `0.8.2-rc.1`.
///
/// A pin names a version verctl wrote, so the pattern contains no other
/// prerelease or build. A wider one would read `tool-1.2.3-linux-x64` against
/// `tool-{version}-x64` as version `1.2.3-linux`, and the rewrite would drop
/// `-linux`; this one matches nothing there, so the pin fails instead.
const VERSION: &str = r"[0-9]+(?:\.[0-9]+)*(?:-[a-z]+\.[0-9]+)?";

/// Current declared versions of every configured package.
///
/// # Errors
///
/// Returns an error when a package's driver cannot be resolved, its manifest
/// cannot be read, or the driver cannot read a version from it.
pub fn current_versions(root: &Path, config: &Config) -> Result<Vec<(String, String)>> {
    let mut versions = Vec::new();
    for spec in &config.packages {
        versions.push((spec.name.clone(), spec.current(config, root)?.version));
    }
    Ok(versions)
}

/// Rewrite every pin to the versions given, and return the files changed.
///
/// # Errors
///
/// Returns an error when:
///
/// - a pin file lies outside `root` or is a symlink;
/// - a pin file cannot be read or written;
/// - a pin file has no `[tools]` entry for the pinned tool;
/// - a pin has a pattern that is malformed or matches a number of times its
///   `occurrences` does not allow.
///
/// Files rewritten before the failing pin stay changed.
pub fn write(root: &Path, pins: &[Pin], versions: &[(String, String)]) -> Result<Vec<PathBuf>> {
    let mut written = Vec::new();
    for pin in pins {
        let Some((_, version)) = versions.iter().find(|(name, _)| name == &pin.package) else {
            continue;
        };
        let (path, _, body) = rewritten(root, pin, version)?;
        fs::write(&path, body).with_context(|| format!("write pin {}", path.display()))?;
        written.push(path);
    }
    Ok(written)
}

/// Same checks as `write`, without touching disk.
///
/// # Errors
///
/// Returns an error under the same conditions as [`write()`], except that no
/// file is written, so a write failure cannot occur.
pub fn plan(root: &Path, pins: &[Pin], versions: &[(String, String)]) -> Result<Vec<PathBuf>> {
    let mut planned = Vec::new();
    for pin in pins {
        let Some((_, version)) = versions.iter().find(|(name, _)| name == &pin.package) else {
            continue;
        };
        let (path, _, _) = rewritten(root, pin, version)?;
        planned.push(path);
    }
    Ok(planned)
}

/// A `pins` entry that does not match the version its package is at.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stale {
    /// The pinned file, as the entry names it.
    pub file: PathBuf,
    /// What is wrong: a pattern that does not match at its declared count,
    /// a file that cannot be rewritten, or one that names another version.
    pub problem: String,
}

/// Every `pins` entry whose file would change, or could not be rewritten, at
/// `versions`, so one run lists every file to fix. Nothing is written.
#[must_use]
pub fn stale(root: &Path, pins: &[Pin], versions: &[(String, String)]) -> Vec<Stale> {
    pins.iter()
        .filter_map(|pin| {
            let (_, version) = versions.iter().find(|(name, _)| name == &pin.package)?;
            let problem = match rewritten(root, pin, version) {
                Ok((_, raw, body)) if raw == body => return None,
                Ok(_) => format!("names a version other than {} {version}", pin.package),
                Err(error) => format!("{error:#}"),
            };
            Some(Stale {
                file: pin.file.clone(),
                problem,
            })
        })
        .collect()
}

/// The pin's path, its bytes now, and its bytes at `version`.
fn rewritten(root: &Path, pin: &Pin, version: &str) -> Result<(PathBuf, String, String)> {
    ensure_inside(root, &pin.file)?;
    let path = root.join(&pin.file);
    let raw = fs::read_to_string(&path).with_context(|| format!("read pin {}", path.display()))?;
    let mut body = raw.clone();
    if let Some(tool) = &pin.tool {
        body = rewrite_tool(&body, tool, version, &path)?;
    }
    for pattern in &pin.patterns {
        body = rewrite_pattern(&body, pattern, version)
            .with_context(|| format!("pin {}", path.display()))?;
    }
    Ok((path, raw, body))
}

/// Verify that `file` stays inside `root` (relative, with no `..` and no
/// symlink, and with its canonical path under `root`), labelling errors with
/// `label`.
///
/// # Errors
///
/// Returns an error when `file` is absolute, contains `..`, is a symlink, or
/// resolves outside `root`.
pub fn ensure_inside_repo(root: &Path, file: &Path, label: &str) -> Result<()> {
    if file.is_absolute()
        || file
            .components()
            .any(|part| matches!(part, Component::ParentDir))
    {
        bail!("{label} must stay inside the repo: {}", file.display());
    }
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let path = root.join(file);
    if let Ok(meta) = fs::symlink_metadata(&path)
        && meta.file_type().is_symlink()
    {
        bail!("{label} must not be a symlink: {}", path.display());
    }
    let resolved = path.canonicalize().unwrap_or(path);
    if !resolved.starts_with(&root) {
        bail!("{label} must stay inside the repo: {}", file.display());
    }
    Ok(())
}

fn ensure_inside(root: &Path, file: &Path) -> Result<()> {
    ensure_inside_repo(root, file, "pin file")
}

/// A mise `[tools]` entry, plus every `?ref=v…` include naming its repo.
///
/// Only the version value changes. A bare string, the `version` of an inline
/// table such as `{ version = "1.2.3", os = ["linux"] }`, and the `version` of
/// a `[tools.<name>]` table all keep their comments, spacing, and options.
fn rewrite_tool(body: &str, tool: &str, version: &str, path: &Path) -> Result<String> {
    let mut doc: DocumentMut = body
        .parse()
        .with_context(|| format!("parse pin {}", path.display()))?;
    let tools = doc
        .get_mut("tools")
        .and_then(Item::as_table_like_mut)
        .with_context(|| format!("{} has no [tools]", path.display()))?;
    let Some(entry) = tools.get_mut(tool) else {
        bail!("{} has no tools.{tool}", path.display());
    };
    set_tool_version(entry, version).with_context(|| format!("{} tools.{tool}", path.display()))?;
    rewrite_own_refs(&doc.to_string(), tool, version)
        .with_context(|| format!("pin {}", path.display()))
}

/// Replace the version a `[tools]` entry specifies, and nothing else of it.
fn set_tool_version(entry: &mut Item, version: &str) -> Result<()> {
    match entry {
        Item::Value(Value::InlineTable(table)) => {
            set_string(table.get_mut("version").context(NO_VERSION)?, version)
        }
        Item::Table(table) => {
            let Some(Item::Value(existing)) = table.get_mut("version") else {
                bail!(NO_VERSION);
            };
            set_string(existing, version)
        }
        Item::Value(existing) => set_string(existing, version),
        Item::None | Item::ArrayOfTables(_) => bail!("is not a version or a table"),
    }
}

/// What an entry that contains no version string reports.
const NO_VERSION: &str = "has no version string to rewrite";

/// Swap the string in `existing` for `version`, keeping the whitespace and the
/// comment around it.
fn set_string(existing: &mut Value, version: &str) -> Result<()> {
    let Value::String(old) = existing else {
        bail!(NO_VERSION);
    };
    let mut new = Formatted::new(version.to_owned());
    *new.decor_mut() = old.decor().clone();
    *old = new;
    Ok(())
}

/// The version in every occurrence of `pattern.match`, where `{version}`
/// marks it. The rest is literal. A bash header, a README sentence, and a
/// YAML value all rewrite the same way, with nothing assumed about the file.
///
/// `Config::load` refuses a pattern with nothing marking where the version
/// starts and ends. So the pattern matches the whole token, a candidate's
/// prerelease included, and never a numeric head with its tail kept.
///
/// The file must contain the version exactly as often as declared. The count is
/// never inferred. A count off in either direction stops the release. Too few
/// means the pin tracks nothing, and too many means a version spelling nobody
/// accounted for. See `Occurrences` for the vocabulary.
fn rewrite_pattern(body: &str, pattern: &PinPattern, version: &str) -> Result<String> {
    let text = &pattern.r#match;
    let (before, after) = text
        .split_once(PLACEHOLDER)
        .with_context(|| format!("pattern {text:?} has no {PLACEHOLDER}"))?;
    if after.contains(PLACEHOLDER) {
        bail!("pattern {text:?} has more than one {PLACEHOLDER}");
    }
    // `R` is carriage return and line feed (CRLF) mode. Without it `$` matches
    // only before `\n`. A file checked out with CRLF endings has a `\r` between
    // the version and the line end. It matches nothing, so a correct file stops
    // a release.
    let (open, close) = if pattern.whole_line {
        ("(?mR)^", "$")
    } else {
        ("", "")
    };
    let finder = Regex::new(&format!(
        "{open}{}{VERSION}{}{close}",
        escape(before),
        escape(after)
    ))
    .with_context(|| format!("pattern {text:?}"))?;
    let found = finder.find_iter(body).count();
    if !pattern.occurrences.allows(found) {
        bail!(
            "pattern {text:?} matches {found} times, expected {}",
            pattern.occurrences
        );
    }
    let pinned = format!("{before}{version}{after}");
    Ok(finder.replace_all(body, NoExpand(&pinned)).into_owned())
}

/// Every `?ref=v…` include that names this tool's own repository. A sibling
/// repo's include in the same file is not ours to move. The URL path must
/// carry the tool's own name.
///
/// The ref runs to the end of the URL or to the next query separator (`&`,
/// `#`, `;`). A ref that is a whole version, prerelease included, moves. A
/// ref that starts with a digit and is not a whole version, such as
/// `v1.2.3_local`, fails, so its numeric head is never moved with its tail
/// kept. A ref that does not start with a digit, such as a branch, is not a pin
/// and stays put.
fn rewrite_own_refs(body: &str, tool: &str, version: &str) -> Result<String> {
    let name = escape(tool.rsplit(['/', ':']).next().unwrap_or(tool));
    let finder = Regex::new(&format!(
        r#"(?<include>/{name}(?:\.git)?//[^\s"',\]]*\?ref=v)(?<reference>[0-9][^\s"',\]&#;]*)"#
    ))
    .with_context(|| format!("tool {tool:?}"))?;
    let whole = Regex::new(&format!("^{VERSION}$")).context("the version pattern")?;
    if let Some(found) = finder
        .captures_iter(body)
        .find(|found| !whole.is_match(&found["reference"]))
    {
        bail!(
            "{:?} pins v{}, which is not a version this rewrites",
            &found[0],
            &found["reference"]
        );
    }
    Ok(finder
        .replace_all(body, format!("${{include}}{version}"))
        .into_owned())
}

#[cfg(test)]
mod tests;