aboutsummaryrefslogtreecommitdiffstats
path: root/src/run/var/mod.rs
blob: 1ccc1951502f85e63a45a11f3a2a317541e621cf (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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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;

mod watch;
pub use watch::WatchId;
use watch::{WatchState, WeakWatchId};

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

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,
            watches: HashMap::new(),
            watched: HashMap::new(),
        }
    }

    pub fn watch(&mut self, vars: Vec<BString>) -> WatchId {
        let watch = WatchId::new();
        let special = vars.iter().any(|v| self.magic.contains_key(v));
        self.watches.insert(
            watch.weak(),
            WatchState {
                special,
                dirty: true,
            },
        );
        for var in vars {
            self.watched
                .entry(var)
                .or_insert_with(Vec::new)
                .push(watch.weak());
        }
        watch
    }

    pub fn peek_dirty(&self, watch_set: &WatchId) -> bool {
        if let Some(w) = self.watches.get(&watch_set.weak()) {
            w.dirty || w.special
        } else {
            false
        }
    }

    pub fn pop_dirty(&mut self, watch_set: &WatchId) -> bool {
        if let Some(w) = self.watches.get_mut(&watch_set.weak()) {
            let dirty = w.dirty || w.special;
            w.dirty = false;
            dirty
        } else {
            false
        }
    }

    pub fn set(&mut self, var: BString, val: BString) {
        if let Some(watchers) = self.watched.get(&var) {
            let mut dead = false;
            for watcher in watchers {
                if watcher.is_dead() {
                    dead = true;
                    self.watches.remove(watcher);
                } else {
                    self.watches.get_mut(watcher).unwrap().dirty = true;
                }
            }

            if dead {
                self.watched.get_mut(&var).unwrap().retain(|w| !w.is_dead());
            }
        }

        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()
}