aboutsummaryrefslogtreecommitdiffstats
path: root/src/run/var.rs
blob: 8e22f5c327c28e86fef8081f19ca59acad442090 (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::os::unix::ffi::OsStrExt;
use std::sync::LazyLock;
use std::time::Instant;

use crate::BString;
use crate::bstr;

pub struct Vars {
    simple: HashMap<BString, BString>,
    magic: HashMap<BString, fn() -> BString>,
    all: HashSet<BString>,
    export: HashSet<BString>,
}

impl Vars {
    fn new(
        mut simple: HashMap<BString, BString>,
        magic: HashMap<BString, fn() -> BString>,
    ) -> Self {
        for (var, val) in std::env::vars_os() {
            // explicitly added variables get priority.
            if !simple.contains_key(var.as_bytes()) {
                simple.insert(var.into_encoded_bytes(), val.into_encoded_bytes());
            }
        }
        let all = simple
            .keys()
            .cloned()
            .chain(magic.keys().cloned())
            .collect();
        let export = std::env::vars_os()
            .map(|x| x.0.into_encoded_bytes())
            .collect();
        Self {
            simple,
            magic,
            all,
            export,
        }
    }

    pub fn set(&mut self, var: BString, val: BString) {
        self.simple.insert(var.clone(), val);
        self.all.insert(var);
    }

    pub fn lookup<'a>(&'a self, var: &bstr) -> Option<Cow<'a, bstr>> {
        if let Some(fun) = self.magic.get(var) {
            return Some(Cow::Owned(fun()));
        }

        if let Some(val) = self.simple.get(var) {
            return Some(Cow::Borrowed(val));
        }

        None
    }

    pub fn allow_export(&mut self, var: &bstr, allow: bool) {
        if allow {
            self.export.insert(var.to_vec());
        } else {
            self.export.remove(var);
        }
    }

    pub fn export<'a>(&'a self) -> HashMap<&'a bstr, Cow<'a, bstr>> {
        self.export
            .iter()
            .filter_map(|var| {
                let val = self.lookup(var)?;
                Some((var.as_ref(), val))
            })
            .collect()
    }

    pub fn vars(&self) -> &HashSet<BString> {
        &self.all
    }
}

macro_rules! map {
    ($($key:expr => $val:expr),* $(,)?) => {{
        let mut map = HashMap::<BString, _, _>::new();
        $(map.insert($key.into(), $val);)*
        map
    }};
}

impl Default for Vars {
    fn default() -> Self {
        use crate::basedir::xdg;

        let simple = map! {
            b"PISH_VERSION" => crate::consts::PISH_VERSION.as_bytes().to_vec(),
            b"PISH_COMMIT" => crate::consts::PISH_COMMIT.as_bytes().to_vec(),
            b"PISH_DIRTY" => vec![crate::consts::PISH_DIRTY as u8 + b'0'],
            xdg::DATA_HOME => xdg::data_home().as_os_str().as_bytes().to_vec(),
            xdg::STATE_HOME => xdg::state_home().as_os_str().as_bytes().to_vec(),
            xdg::CONFIG_HOME => xdg::config_home().as_os_str().as_bytes().to_vec(),
        };

        let magic = map! {
            b"CWD_PRETTY" => crate::pretty_cwd as _,
            b"SECONDS" => seconds_since_startup as _,
        };

        // call it once such that lazylock gets initialized
        seconds_since_startup();

        let mut this = Self::new(simple.clone(), magic);
        for var in simple.keys() {
            if var.starts_with(b"XDG_") {
                this.allow_export(var, true);
            }
        }
        this
    }
}

static START: LazyLock<Instant> = LazyLock::new(Instant::now);

fn seconds_since_startup() -> BString {
    format!("{}", START.elapsed().as_secs_f64() as u64).into_bytes()
}