wakapi 0.3.1

Wakatime API client
Documentation
//! This module provides the `WakatimeConfig` struct to read the Wakatime INI config file.
//! Only the most basic part of the config file is implemented
//! (settings/api_key, settings/debug, settings/api_url).
//!
//! This module should be used with `WakapiClient` (not implemented yet).
use std::path::Path;

use directories::UserDirs;
use serde::Deserialize;

use crate::error::WakapiError;

/// Wakatime INI config file.
///
/// Only the most basic part of the config file is implemented
/// (settings/api_key, settings/debug, settings/api_url).
///
/// Full content :
/// <https://github.com/wakatime/wakatime-cli/blob/develop/USAGE.md#ini-config-file>
#[derive(Deserialize)]
pub struct WakatimeConfig {
    pub settings: Option<ConfigSettings>,
}

#[derive(Deserialize)]
pub struct ConfigSettings {
    pub debug: Option<bool>,
    pub api_key: Option<String>,
    pub api_url: Option<String>,
}

impl WakatimeConfig {
    /// Read the config file from the given location.
    /// If no location is given, the default location is $WAKATIME_HOME/.wakatime.cfg
    /// with $WAKATIME_HOME = user home directory by default.
    pub fn read(location: Option<String>) -> Result<Self, WakapiError> {
        // Get location : $WAKATIME_HOME/.wakatime.cfg, with $WAKATIME_HOME = $HOME
        let path = match location {
            Some(location) => Path::new(&location).join(".wakatime.cfg"),
            None => match std::env::var("WAKATIME_HOME") {
                Ok(home) => Path::new(&home).join(".wakatime.cfg"),
                Err(_) => match UserDirs::new() {
                    Some(user_dirs) => user_dirs.home_dir().join(".wakatime.cfg"),
                    None => {
                        return Err(WakapiError::HomeDirNotFound);
                    }
                },
            },
        };
        // Use path to read the file with serde_toml
        let content = std::fs::read_to_string(path)?;
        let config: WakatimeConfig = toml::from_str(&content)?;
        Ok(config)
    }
}