espforge 0.1.20

A scaffolding++ project generator for ESP32 projects
Documentation
use anyhow::{Context, Result, anyhow};
use espforge_codegen::{
    esp_generate, generate_components_source, generate_entry_point_source, generate_lib_source,
};
use espforge_configuration::EspforgeConfiguration;
use std::fs;
use std::path::Path;

pub fn generate_scaffold(model: &EspforgeConfiguration, target_dir: &Path) -> Result<()> {
    esp_generate(
        model.get_name(),
        model.get_chip(),
        model.is_embassy(),
        model.has_wifi(),
        target_dir,
    )
}

/// Generates the generated.rs file containing component definitions
pub fn generate_component_code(src_dir: &Path, model: &EspforgeConfiguration) -> Result<()> {
    let components_src = generate_components_source(model)?;
    fs::write(src_dir.join("generated.rs"), components_src)
        .context("Failed to write src/generated.rs")?;
    Ok(())
}

/// Creates the lib.rs file that exports the project structure
pub fn setup_library_structure(src_dir: &Path, additional_modules: &[String]) -> Result<()> {
    // Delegate content generation to the espforge_codegen crate
    let content = generate_lib_source(additional_modules)?;

    // if !additional_modules.is_empty() {
    //     let mut mod_declarations = String::new();
    //     for module in additional_modules {
    //         mod_declarations.push_str(&format!("pub mod {};\n", module));
    //     }
    //     content = format!("{}\n{}", mod_declarations, content);
    // }

    fs::write(src_dir.join("lib.rs"), content).context("Failed to write src/lib.rs")?;
    Ok(())
}

/// Renders and writes the main entry point (main.rs)
pub fn generate_entry_point(src_dir: &Path, model: &EspforgeConfiguration) -> Result<()> {
    let content = generate_entry_point_source(model)
        .map_err(|e| anyhow!("Failed to render main.rs: {}", e))?;

    let path = src_dir.join("bin/main.rs");
    if let Some(p) = path.parent() {
        fs::create_dir_all(p)?;
    }
    fs::write(&path, content).context("Failed to write generated main.rs")?;
    Ok(())
}