laractions 0.1.0

Actions for Laravel Rust: encapsulate business logic in classes that run now or on the queue.
Documentation
use std::fs;
use std::path::{Path, PathBuf};

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

use crate::registry;
use crate::support::{pascal, snake};

const ACTION_STUB: &str = include_str!("stubs/action.stub");
const MODEL_ACTION_STUB: &str = include_str!("stubs/model-action.stub");

/// An action file that [`generate`] wrote.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Generated {
    /// The file, relative to the application's base path.
    pub path: PathBuf,
    /// The struct in it.
    pub class: String,
}

/// Why [`generate`] wrote nothing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GenerateError {
    /// The name has nothing to name a struct after.
    EmptyName,
    /// The file is already there.
    Exists(PathBuf),
    /// The disk refused.
    Io(String),
}

/// Write an action from its stub, the way `make:action` does.
///
/// The name is a struct name, `SendEmail` or `send_email`, optionally behind folders:
/// `Billing/SendEmail` goes to `src/actions/billing/send_email.rs`. With a model, the action goes
/// to a folder named after it, `src/actions/user/send_email.rs`, as PHP puts it in `Actions\User`.
/// The new module is declared in the `mod.rs` beside it.
///
/// # Errors
///
/// Fails when the name is empty, the file exists, or the disk refuses.
pub fn generate(base: &Path, name: &str, model: Option<&str>) -> Result<Generated, GenerateError> {
    let segments: Vec<&str> = name
        .split(['/', '\\'])
        .flat_map(|segment| segment.split("::"))
        .filter(|segment| !segment.is_empty())
        .collect();
    let Some((last, folders)) = segments.split_last() else {
        return Err(GenerateError::EmptyName);
    };

    let class = pascal(last);
    let file = snake(last);

    let (stub, directories) = match model {
        Some(model) => {
            let model = model.trim_matches('\\').trim_matches(':');
            let name = model
                .rsplit("::")
                .next()
                .unwrap_or(model)
                .rsplit('\\')
                .next()
                .unwrap_or(model);
            let path = if model.contains("::") || model.contains('\\') {
                model.replace('\\', "::")
            } else {
                format!("crate::models::{model}")
            };

            let stub = MODEL_ACTION_STUB
                .replace("{{ class }}", &class)
                .replace("{{ modelFullName }}", &path)
                .replace("{{ modelName }}", name)
                .replace("{{ modelVariable }}", &snake(name));

            (stub, vec![snake(name)])
        }
        None => (
            ACTION_STUB.replace("{{ class }}", &class),
            folders.iter().map(|folder| snake(folder)).collect(),
        ),
    };

    let mut relative = PathBuf::from("src/actions");

    for directory in &directories {
        relative.push(directory);
    }

    let directory = base.join(&relative);
    let path = directory.join(format!("{file}.rs"));

    if path.exists() {
        return Err(GenerateError::Exists(relative.join(format!("{file}.rs"))));
    }

    let io = |error: std::io::Error| GenerateError::Io(error.to_string());

    fs::create_dir_all(&directory).map_err(io)?;
    fs::write(&path, stub).map_err(io)?;

    declare(&base.join("src/actions"), &directories, &file).map_err(io)?;

    Ok(Generated {
        path: relative.join(format!("{file}.rs")),
        class,
    })
}

/// Declare a module in its folder's `mod.rs`, and that folder in the one above.
fn declare(root: &Path, directories: &[String], file: &str) -> std::io::Result<()> {
    let mut chain: Vec<(PathBuf, String)> = Vec::new();
    let mut directory = root.to_path_buf();

    for name in directories {
        chain.push((directory.clone(), name.clone()));
        directory.push(name);
    }

    chain.push((directory, file.to_owned()));

    for (directory, module) in chain {
        let mod_file = directory.join("mod.rs");
        let line = format!("pub mod {module};");
        let current = fs::read_to_string(&mod_file).unwrap_or_default();

        if current.lines().any(|existing| existing.trim() == line) {
            continue;
        }

        fs::create_dir_all(&directory)?;

        let mut next = current;

        if !next.is_empty() && !next.ends_with('\n') {
            next.push('\n');
        }

        next.push_str(&line);
        next.push('\n');

        fs::write(mod_file, next)?;
    }

    Ok(())
}

/// Create a new action.
#[command("make:action")]
pub async fn make_action(
    /// The name of the action, such as `SendEmail`.
    name: String,
    /// Create a model action, bound to this model.
    #[arg(long)]
    model: Option<String>,
    console: &mut Console,
) -> laravel::Result<u8> {
    let base = laravel::config().app.base_path.clone();

    match generate(&base, &name, model.as_deref()) {
        Ok(generated) => {
            console.success(format!("Action [{}] created successfully.", generated.path.display()));

            let declared = fs::read_to_string(base.join("src/lib.rs"))
                .map(|lib| lib.contains("mod actions"))
                .unwrap_or(true);

            if !declared {
                console.line("Declare the module in src/lib.rs: pub mod actions;");
            }

            Ok(0)
        }
        Err(GenerateError::Exists(path)) => {
            console.error(format!("Action already exists. [{}]", path.display()));

            Ok(1)
        }
        Err(GenerateError::EmptyName) => {
            console.error("The action needs a name.");

            Ok(1)
        }
        Err(GenerateError::Io(error)) => {
            console.error(format!("Could not write the action: {error}"));

            Ok(1)
        }
    }
}

/// List all registered actions.
#[command("list:actions")]
pub async fn list_actions(console: &mut Console) -> laravel::Result<()> {
    let actions = registry::all();

    if actions.is_empty() {
        console.warn("No action files found.");

        return Ok(());
    }

    console.info("Available Actions:");

    for registration in actions {
        console.line(format!("- {}", registration.name()));
    }

    Ok(())
}