capy-cli 0.7.1

The command-line interface for the Capy web framework.
Documentation
use crate::{
    generate::format_rust, names::GeneratedNames, FrontendDriver, Generator, ProjectConfig,
};
use anyhow::{bail, Context, Result};
use fs2::FileExt;
use std::{
    fs::{self, OpenOptions},
    io::Write,
    path::{Path, PathBuf},
    time::{SystemTime, UNIX_EPOCH},
};

struct Change {
    path: PathBuf,
    before: Option<Vec<u8>>,
    after: Vec<u8>,
}

/// Install conventional auth without overwriting application-owned files.
/// All sources and registry edits are validated/formatted before the first mutation.
pub fn make_auth(root: &Path) -> Result<Vec<PathBuf>> {
    reject_symlinks(root, &root.join(".capy-generator.lock"))?;
    let lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(root.join(".capy-generator.lock"))?;
    lock.lock_exclusive()
        .context("Cannot lock the Capy generator registry")?;
    let mut changes = Vec::new();
    let mut add = |relative: &str, after: String, replace: bool| -> Result<()> {
        let path = root.join(relative);
        reject_symlinks(root, &path)?;
        let before = match fs::read(&path) {
            Ok(bytes) => Some(bytes),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => return Err(error.into()),
        };
        if !replace && before.is_some() {
            bail!("{} already exists. Auth may already be installed; Capy never overwrites application files.", path.display());
        }
        if replace && before.is_none() {
            bail!("Required registry {} is missing.", path.display());
        }
        let after = if relative.ends_with(".rs") {
            format_rust(&after)?
        } else {
            after
        };
        changes.push(Change {
            path,
            before,
            after: after.into_bytes(),
        });
        Ok(())
    };
    add(
        "app/auth.rs",
        include_str!("../templates/auth/auth.rs.txt").into(),
        false,
    )?;
    add(
        "app/models/user.rs",
        include_str!("../templates/auth/user.rs.txt").into(),
        false,
    )?;
    add("config/auth.toml", "# Auth is activated explicitly by App::auth in src/main.rs.\nsession_lifetime_seconds = 2592000\npassword_reset_lifetime_seconds = 1800\nsame_site = \"lax\"\n# cookie_name = \"my_app_session\"\n# Secure defaults to true in production, false on local HTTP.\n".into(), false)?;
    let app_registry = read(root, "app/mod.rs")?;
    GeneratedNames::new("Auth")?.check_registry(&app_registry, "auth", Generator::Controller)?;
    add(
        "app/mod.rs",
        format!("{app_registry}\npub mod auth;\n"),
        true,
    )?;
    let models = read(root, "app/models/mod.rs")?;
    GeneratedNames::new("User")?.check_registry(&models, "user", Generator::Model)?;
    add("app/models/mod.rs", format!("{models}\npub mod user;\npub use user::Entity as User;\npub use user::Model as UserModel;\n"), true)?;
    let migration = format!(
        "m{}_create_identity",
        SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
    );
    add(
        &format!("database/migrations/{migration}.rs"),
        include_str!("../templates/auth/migration.rs.txt").into(),
        false,
    )?;
    let registry = read(root, "database/migrations/mod.rs")?;
    if registry.matches("// capy:modules").count() != 1
        || registry.matches("// capy:migrations").count() != 1
    {
        bail!("Restore // capy:modules and // capy:migrations in the migration registry before installing auth.");
    }
    add(
        "database/migrations/mod.rs",
        registry
            .replace(
                "// capy:modules",
                &format!("mod {migration};\n// capy:modules"),
            )
            .replace(
                "// capy:migrations",
                &format!("Box::new({migration}::Migration),\n// capy:migrations"),
            ),
        true,
    )?;
    let main = read(root, "src/main.rs")?;
    if main.matches("App::new()").count() != 1 || !main.contains("as application;") {
        bail!("Auth installation needs the conventional App::new() builder and `application` crate alias in src/main.rs. Restore that entry point or install auth manually; no files changed.");
    }
    add(
        "src/main.rs",
        main.replace(
            "App::new()",
            "App::new().auth(application::app::auth::delivery())",
        ),
        true,
    )?;
    let mut manifest = read(root, "Cargo.toml")?.parse::<toml_edit::DocumentMut>()?;
    let dependency = manifest["dependencies"]["capy"]
        .as_table_like_mut()
        .context("Use a table-style capy-framework dependency before installing auth.")?;
    let mut features = dependency
        .get("features")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    if !features.iter().any(|v| v.as_str() == Some("auth")) {
        features.push("auth");
    }
    dependency.insert("features", toml_edit::value(features));
    add("Cargo.toml", manifest.to_string(), true)?;
    let gitignore = read(root, ".gitignore")?;
    add(
        ".gitignore",
        format!("{gitignore}\n/.capy-reset-outbox/\n"),
        true,
    )?;
    if ProjectConfig::load(root)?.frontend.driver == FrontendDriver::React {
        // Upgrade only the byte-for-byte previous conventional helper. Customized
        // clients must expose the hook explicitly; never replace application edits.
        let helper = read(root, "frontend/src/lib/api.ts")?;
        if helper == include_str!("../templates/auth/legacy-api.ts.txt") {
            add(
                "frontend/src/lib/api.ts",
                include_str!("../templates/frontend/src/lib/api.ts.txt").into(),
                true,
            )?;
        } else if !helper.contains("export function setCsrfTokenProvider(") {
            bail!("The customized frontend API helper needs setCsrfTokenProvider support. Add the hook from the current Capy template before installing auth; no files changed.");
        }
        add(
            "frontend/src/lib/auth.ts",
            include_str!("../templates/auth/auth.ts.txt").into(),
            false,
        )?;
        let main = read(root, "frontend/src/main.tsx")?;
        add(
            "frontend/src/main.tsx",
            format!("import './lib/auth'\n{main}"),
            true,
        )?;
    }
    // Stage and sync every file before committing. Cooperative generators share the lock.
    let mut staged = Vec::new();
    for change in &changes {
        let mut file =
            tempfile::NamedTempFile::new_in(change.path.parent().context("Missing parent")?)?;
        if change.before.is_some() {
            file.as_file()
                .set_permissions(fs::metadata(&change.path)?.permissions())?;
        }
        file.write_all(&change.after)?;
        file.as_file().sync_all()?;
        staged.push(file);
    }
    for (index, (file, change)) in staged.into_iter().zip(&changes).enumerate() {
        let result = if change.before.is_some() {
            file.persist(&change.path).map(|_| ()).map_err(|e| e.error)
        } else {
            file.persist_noclobber(&change.path)
                .map(|_| ())
                .map_err(|e| e.error)
        };
        if let Err(error) = result {
            for previous in changes[..index].iter().rev() {
                match &previous.before {
                    Some(bytes) => fs::write(&previous.path, bytes).with_context(|| {
                        format!(
                            "Auth rollback failed for {}; inspect the partially installed files.",
                            previous.path.display()
                        )
                    })?,
                    None => fs::remove_file(&previous.path)?,
                }
            }
            return Err(error)
                .context("Auth installation failed; committed file changes were rolled back");
        }
    }
    Ok(changes.into_iter().map(|change| change.path).collect())
}
fn read(root: &Path, relative: &str) -> Result<String> {
    let path = root.join(relative);
    reject_symlinks(root, &path)?;
    fs::read_to_string(&path).with_context(|| format!("Cannot read {}", path.display()))
}
fn reject_symlinks(root: &Path, path: &Path) -> Result<()> {
    for ancestor in path.ancestors().take_while(|p| *p != root) {
        if let Ok(metadata) = fs::symlink_metadata(ancestor) {
            if metadata.file_type().is_symlink() {
                bail!("Auth installer refuses symlink {}", ancestor.display());
            }
        }
    }
    Ok(())
}