auric 0.1.5

CLI for the Ember-inspired Auric SPA framework
use clap::Parser;
use std::path::PathBuf;
use std::{fs, path::Path};

#[derive(Debug, Parser)]
pub struct Opts {
    /// Model Name
    #[arg(value_name = "name")]
    pub name: String,
}

pub async fn run(name: String) -> anyhow::Result<()> {
    // Delete model module file
    let models_dir = PathBuf::new().join("src").join("models");
    let (modulename, filename, dir) = {
        let s = change_case::snake_case(&name).replace("_", "/");
        let filename = format!("{s}.rs");
        let modulename = match s.rfind("/") {
            None => s,
            Some(n) => s[n + 1..].to_owned(),
        };
        let dir = models_dir
            .join(&filename)
            .parent()
            .expect("Expected to get parent dir")
            .to_owned();
        (modulename, filename, dir)
    };
    let relative_path = models_dir.join(filename);
    let root_dir = Path::new(".");
    let path = root_dir.join(&relative_path);
    if path.exists() {
        fs::remove_file(&path)?;
        eprintln!("deleted {}", relative_path.display());
    }

    // Remove reference to it from the parent module
    let relative_path = dir.join("mod.rs");
    let path = root_dir.join(&relative_path);
    let code = fs::read_to_string(&path)?;
    let new_code = code.replace(&format!("pub mod {modulename};\n"), "");
    if code != new_code {
        fs::write(&path, new_code)?;
        eprintln!("updated {}", relative_path.display());
    }

    Ok(())
}