capy-cli 0.7.2

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

struct Change {
    path: PathBuf,
    before: Option<Vec<u8>>,
    after: Vec<u8>,
}
/// Generate an application-owned mailable and compiled text/HTML templates.
pub fn make_mail(root: &Path, name: &str) -> Result<Vec<PathBuf>> {
    generate(root, name, false)
}
/// Generate a mail notification without unused channel stubs or a runtime registry.
pub fn make_notification(root: &Path, name: &str) -> Result<Vec<PathBuf>> {
    generate(root, name, true)
}
fn generate(root: &Path, name: &str, notification: bool) -> Result<Vec<PathBuf>> {
    generate_with(root, name, notification, |file, path, existing| {
        if existing {
            file.persist(path).map(|_| ()).map_err(|e| e.error.into())
        } else {
            file.persist_noclobber(path)
                .map(|_| ())
                .map_err(|e| e.error.into())
        }
    })
}
fn generate_with(
    root: &Path,
    name: &str,
    notification: bool,
    mut persist: impl FnMut(tempfile::NamedTempFile, &Path, bool) -> Result<()>,
) -> Result<Vec<PathBuf>> {
    let names = GeneratedNames::new(name)?;
    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 directory = if notification {
        "notifications"
    } else {
        "mail"
    };
    let registry_path = format!("app/{directory}/mod.rs");
    reject_symlinks(root, &root.join(&registry_path))?;
    let registry = match fs::read_to_string(root.join(&registry_path)) {
        Ok(value) => Some(value),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(e.into()),
    };
    names.check_registry(
        registry.as_deref().unwrap_or(""),
        &names.module,
        Generator::Controller,
    )?;
    let mut changes = Vec::new();
    let mut add = |relative: &str, after: String, existing: bool| -> Result<()> {
        let path = root.join(relative);
        reject_symlinks(root, &path)?;
        let before = match fs::read(&path) {
            Ok(bytes) => Some(bytes),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => return Err(e.into()),
        };
        if before.is_some() != existing {
            bail!(
                "{} {}. Capy never silently overwrites application files.",
                path.display(),
                if existing {
                    "is missing"
                } else {
                    "already exists"
                }
            );
        }
        let after = if relative.ends_with(".rs") {
            format_rust(&after)?
        } else {
            after
        };
        changes.push(Change {
            path,
            before,
            after: after.into_bytes(),
        });
        Ok(())
    };
    let source = if notification {
        include_str!("../templates/mail/notification.rs.txt")
    } else {
        include_str!("../templates/mail/mail.rs.txt")
    };
    add(
        &format!("app/{directory}/{}.rs", names.module),
        source
            .replace("{{module}}", &names.module)
            .replace("{{type}}", &names.ty),
        false,
    )?;
    add(
        &registry_path,
        format!(
            "{}\npub mod {};\n",
            registry
                .as_deref()
                .unwrap_or("//! Application-owned outbound communication."),
            names.module
        ),
        registry.is_some(),
    )?;
    add(
        &format!("templates/mail/{}.html", names.module),
        include_str!("../templates/mail/body.html.txt").into(),
        false,
    )?;
    add(
        &format!("templates/mail/{}.txt", names.module),
        include_str!("../templates/mail/body.txt.txt").into(),
        false,
    )?;
    if registry.is_none() {
        let app = read(root, "app/mod.rs")?;
        GeneratedNames::new(directory)?.check_registry(&app, directory, Generator::Controller)?;
        add("app/mod.rs", format!("{app}\npub mod {directory};\n"), true)?;
    }
    // Install only the optional mail capability; synchronous delivery needs no Jobs.
    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 mail.")?;
    let mut features = dependency
        .get("features")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();
    if !features.iter().any(|f| f.as_str() == Some("mail")) {
        features.push("mail");
    }
    dependency.insert("features", toml_edit::value(features));
    add("Cargo.toml", manifest.to_string(), true)?;
    let main = read(root, "src/main.rs")?;
    if !main.contains(".mail()") && !main.contains(".with_mail(") {
        if main.matches("App::new()").count() != 1 {
            bail!("Mail installation needs the conventional App::new() builder. Install App::mail manually for customized entry points; no files changed.");
        }
        add(
            "src/main.rs",
            main.replace("App::new()", "App::new().mail()"),
            true,
        )?;
    }
    if !root.join("config/mail.toml").exists() {
        add(
            "config/mail.toml",
            include_str!("../templates/mail/config.toml.txt").into(),
            false,
        )?;
    } else {
        reject_symlinks(root, &root.join("config/mail.toml"))?;
    }
    // Stage on the project filesystem before creating optional directories.
    let mut staged = Vec::new();
    for change in &changes {
        let mut file = tempfile::NamedTempFile::new_in(root)?;
        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);
    }
    let mut directories = Vec::new();
    let mut committed = 0;
    let result: Result<()> = (|| {
        for change in &changes {
            let mut missing: Vec<_> = change
                .path
                .parent()
                .context("Missing parent")?
                .ancestors()
                .take_while(|p| *p != root && !p.exists())
                .map(Path::to_path_buf)
                .collect();
            missing.reverse();
            for path in missing {
                reject_symlinks(root, &path)?;
                fs::create_dir(&path)?;
                directories.push(path);
            }
        }
        for (file, change) in staged.into_iter().zip(&changes) {
            persist(file, &change.path, change.before.is_some())?;
            committed += 1;
        }
        Ok(())
    })();
    if let Err(error) = result {
        for change in changes[..committed].iter().rev() {
            if let Some(before) = &change.before {
                let mut file = tempfile::NamedTempFile::new_in(root)?;
                file.as_file()
                    .set_permissions(fs::metadata(&change.path)?.permissions())?;
                file.write_all(before)?;
                file.as_file().sync_all()?;
                file.persist(&change.path)
                    .map_err(|e| e.error)
                    .context("Mail generator rollback failed; inspect partially installed files")?;
            } else {
                fs::remove_file(&change.path)?;
            }
        }
        for directory in directories.into_iter().rev() {
            fs::remove_dir(directory)?;
        }
        return Err(error.context("Mail generation failed; committed changes were rolled back"));
    }
    Ok(changes.into_iter().map(|c| c.path).collect())
}
fn read(root: &Path, relative: &str) -> Result<String> {
    let path = root.join(relative);
    reject_symlinks(root, &path)?;
    Ok(fs::read_to_string(path)?)
}
fn reject_symlinks(root: &Path, path: &Path) -> Result<()> {
    for ancestor in path.ancestors().take_while(|p| *p != root) {
        if fs::symlink_metadata(ancestor).is_ok_and(|m| m.file_type().is_symlink()) {
            bail!("Mail generator refuses symlink {}", ancestor.display());
        }
    }
    Ok(())
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn collision_and_failed_install_leave_application_unchanged() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("app");
        crate::new_project_with_frontend(&root, "app", crate::FrontendDriver::None).unwrap();
        let before = fs::read(root.join("app/mod.rs")).unwrap();
        let mut writes = 0;
        assert!(generate_with(&root, "WelcomeMail", false, |file, path, _| {
            writes += 1;
            if writes == 6 {
                bail!("simulated failure");
            }
            file.persist(path).map(|_| ()).map_err(|e| e.error.into())
        })
        .is_err());
        assert_eq!(fs::read(root.join("app/mod.rs")).unwrap(), before);
        assert!(!root.join("app/mail").exists());
        assert!(!root.join("templates").exists());
        make_mail(&root, "WelcomeMail").unwrap();
        make_notification(&root, "WelcomeNotification").unwrap();
        let before = fs::read(root.join("app/mail/mod.rs")).unwrap();
        assert!(make_mail(&root, "WelcomeMail").is_err());
        assert_eq!(fs::read(root.join("app/mail/mod.rs")).unwrap(), before);
        assert_eq!(
            read(&root, "src/main.rs")
                .unwrap()
                .matches(".mail()")
                .count(),
            1
        );
    }
    #[cfg(unix)]
    #[test]
    fn symlinked_templates_are_rejected_before_writes() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("app");
        crate::new_project_with_frontend(&root, "app", crate::FrontendDriver::None).unwrap();
        std::os::unix::fs::symlink(temp.path(), root.join("templates")).unwrap();
        assert!(make_mail(&root, "WelcomeMail").is_err());
        assert!(!root.join("app/mail").exists());
    }
}