learnwy_bin_utils 0.2.0

self use
use crate::log_level::LogLevel;
use dirs::{data_dir, home_dir};
use crate::path_ext::PathExt;

#[derive(clap::Parser, Debug)]
pub struct Config {
    /// The root directory of fnm installations.
    #[clap(long, global = true, hide_env_values = true)]
    pub base_dir: Option<std::path::PathBuf>,

    /// The log level of fnm commands
    #[clap(long, default_value = "info", global = true, hide_env_values = true, possible_values = LogLevel::possible_values())]
    log_level: LogLevel,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            base_dir: None,
            log_level: LogLevel::Info,
        }
    }
}

impl Config {
    pub fn log_level(&self) -> &LogLevel {
        &self.log_level
    }

    pub fn base_dir_with_default(&self) -> std::path::PathBuf {
        let user_pref = self.base_dir.clone();
        if let Some(dir) = user_pref {
            return dir;
        }

        let legacy = home_dir()
            .map(|dir| dir.join(".learnwy"))
            .filter(|dir| dir.exists());

        let modern = data_dir().map(|dir| dir.join("learnwy"));

        if let Some(dir) = legacy {
            return dir;
        }

        modern
            .expect("Can't get data directory")
            .ensure_exists_silently()
    }

    pub fn data_dir(&self) -> std::path::PathBuf {
        self.base_dir_with_default()
            .join("data")
            .ensure_exists_silently()
    }


    #[cfg(test)]
    pub fn with_base_dir(mut self, base_dir: Option<std::path::PathBuf>) -> Self {
        self.base_dir = base_dir;
        self
    }
}