takoyaki_core 1.2.0

Core package to build plugins for takoyaki
Documentation
use std::path::PathBuf;

/// All the paths are stored and constructed here globally
pub struct Paths {}

impl Paths {
    /// Returns the path where config exists. The config path should be one among these:
    /// * ~/.takoyaki.yaml
    /// * ~/.config/takoyaki.yaml
    /// * ~/.config/takoyaki/config.yaml
    ///
    /// If the config is not found in any of them, it creates a new config file at ~/.takoyaki.yaml
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use takoyaki_core::Paths;
    /// let config_dir = Paths::get_config_path();
    /// ```
    pub fn get_config_path() -> PathBuf {
        // Some constants to begin with
        let home_dir = dirs::home_dir().unwrap(); // Hoping that the config directory exists
        let config_dir = dirs::config_dir().unwrap_or(home_dir.join(".config"));

        // List of directories that will be search
        let directories = [
            home_dir.join(".takoyaki.yaml"),
            config_dir.join("takoyaki.yaml"),
            config_dir.join("takoyaki").join("config.yaml"),
        ];

        // Check which exists
        let existing_dir = directories.iter().find(|d| d.exists());

        // Create fallback config path
        let fallback_config = home_dir.join(".takoyaki.yaml");

        // Check if existing directory is empty (No where the config is found)
        if existing_dir.is_none() {
            // Create the fallback config
            std::fs::File::create(&fallback_config).expect("Unable to create a file");
        }

        // Return either the found one or the fallback one
        existing_dir.unwrap_or(&fallback_config).to_path_buf()
    }

    /// Returns the path where the cache for a specific plugin is stored
    /// The cache is basically stored at $USER_CACHE_DIR/takoyaki/<plugin_name>/cache.json
    ///
    /// Note: This does not check if the cache exists or not. Use the `Cache` struct instead. This will just return the path
    ///
    /// # Examples
    ///
    /// ```
    /// use takoyaki_core::Paths;
    ///
    /// let plugin_name = "github";
    ///
    /// let expected = dirs::cache_dir().unwrap().join("takoyaki").join(plugin_name).join("cache.json");
    ///
    /// let returned_cache_path = Paths::get_cache_path("github");
    ///
    /// assert_eq!(returned_cache_path, expected);
    /// ```
    pub fn get_cache_path(name: &str) -> PathBuf {
        // Create a fallback cache path
        let cache_dir_fallback = dirs::home_dir().unwrap().join(".cache");

        // Get the system based cache path or use the fallback one
        let cache_dir = dirs::cache_dir()
            .unwrap_or(cache_dir_fallback)
            .join("takoyaki");

        // Return the cache path
        cache_dir.join(name).join("cache.json")
    }
}