rust-utils 0.16.0

Various utility routines used in the rust programs I have written
Documentation
//! Basic config API
//!
//! Contains a special trait that allows a type to have an associated config file

use serde::{Deserialize, Serialize};
use std::{
    env, fs,
    io::Result as IoResult,
    path::PathBuf
};
use ron::ser::PrettyConfig;

/// The type of config file we are using
#[derive(Clone, Copy)]
pub enum ConfigType {
    Toml,
    Ron
}

/// The `Config` trait allows a type to have an associated config file
///
/// Requires the [`Default`], [`Serialize`], and [`Deserialize`] traits (can be derived) to be implemented
pub trait Config: Serialize + Default + for <'de> Deserialize<'de> {
    /// This constant must be set to the file name of the config file
    const FILE_NAME: &'static str;

    /// This constant is the type of config
    ///
    /// Defaults to TOML
    const TYPE: ConfigType = ConfigType::Toml;

    /// Returns the save directory of the config file.
    ///
    /// This method must be defined
    fn get_save_dir() -> PathBuf;

    /// Returns the full path of the config file
    fn get_full_path() -> PathBuf {
        Self::get_save_dir().join(Self::FILE_NAME)
    }

    /// Load from the config file
    ///
    /// Returns the defaults if the file does not exist or is corrupted
    ///
    /// Panics if the config directory cannot be created
    #[track_caller]
    fn load() -> Self {
        let file_str = if let Ok(file) = fs::read_to_string(Self::get_full_path()) {
            file
        }
        else {
            let config = Self::default();
            config.save().expect("Unable to load config!");
            return config;
        };

        match Self::TYPE {
            ConfigType::Toml => {
                if let Ok(cfg) = toml::from_str(&file_str) {
                    cfg
                }
                else { Self::default() }
            }

            ConfigType::Ron => {
                if let Ok(cfg) = ron::from_str(&file_str) {
                    cfg
                }
                else { Self::default() }
            }
        }
    }

    /// Save to the config file
    ///
    /// It is recommended to call this in every method that has &mut self as an argument!
    #[track_caller]
    fn save(&self) -> IoResult<()> {
        let save_str = match Self::TYPE {
            ConfigType::Toml => toml::to_string_pretty(&self).unwrap(),
            ConfigType::Ron => {
                let cfg = PrettyConfig::default();
                ron::ser::to_string_pretty(&self, cfg).unwrap()
            }
        };

        fs::create_dir_all(Self::get_save_dir())?;
        fs::write(Self::get_full_path(), save_str)
    }

    /// Helper function to get the user's config root folder (normally `$HOME/.config` on most unix-like systems)
    ///
    /// Panics if your user does not have a home folder
    #[track_caller]
    fn get_config_root() -> PathBuf {
        if let Ok(xdg_config_home) = env::var("XDG_CONFIG_HOME") {
            xdg_config_home.into()
        }
        else {
            PathBuf::from(
                env::var("HOME").expect("Where is your home folder?!")
            )
                .join(".config")
        }
    }
}