couchdb-orm 0.1.6

couchdb-orm Copyright (C) 2020-2023 OpenToolAdd This program comes with ABSOLUTELY NO WARRANTY; This is free software, and you are welcome to redistribute it under certain conditions; type `show-license' for details. A CLI ORM to manage some Databases operations like migration, schema creation, etc.... For the moment it only handle CouchDB.
Documentation
// Copyright (C) 2020-2023  OpenToolAdd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// contact: contact@tool-add.com

use crate::cli::args::actions::register::db::register_db;
use chrono::Utc;
use couchdb_orm::utils::{get_dir_entries, init_meta_dir, main_content};
use dialoguer::{theme::ColorfulTheme, Select};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::str::FromStr;
use thiserror::Error;

fn write_main_file(rootdir: &PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let main_file_name: PathBuf =
        PathBuf::from_str(&format!("{}/_meta/src/main.rs", rootdir.to_str().unwrap())).unwrap();

    let main_content: String = main_content(rootdir)?;

    // println!("{:#?}", main_content);
    fs::write(main_file_name, main_content)?;

    Ok(())
}

fn write_seed_db_mod(
    db_path: &str,
    filename: &PathBuf,
    rootdir: &PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    // println!("{}", db_path);
    let seeds_path: PathBuf = PathBuf::from_str(&db_path)?;
    let mod_file_name: PathBuf = PathBuf::from_str(&format!("{}/mod.rs", db_path)).unwrap();

    let available_seeds: Vec<PathBuf> = fs::read_dir(&seeds_path)?
        .map(|res| res.map(|e| e.path()))
        .collect::<Result<Vec<PathBuf>, std::io::Error>>()?;
    let available_seeds: Vec<&PathBuf> = available_seeds
        .iter()
        .filter(|e| e.file_name().unwrap() != "mod.rs")
        .collect();

    let available_seeds_mod_filenames: String = available_seeds
        .iter()
        .map(|e| {
            let mut s = e
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .to_string()
                .replace(".rs", ";");
            s.push_str("\n");
            format!("pub mod {}", s)
        })
        .collect();
    let mut available_seeds_enum: Vec<String> = available_seeds
        .iter()
        .map(|e| {
            e.file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .to_string()
                .replace(".rs", "")
        })
        .collect();
    let filename_str: String = format!(
        r#"{}"#,
        filename
            .file_name()
            .unwrap()
            .to_str()
            .unwrap()
            .to_string()
            .replace(".rs", "")
    );
    if !available_seeds_enum.contains(&filename_str) {
        available_seeds_enum.push(filename_str.clone())
    }
    let available_seeds_enum: String = available_seeds_enum.join(",\n");
    let mut available_seeds_list: Vec<String> = available_seeds
        .iter()
        .map(|e| {
            let s = e
                .file_name()
                .unwrap()
                .to_str()
                .unwrap()
                .to_string()
                .replace(".rs", "");
            let s = format!(r#""{}""#, s);
            s
        })
        .collect();
    let filename_str: String = format!(r#""{}""#, &filename_str);

    if !available_seeds_list.contains(&filename_str) {
        available_seeds_list.push(filename_str.clone());
    }
    let available_seeds_list: String = available_seeds_list.join(",\n");
    let available_seeds_content: String = format!(
        include_str!("../../../../../../../static/templates/available_seeds.tpl"),
        available_seeds_mod_filenames, available_seeds_enum, available_seeds_list
    );
    // println!("{:?}", available_migration_content);
    fs::write(mod_file_name, available_seeds_content)?;

    write_main_file(rootdir)?;
    Ok(())
}

fn write_seed_file(
    db_path: &str,
    db_name: &str,
    name: &str,
    filename: &String,
    override_version: bool,
    rootdir: &PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    let src_name: String = filename.replace(".rs", "");
    let timestamp: i64 = Utc::now().timestamp();
    let file_content: String = format!(
        include_str!("../../../../../../../static/templates/seed_file.tpl"),
        db_name, src_name, db_name, db_name, db_name
    );
    let file_name: PathBuf =
        PathBuf::from_str(&format!("{}/seed_{}_{}.rs", db_path, timestamp, name,)).unwrap();

    if !file_name.exists() || override_version {
        fs::write(&file_name, &file_content)?;
    }

    write_seed_db_mod(db_path, &file_name, rootdir)?;
    Ok(())
}

#[derive(Debug, Error, Serialize, Deserialize, Clone)]
#[error("RegisterSeedError: {0}")]
struct RegisterSeedError(String);

pub fn register_seed(
    db_name: String,
    name: String,
    override_version: bool,
    rootdir: &PathBuf,
) -> Result<(), Box<dyn std::error::Error>> {
    init_meta_dir(&rootdir)?;
    let db_path: PathBuf = PathBuf::from_str(&format!(
        "{}/_meta/src/seeds/{}",
        rootdir.to_str().unwrap(),
        db_name
    ))?;
    let schemas_path: PathBuf = PathBuf::from_str(&format!(
        "{}/_meta/src/schemas/{}",
        rootdir.to_str().unwrap(),
        db_name
    ))?;

    register_db(&db_name, rootdir)?;

    let schemas_available: Vec<PathBuf> = get_dir_entries(&schemas_path)?;
    let schemas_available: Vec<&str> = schemas_available
        .iter()
        .filter(|res| !res.to_str().unwrap().contains(&"mod.rs"))
        .map(|s| s.to_str().unwrap())
        .collect();

    if schemas_available.len() > 0 {
        let selection: usize = Select::with_theme(&ColorfulTheme::default())
            .with_prompt("Select a schema to create a seed: ")
            .items(&schemas_available)
            .interact()?;

        let selection: PathBuf = PathBuf::from_str(schemas_available[selection]).unwrap();
        let filename: String = selection
            .file_name()
            .unwrap()
            .to_os_string()
            .into_string()
            .unwrap();

        // println!("{:?}", filenames);
        write_seed_file(
            &db_path.to_str().unwrap(),
            &db_name,
            &name,
            &filename,
            override_version,
            rootdir,
        )
    } else {
        Err(Box::new(RegisterSeedError(format!(
            "No schemas registered in {}",
            schemas_path.to_str().unwrap()
        ))))
    }
}

#[cfg(test)]
mod test {}