laravel-excel 0.3.0

Excel, CSV, ODS, HTML and PDF exports and imports with typed columns for Laravel Rust: a port of Laravel Excel (maatwebsite/excel).
Documentation
//! The `make:export` and `make:import` commands: `ExportMakeCommand` and `ImportMakeCommand`.
//!
//! They write a file to `src/exports` or `src/imports`, from the same stubs as Laravel Excel's.
//! Declare the new module in that directory's `mod.rs` yourself.

use std::path::PathBuf;

use laravel::console::{Console, command};

use crate::error::ExcelError;

fn snake(name: &str) -> String {
    let mut snake = String::new();
    for (index, c) in name.chars().enumerate() {
        if c.is_uppercase() {
            if index > 0 {
                snake.push('_');
            }
            snake.extend(c.to_lowercase());
        } else {
            snake.push(c);
        }
    }
    snake
}

fn valid(name: &str) -> bool {
    let mut chars = name.chars();
    chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}

fn write(
    console: &mut Console,
    kind: &str,
    directory: &str,
    name: &str,
    contents: String,
    force: bool,
) -> laravel::Result<()> {
    if !valid(name) {
        return Err(ExcelError::Command(format!(
            "The {} name [{name}] isn't a valid Rust type name.",
            kind.to_lowercase()
        ))
        .into());
    }
    let path: PathBuf = laravel::config()
        .app
        .base_path
        .join("src")
        .join(directory)
        .join(format!("{}.rs", snake(name)));
    if path.exists() && !force {
        return Err(ExcelError::Command(format!("{kind} already exists.")).into());
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(&path, contents)?;
    console.success(format!("{kind} [{}] created successfully.", path.display()));
    console.info(format!("Declare it in src/{directory}/mod.rs: `mod {};`", snake(name)));
    Ok(())
}

/// The model's type and its module path, such as `User` and `crate::models::User`.
fn model_path(model: &str) -> (String, String) {
    let model = model.replace(['\\', '/'], "::");
    let name = model.rsplit("::").next().unwrap_or(&model).to_owned();
    let path = if model.contains("::") {
        model.clone()
    } else {
        format!("crate::models::{model}")
    };
    (name, path)
}

/// Create a new export.
#[command("make:export")]
pub async fn make_export(
    /// The name of the export, such as `UsersExport`.
    name: String,
    /// Generate an export for the given model.
    #[arg(short, long)]
    model: Option<String>,
    /// Generate an export for a query.
    #[arg(long)]
    query: bool,
    /// Overwrite the export if it exists.
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> laravel::Result<()> {
    let contents = match (&model, query) {
        (Some(model), true) => {
            let (model, path) = model_path(model);
            format!(
                "use laravel_excel::concerns::*;\n\nuse {path};\n\npub struct {name};\n\nimpl FromQuery for {name} {{\n    type Model = {model};\n\n    fn query(&self) -> laravel::db::Builder<{model}> {{\n        {model}::query()\n    }}\n}}\n\nlaravel_excel::export!({name}: FromQuery);\n"
            )
        }
        (Some(model), false) => {
            let (model, path) = model_path(model);
            format!(
                "use laravel_excel::concerns::*;\n\nuse {path};\n\npub struct {name};\n\nimpl FromCollection for {name} {{\n    type Row = {model};\n\n    async fn collection(&self) -> laravel::Result<Vec<{model}>> {{\n        {model}::query().get().await\n    }}\n}}\n\nlaravel_excel::export!({name}: FromCollection);\n"
            )
        }
        (None, true) => format!(
            "use laravel_excel::concerns::*;\n\npub struct {name};\n\nimpl FromQuery for {name} {{\n    // The model the query returns, such as `crate::models::User`.\n    type Model = ();\n\n    fn query(&self) -> laravel::db::Builder<Self::Model> {{\n        todo!()\n    }}\n}}\n\nlaravel_excel::export!({name}: FromQuery);\n"
        ),
        (None, false) => format!(
            "use laravel_excel::concerns::*;\n\npub struct {name};\n\nimpl FromCollection for {name} {{\n    type Row = Vec<Value>;\n\n    async fn collection(&self) -> laravel::Result<Vec<Vec<Value>>> {{\n        todo!()\n    }}\n}}\n\nlaravel_excel::export!({name}: FromCollection);\n"
        ),
    };
    write(console, "Export", "exports", &name, contents, force)
}

/// Create a new import.
#[command("make:import")]
pub async fn make_import(
    /// The name of the import, such as `UsersImport`.
    name: String,
    /// Generate an import for the given model.
    #[arg(short, long)]
    model: Option<String>,
    /// Overwrite the import if it exists.
    #[arg(long)]
    force: bool,
    console: &mut Console,
) -> laravel::Result<()> {
    let contents = match &model {
        Some(model) => {
            let (model, path) = model_path(model);
            format!(
                "use laravel::model::{{IntoRow, row}};\nuse laravel_excel::concerns::*;\n\nuse {path};\n\npub struct {name};\n\nimpl ToModel for {name} {{\n    type Model = {model};\n\n    fn model(&self, row: Row) -> impl IntoIterator<Item = impl IntoRow<{model}>> {{\n        Some(row!({model} {{\n            //\n        }}))\n    }}\n}}\n\nlaravel_excel::import!({name}: ToModel);\n"
            )
        }
        None => format!(
            "use laravel_excel::concerns::*;\n\npub struct {name};\n\nimpl ToCollection for {name} {{\n    async fn collection(&self, rows: Vec<Row>) -> laravel::Result<()> {{\n        //\n        Ok(())\n    }}\n}}\n\nlaravel_excel::import!({name}: ToCollection);\n"
        ),
    };
    write(console, "Import", "imports", &name, contents, force)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn names_become_file_names() {
        assert_eq!(snake("UsersExport"), "users_export");
        assert!(valid("UsersExport"));
        assert!(!valid("Users-Export"));
        assert_eq!(
            model_path("User"),
            ("User".to_owned(), "crate::models::User".to_owned())
        );
        assert_eq!(
            model_path("crate::models::admin::User"),
            ("User".to_owned(), "crate::models::admin::User".to_owned())
        );
    }
}