aboutsummaryrefslogtreecommitdiffstats
path: root/src/run/var.rs
blob: 0e64ad7a36d8ef7f09821156236731c9e79cf204 (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
use std::collections::{HashMap, HashSet};

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

pub struct Vars {
    simple: HashMap<BString, BString>,
    magic: HashMap<BString, fn() -> BString>,
    all: 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() {
            simple.insert(var.into_encoded_bytes(), val.into_encoded_bytes());
        }
        let all = simple
            .keys()
            .cloned()
            .chain(magic.keys().cloned())
            .collect();
        Self { simple, magic, all }
    }

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

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

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

        None
    }

    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 {
        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'],
        };
        let magic = map! {
            b"CWD_PRETTY" => crate::pretty_cwd as _
        };
        Self::new(simple, magic)
    }
}