aboutsummaryrefslogtreecommitdiffstats
path: root/src/basedir.rs
blob: 3589b71bda6f0ca4230f10ab7684106d543579d3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use std::{env, path::PathBuf};

const NAME: &str = env!("CARGO_PKG_NAME");

pub fn home() -> PathBuf {
    if let Ok(home) = env::var("HOME") {
        PathBuf::from(home)
    } else {
        PathBuf::new()
    }
}

/// Choosing directories according to https://specifications.freedesktop.org/basedir/latest/#variables
pub mod xdg {
    use super::*;

    pub const DATA_HOME: &str = "XDG_DATA_HOME";

    /// $XDG_DATA_HOME defines the base directory relative to which user-specific data files should be stored.
    /// If $XDG_DATA_HOME is either not set or empty, a default equal to $HOME/.local/share should be used.
    pub fn data_home() -> PathBuf {
        if let Some(dir) = env::var_os(DATA_HOME) {
            PathBuf::from(dir)
        } else {
            home().join(".local/share")
        }
    }

    pub const CONFIG_HOME: &str = "XDG_CONFIG_HOME";

    /// $XDG_CONFIG_HOME defines the base directory relative to which user-specific configuration files should be stored.
    /// If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.
    pub fn config_home() -> PathBuf {
        if let Some(dir) = env::var_os(CONFIG_HOME) {
            PathBuf::from(dir)
        } else {
            home().join(".config")
        }
    }

    pub const STATE_HOME: &str = "XDG_STATE_HOME";

    /// $XDG_STATE_HOME defines the base directory relative to which user-specific state files should be stored.
    /// If $XDG_STATE_HOME is either not set or empty, a default equal to $HOME/.local/state should be used.
    pub fn state_home() -> PathBuf {
        if let Some(dir) = env::var_os(STATE_HOME) {
            PathBuf::from(dir)
        } else {
            home().join(".local/state")
        }
    }
}

pub fn data_dir() -> PathBuf {
    xdg::data_home().join(NAME)
}

pub fn config_dir() -> PathBuf {
    xdg::config_home().join(NAME)
}

pub fn state_dir() -> PathBuf {
    xdg::state_home().join(NAME)
}