verctl-core 0.9.5

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! Whether a manifest opts its package out of publishing.
//!
//! The stack's own tool reads this setting from the manifest, so verctl reads
//! it there too. A package that opts out releases on GitHub only, with no
//! `publisher: none` beside it. Nothing here follows a symlink or leaves the
//! tree it is given.

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

use anyhow::{Context, Result};
use toml_edit::{DocumentMut, Item};

/// How the manifest at `manifest` opts its package out of publishing, in the
/// words an error can repeat. `None` when it publishes, when the file is
/// missing, and for a manifest of another stack.
///
/// A `Cargo.toml` opts out with `package.publish` set to `false` or `[]`, and
/// a `package.json` with `"private": true`. `tree` is the root of the tree the
/// manifest is in, and no lookup leaves it.
///
/// # Errors
///
/// Returns an error when the manifest exists and cannot be read or parsed.
pub fn opt_out(manifest: &Path, tree: &Path) -> Result<Option<&'static str>> {
    let Some(bytes) = read_optional(manifest)? else {
        return Ok(None);
    };
    let text = String::from_utf8(bytes).with_context(|| manifest.display().to_string())?;
    let opted = match manifest.file_name().and_then(|name| name.to_str()) {
        Some("Cargo.toml") => {
            cargo_opts_out(manifest, &text, tree).with_context(|| manifest.display().to_string())?
        }
        Some("package.json") => {
            let json: serde_json::Value =
                serde_json::from_str(&text).with_context(|| manifest.display().to_string())?;
            (json.get("private") == Some(&serde_json::Value::Bool(true)))
                .then_some(r#"package.json sets "private": true"#)
        }
        _ => None,
    };
    Ok(opted)
}

/// How the `Cargo.toml` at `manifest`, containing `text`, sets
/// `package.publish` to `false` or `[]`, or `None` when it does not.
///
/// With `publish.workspace = true`, the value is `workspace.package.publish`
/// of its workspace root. That root is the file `package.workspace` names.
/// Without that key it is the same file when it contains a `[workspace]`, else
/// the nearest ancestor manifest that does, as Cargo finds it.
///
/// The search stays inside `tree` and never passes through a symlink. The
/// merge-base copy and the working tree therefore resolve the same root, and no
/// manifest outside the repository is read.
fn cargo_opts_out(manifest: &Path, text: &str, tree: &Path) -> Result<Option<&'static str>> {
    let document = text.parse::<DocumentMut>()?;
    let Some(package) = document.get("package") else {
        return Ok(None);
    };
    let Some(publish) = package.get("publish") else {
        return Ok(None);
    };
    if publish.get("workspace").and_then(Item::as_bool) != Some(true) {
        return Ok(denies(publish).map(|denial| match denial {
            Reason::False => "Cargo.toml sets publish = false",
            Reason::NoRegistry => "Cargo.toml sets publish = []",
        }));
    }
    let Some(workspace) = workspace_root(manifest, &document, tree)? else {
        return Ok(None);
    };
    Ok(workspace
        .get("workspace")
        .and_then(|table| table.get("package"))
        .and_then(|package| package.get("publish"))
        .and_then(denies)
        .map(|denial| match denial {
            Reason::False => "Cargo.toml inherits publish = false from its workspace",
            Reason::NoRegistry => "Cargo.toml inherits publish = [] from its workspace",
        }))
}

/// The two values of `publish` that turn publishing off, as the
/// [manifest reference] lists them.
///
/// [manifest reference]: https://doc.rust-lang.org/cargo/reference/manifest.html#the-publish-field
enum Reason {
    /// `publish = false`.
    False,
    /// `publish = []`: no registry may receive the package.
    NoRegistry,
}

/// Which value of `publish` turns publishing off, if any.
fn denies(publish: &Item) -> Option<Reason> {
    if publish.as_bool() == Some(false) {
        Some(Reason::False)
    } else if publish.as_array().is_some_and(toml_edit::Array::is_empty) {
        Some(Reason::NoRegistry)
    } else {
        None
    }
}

/// The workspace root manifest of the package at `manifest`, parsed, when
/// one exists inside `tree`. Every path is followed from `tree` without
/// resolving a symlink, in the package's own path and in each candidate's.
/// The merge-base copy contains no symlinks, so a manifest reached through one
/// would let the two trees resolve different roots.
fn workspace_root(
    manifest: &Path,
    document: &DocumentMut,
    tree: &Path,
) -> Result<Option<DocumentMut>> {
    if document.contains_key("workspace") {
        return Ok(Some(document.clone()));
    }
    let parent = manifest.parent().unwrap_or_else(|| Path::new(""));
    let Ok(package) = parent.strip_prefix(tree) else {
        return Ok(None);
    };
    if without_links(tree, package)?.is_none() {
        return Ok(None);
    }
    let named = document
        .get("package")
        .and_then(|package| package.get("workspace"))
        .and_then(Item::as_str);
    let dirs: Vec<PathBuf> = named.map_or_else(
        || package.ancestors().skip(1).map(Path::to_path_buf).collect(),
        |path| vec![package.join(path)],
    );
    for dir in dirs {
        let Some(candidate) = without_links(tree, &dir.join("Cargo.toml"))? else {
            continue;
        };
        let Some(bytes) = read_optional(&candidate)? else {
            continue;
        };
        let text = String::from_utf8(bytes).with_context(|| candidate.display().to_string())?;
        let parsed = text
            .parse::<DocumentMut>()
            .with_context(|| candidate.display().to_string())?;
        if parsed.contains_key("workspace") {
            return Ok(Some(parsed));
        }
    }
    Ok(None)
}

/// `path`, relative to `tree`, joined onto `tree` one component at a time.
/// `None` when a component is missing or a symlink, or when the path leaves
/// `tree`. A `..` drops a component already checked, so it never resolves
/// through a link.
fn without_links(tree: &Path, path: &Path) -> Result<Option<PathBuf>> {
    let mut resolved = tree.to_path_buf();
    let mut depth = 0_usize;
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if depth == 0 {
                    return Ok(None);
                }
                resolved.pop();
                depth -= 1;
            }
            Component::Normal(name) => {
                resolved.push(name);
                depth += 1;
                match fs::symlink_metadata(&resolved) {
                    Ok(metadata) if metadata.file_type().is_symlink() => return Ok(None),
                    Ok(_) => {}
                    Err(error)
                        if matches!(
                            error.kind(),
                            ErrorKind::NotFound | ErrorKind::NotADirectory
                        ) =>
                    {
                        return Ok(None);
                    }
                    Err(error) => {
                        return Err(error).with_context(|| resolved.display().to_string());
                    }
                }
            }
            Component::RootDir | Component::Prefix(_) => return Ok(None),
        }
    }
    Ok(Some(resolved))
}

fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
    match fs::read(path) {
        Ok(bytes) => Ok(Some(bytes)),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
        Err(error) => Err(error).with_context(|| path.display().to_string()),
    }
}

#[cfg(test)]
mod tests;