kcode-rust-libs-v2 1.1.0

Create, edit, validate, and publish complete agent-authored Rust library snapshots
Documentation
//! Six-operation managed Rust-library boundary.

mod model;
mod repository;
mod sandbox;

use std::fmt;
use std::path::{Path, PathBuf};

pub use model::{Error, File, Result};
use model::{ValidSource, validate_name, validate_source};

/// One complete editable managed-library source snapshot.
///
/// Edit `files` directly and call [`Lib::write`] to commit the complete
/// replacement. Private fields bind the source to its repository generation
/// and publication credential.
pub struct Lib {
    /// Every useful UTF-8 source file, canonically sorted by path after open or write.
    pub files: Vec<File>,
    repository: PathBuf,
    name: String,
    identity: 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())?;
    validate_name(name)?;
    let source = initial_source(name)?;
    let snapshot = repository::create(rust_libs_root.as_ref(), name, &source)?;
    Ok(Lib {
        files: snapshot.files,
        repository: snapshot.repository,
        name: name.to_owned(),
        identity: snapshot.identity,
        token,
    })
}

/// Opens an existing library, migrating a valid legacy flat repository when needed.
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())?;
    validate_name(name)?;
    let snapshot = repository::open(rust_libs_root.as_ref(), name)?;
    Ok(Lib {
        files: snapshot.files,
        repository: snapshot.repository,
        name: name.to_owned(),
        identity: snapshot.identity,
        token,
    })
}

/// Returns the package version and root `Documentation.md`, migrating when needed.
pub fn docs(rust_libs_root: impl AsRef<Path>, name: &str) -> Result<(String, String)> {
    validate_name(name)?;
    repository::docs(rust_libs_root.as_ref(), name)
}

impl Lib {
    /// Atomically commits `files` as the complete source if this snapshot is current.
    pub fn write(&mut self) -> Result<()> {
        let source = validate_source(&self.files, &self.name)?;
        let snapshot = repository::replace(&self.repository, &self.identity, &source)?;
        self.files = snapshot.files;
        self.identity = snapshot.identity;
        Ok(())
    }

    /// Validates exactly the current in-memory complete source.
    pub fn check(&self) -> Result<()> {
        let source = validate_source(&self.files, &self.name)?;
        sandbox::check(&source)
    }

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

impl fmt::Debug for Lib {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Lib")
            .field("files", &self.files)
            .field("repository", &self.repository)
            .field("name", &self.name)
            .field("identity", &"[PRIVATE]")
            .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<ValidSource> {
    validate_source(
        &[
            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,
    )
}