verctl-core 0.9.6

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! How a package is published.
//!
//! [`Publisher::of`] resolves it once: the built-in cargo or bun upload, a
//! command the repository wrote, or a release on GitHub only. A built-in
//! publisher has typed options a package sets under `publish`, such as
//! [`CargoPublish::verify`], and keeps its registry check. A replaced
//! command has none of either.
//!
//! Placeholders in a `publishers` entry: `{path}` `{dir}` `{registry}`
//! `{config}`, and in a `query` also `{name}` `{version}`. A placeholder with
//! no value fails the run instead of dropping its argument.

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

use anyhow::{Context, Result, bail};
use serde::Deserialize;

mod resolve;

use resolve::BUN_QUERY;
pub use resolve::{
    CargoPublish, Publisher, RELEASE_ONLY, check_options, prerelease_tag, publisher_name, resolve,
    resolve_for_version, stock_publisher_for_file,
};

/// A publisher recipe: the command to upload a package and where its registry
/// config lives.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct PublisherSpec {
    /// What the registry calls the package. Defaults to `package`.
    pub noun: Option<String>,
    /// Upload command, with the placeholders from the module docs.
    pub argv: Option<Vec<String>>,
    /// Ancestor file that owns registry/auth (`bunfig.toml`).
    pub config_name: Option<String>,
    /// Arguments appended when `config_name` is found.
    pub config_argv: Option<Vec<String>>,
    /// Appended when `registry` is set and does not alias to empty.
    pub registry_argv: Option<Vec<String>>,
    /// Appended when there is no registry (or the alias is empty).
    pub default_argv: Option<Vec<String>>,
    /// Registry aliases. An empty value means the default registry, which needs
    /// no flag.
    #[serde(default)]
    pub registries: BTreeMap<String, String>,
    /// Asks the registry whether a version is published: it exits zero and
    /// prints the version when the registry has it. It runs in the package
    /// directory, where the publisher's registry config is in effect. When
    /// omitted, the stock recipe's query applies; an empty list turns the check
    /// off, leaving the stderr match.
    pub query: Option<Vec<String>>,
}

impl PublisherSpec {
    /// Look up one of the stock publishers (`cargo` or `bun`) by name.
    #[must_use]
    pub fn stock(name: &str) -> Option<Self> {
        match name {
            "cargo" => Some(Self {
                noun: Some("crate".into()),
                argv: Some(vec![
                    "cargo".into(),
                    "publish".into(),
                    "--locked".into(),
                    "--manifest-path".into(),
                    "{path}".into(),
                ]),
                registry_argv: Some(vec!["--registry".into(), "{registry}".into()]),
                registries: BTreeMap::from([("crates-io".into(), String::new())]),
                ..Self::default()
            }),
            "bun" => Some(Self {
                noun: Some("package".into()),
                argv: Some(vec![
                    "bun".into(),
                    "publish".into(),
                    "--tolerate-republish".into(),
                    "--cwd".into(),
                    "{dir}".into(),
                ]),
                config_name: Some("bunfig.toml".into()),
                config_argv: Some(vec!["--config".into(), "{config}".into()]),
                registry_argv: Some(vec!["--registry".into(), "{registry}".into()]),
                default_argv: Some(vec!["--access".into(), "public".into()]),
                registries: BTreeMap::from([
                    ("npm".into(), String::new()),
                    ("github".into(), "https://npm.pkg.github.com".into()),
                ]),
                query: Some(BUN_QUERY.iter().map(|part| (*part).to_owned()).collect()),
            }),
            _ => None,
        }
    }

    fn merge(self, over: Self) -> Self {
        Self {
            noun: over.noun.or(self.noun),
            argv: over.argv.or(self.argv),
            config_name: over.config_name.or(self.config_name),
            config_argv: over.config_argv.or(self.config_argv),
            registry_argv: over.registry_argv.or(self.registry_argv),
            default_argv: over.default_argv.or(self.default_argv),
            registries: if over.registries.is_empty() {
                self.registries
            } else {
                over.registries
            },
            query: over.query.or(self.query),
        }
    }

    /// Render the noun and argv for one package, expanding placeholders.
    ///
    /// # Errors
    ///
    /// Returns an error when the publisher declares no `argv`, or when an
    /// argument uses a placeholder with no value for this package.
    pub fn render(
        &self,
        name: &str,
        manifest: &Path,
        registry: Option<&str>,
    ) -> Result<(String, Vec<String>)> {
        let argv = self
            .argv
            .as_ref()
            .with_context(|| format!("publisher {name:?} needs argv"))?;
        let out = self.assemble(argv, manifest, registry, &[], ExtraArgs::Upload)?;
        let noun = self.noun.clone().unwrap_or_else(|| "package".into());
        Ok((noun, out))
    }

    /// Expand `argv` for the package in `manifest`, then append what
    /// `appended` requests. `extra` adds placeholders.
    ///
    /// # Errors
    ///
    /// Returns an error when a placeholder has no value.
    pub fn assemble(
        &self,
        argv: &[String],
        manifest: &Path,
        registry: Option<&str>,
        extra: &[(&'static str, String)],
        appended: ExtraArgs,
    ) -> Result<Vec<String>> {
        let dir = package_dir(manifest);
        let config = self
            .config_name
            .as_deref()
            .and_then(|file| find_config(manifest, file));
        let registry = resolve_registry(&self.registries, registry);
        let mut ctx = BTreeMap::from([
            ("path", manifest.display().to_string()),
            ("dir", dir.display().to_string()),
        ]);
        ctx.extend(extra.iter().cloned());
        if let Some(path) = &config {
            ctx.insert("config", path.display().to_string());
        }
        if let Some(registry) = &registry {
            ctx.insert("registry", registry.clone());
        }
        let mut out = expand(argv, &ctx)?;
        let (recipe, default) = match appended {
            ExtraArgs::Upload => (true, true),
            ExtraArgs::StockQuery => (true, false),
            ExtraArgs::Nothing => (false, false),
        };
        if recipe
            && config.is_some()
            && let Some(extra) = &self.config_argv
        {
            out.extend(expand(extra, &ctx)?);
        }
        if recipe && config.is_none() && registry.is_some() {
            if let Some(extra) = &self.registry_argv {
                out.extend(expand(extra, &ctx)?);
            }
        } else if default
            && registry.is_none()
            && let Some(extra) = &self.default_argv
        {
            out.extend(expand(extra, &ctx)?);
        }
        Ok(out)
    }
}

/// What [`PublisherSpec::assemble`] appends after the expanded argv.
#[derive(Debug, Clone, Copy)]
pub enum ExtraArgs {
    /// The recipe's config or registry arguments, else `default_argv`
    /// (`--access public`): the full upload command.
    Upload,
    /// The recipe's config or registry arguments, so a stock query targets the
    /// registry the upload goes to.
    StockQuery,
    /// Nothing: a query a repository declares runs as written, and reaches
    /// the registry through its own `{registry}` or `{config}` placeholder.
    Nothing,
}

/// The directory a manifest sits in; `.` for a bare file name.
#[must_use]
pub fn package_dir(manifest: &Path) -> &Path {
    manifest
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// Resolve a registry alias against `aliases`.
#[must_use]
pub fn resolve_registry(
    aliases: &BTreeMap<String, String>,
    registry: Option<&str>,
) -> Option<String> {
    let raw = registry?.trim();
    if raw.is_empty() {
        return None;
    }
    match aliases.get(raw) {
        Some(mapped) if mapped.is_empty() => None,
        Some(mapped) => Some(mapped.clone()),
        None => Some(raw.to_owned()),
    }
}

/// Replace each `{placeholder}` in `parts` with the value `ctx` provides for
/// it.
///
/// A placeholder left after expansion fails the run instead of dropping its
/// argument. A dropped argument would shorten the command line, and a typo
/// such as `{registr}` would surface later as another tool's error.
///
/// A known placeholder with no value for this package, such as `{registry}`
/// on a package with no registry, fails the same way. Text in braces that is
/// not a placeholder name, such as a JSON argument, passes through.
///
/// # Errors
///
/// Returns an error naming the argument, the placeholder, and the
/// placeholders that have a value here.
pub fn expand(parts: &[String], ctx: &BTreeMap<&str, String>) -> Result<Vec<String>> {
    let mut out = Vec::with_capacity(parts.len());
    for part in parts {
        let mut expanded = part.clone();
        for (key, value) in ctx {
            expanded = expanded.replace(&format!("{{{key}}}"), value);
        }
        if let Some(name) = placeholder_in(&expanded) {
            let known = ctx
                .keys()
                .map(|key| format!("{{{key}}}"))
                .collect::<Vec<_>>()
                .join(" ");
            bail!(
                "argument {part:?} uses {{{name}}}, which has no value for this package; the placeholders with a value are {known}"
            );
        }
        if !expanded.is_empty() {
            out.push(expanded);
        }
    }
    Ok(out)
}

/// The first `{name}` in `text` whose name is a placeholder name: a letter or
/// underscore, then letters, digits, or underscores.
fn placeholder_in(text: &str) -> Option<&str> {
    let mut rest = text;
    while let Some(open) = rest.find('{') {
        let after = &rest[open + 1..];
        let close = after.find('}')?;
        let name = &after[..close];
        let mut chars = name.chars();
        if chars
            .next()
            .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            return Some(name);
        }
        rest = after;
    }
    None
}

fn find_config(manifest: &Path, file_name: &str) -> Option<PathBuf> {
    let start = manifest.parent().unwrap_or(manifest);
    for dir in start.ancestors() {
        let candidate = dir.join(file_name);
        if candidate.is_file() {
            return Some(candidate);
        }
        if dir.join(".git").exists() {
            break;
        }
    }
    None
}