kcode-rust-libs-v2 2.0.0

Create, edit, validate, and publish managed Rust libraries
Documentation
//! Six-operation facade for managed Rust libraries.

use std::error::Error as StdError;
use std::fmt;
use std::path::Path;

use kcode_rust_library_repository::Repository;
use kcode_rust_source::Source;

pub use kcode_rust_source::File;

/// A managed-library operation failure.
pub struct Error(String);

/// Result type returned by this crate.
pub type Result<T> = std::result::Result<T, Error>;

/// One complete editable managed-library source snapshot.
///
/// Edit [`Lib::files`] directly, then call [`Lib::write`] to commit the
/// complete replacement. Private state binds the snapshot to its repository
/// generation and publication credential.
pub struct Lib {
    /// Every managed UTF-8 source file, canonically sorted after open or write.
    pub files: Vec<File>,
    repository: Repository,
    name: String,
    token: Secret,
}

/// Creates a minimal Rust 2024 library and returns its complete source.
pub fn create(
    rust_libs_root: impl AsRef<Path>,
    name: &str,
    crates_io_registry_token: impl AsRef<str>,
) -> Result<Lib> {
    let token = Secret::new(crates_io_registry_token.as_ref())?;
    let source = initial_source(name)?;
    let repository = kcode_rust_library_repository::create(rust_libs_root, name, &source)
        .map_err(Error::leaf)?;
    Ok(Lib::new(repository, name, token))
}

/// Opens an existing current-generation library repository.
pub fn open(
    rust_libs_root: impl AsRef<Path>,
    name: &str,
    crates_io_registry_token: impl AsRef<str>,
) -> Result<Lib> {
    let token = Secret::new(crates_io_registry_token.as_ref())?;
    let repository =
        kcode_rust_library_repository::open(rust_libs_root, name).map_err(Error::leaf)?;
    Ok(Lib::new(repository, name, token))
}

/// Returns the current package version and root `Documentation.md`.
pub fn docs(rust_libs_root: impl AsRef<Path>, name: &str) -> Result<(String, String)> {
    kcode_rust_library_repository::docs(rust_libs_root, name).map_err(Error::leaf)
}

impl Lib {
    fn new(repository: Repository, name: &str, token: Secret) -> Self {
        let files = repository.source().files().to_vec();
        Self {
            files,
            repository,
            name: name.to_owned(),
            token,
        }
    }

    /// Atomically commits `files` if this repository snapshot is still current.
    pub fn write(&mut self) -> Result<()> {
        let source = Source::validate(&self.files, &self.name).map_err(Error::leaf)?;
        self.repository.replace(&source).map_err(Error::leaf)?;
        self.files = source.files().to_vec();
        Ok(())
    }

    /// Formats and validates exactly the current in-memory complete source.
    pub fn check(&self) -> Result<()> {
        let source = Source::validate(&self.files, &self.name).map_err(Error::leaf)?;
        kcode_rust_library_toolchain::check(&source).map_err(Error::leaf)
    }

    /// Rechecks and publishes exactly the current in-memory complete source.
    pub fn publish(&self) -> Result<()> {
        let source = Source::validate(&self.files, &self.name).map_err(Error::leaf)?;
        kcode_rust_library_toolchain::publish(&source, self.token.expose()).map_err(Error::leaf)
    }
}

impl Error {
    fn new(category: &str, message: impl fmt::Display) -> Self {
        Self(format!("{category}: {message}"))
    }

    fn leaf(error: impl fmt::Display) -> Self {
        Self(error.to_string())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_tuple("Error").field(&self.0).finish()
    }
}

impl StdError for Error {}

impl fmt::Debug for Lib {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Lib")
            .field("files", &self.files)
            .field("repository", &"[PRIVATE]")
            .field("name", &self.name)
            .field("token", &"[REDACTED]")
            .finish()
    }
}

struct Secret(String);

impl Secret {
    fn new(value: &str) -> Result<Self> {
        let value = value.trim();
        if value.is_empty() {
            return Err(Error::new(
                "invalid_token",
                "the crates.io registry token is empty",
            ));
        }
        Ok(Self(value.to_owned()))
    }

    fn expose(&self) -> &str {
        &self.0
    }
}

fn initial_source(name: &str) -> Result<Source> {
    Source::validate(
        &[
            File {
                path: "Cargo.toml".to_owned(),
                contents: format!(
                    "[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\n"
                ),
            },
            File {
                path: "Documentation.md".to_owned(),
                contents: String::new(),
            },
            File {
                path: "src/lib.rs".to_owned(),
                contents: String::new(),
            },
        ],
        name,
    )
    .map_err(Error::leaf)
}