Skip to main content

byob_exec/env/
choices.rs

1//! What the user decided per workspace: load its project environment or not, run its
2//! commands in a container or not. A workspace is identified by its canonical path.
3//!
4//! Answers a person gave are saved in `<data>/envs/workspaces.json` (read on every lookup,
5//! so another byob process or a hand edit is seen); answers the policy gave for them
6//! (`--auto-approve`) only last for this process, so a test run never decides for good.
7
8use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10use std::sync::{Mutex, PoisonError};
11
12use serde::{Deserialize, Serialize};
13
14use super::write_atomic;
15
16/// The decisions for one workspace (`None`: not decided, ask).
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Choice {
19    /// Load the workspace's own environment (flake.nix, pixi.toml, …).
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub project: Option<bool>,
22    /// Run its commands in a container.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub container: Option<bool>,
25}
26
27impl Choice {
28    fn overlay(self, over: Choice) -> Choice {
29        Choice { project: over.project.or(self.project), container: over.container.or(self.container) }
30    }
31
32    fn is_empty(self) -> bool {
33        self == Choice::default()
34    }
35}
36
37#[derive(Debug, Default, Serialize, Deserialize)]
38struct File {
39    #[serde(default)]
40    workspaces: BTreeMap<PathBuf, Choice>,
41}
42
43/// Which part of a [`Choice`] to change.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Field {
46    Project,
47    Container,
48}
49
50/// The saved and the session-only decisions.
51#[derive(Debug, Default)]
52pub struct Choices {
53    /// `None`: nothing is saved (no data folder).
54    file: Option<PathBuf>,
55    session: Mutex<BTreeMap<PathBuf, Choice>>,
56    /// Serializes read-modify-write of the file.
57    writing: Mutex<()>,
58}
59
60impl Choices {
61    pub fn new(file: Option<PathBuf>) -> Self {
62        Self { file, ..Self::default() }
63    }
64
65    fn load(&self) -> File {
66        self.file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
67    }
68
69    /// The decisions for `ws`: this session's, then the saved ones.
70    pub fn get(&self, ws: &Path) -> Choice {
71        let saved = self.load().workspaces.get(ws).copied().unwrap_or_default();
72        let session = self.session.lock().unwrap_or_else(PoisonError::into_inner).get(ws).copied().unwrap_or_default();
73        saved.overlay(session)
74    }
75
76    /// Decide `field` for `ws` (`None`: forget). `save`: a person decided, keep it;
77    /// otherwise it lasts for this process only. Forgetting clears both.
78    pub fn set(&self, ws: &Path, field: Field, value: Option<bool>, save: bool) -> Result<(), String> {
79        let put = |c: &mut Choice, v: Option<bool>| match field {
80            Field::Project => c.project = v,
81            Field::Container => c.container = v,
82        };
83        {
84            let mut session = self.session.lock().unwrap_or_else(PoisonError::into_inner);
85            let c = session.entry(ws.to_path_buf()).or_default();
86            put(c, if save && self.file.is_some() { None } else { value });
87            if c.is_empty() {
88                session.remove(ws);
89            }
90        }
91        if !save && value.is_some() {
92            return Ok(());
93        }
94        let Some(path) = &self.file else { return Ok(()) };
95        let _w = self.writing.lock().unwrap_or_else(PoisonError::into_inner);
96        let mut f = self.load();
97        let c = f.workspaces.entry(ws.to_path_buf()).or_default();
98        put(c, value);
99        if c.is_empty() {
100            f.workspaces.remove(ws);
101        }
102        write_atomic(path, serde_json::to_string_pretty(&f).unwrap_or_default().as_bytes())
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn saved_answers_persist_and_session_ones_do_not() {
112        let d = tempfile::tempdir().unwrap();
113        let file = d.path().join("envs/workspaces.json");
114        let ws = Path::new("/home/me/proj");
115        let c = Choices::new(Some(file.clone()));
116        assert_eq!(c.get(ws), Choice::default());
117        c.set(ws, Field::Project, Some(true), false).unwrap();
118        assert_eq!(c.get(ws).project, Some(true));
119        assert!(!file.exists(), "an automatic answer isn't saved");
120        assert_eq!(Choices::new(Some(file.clone())).get(ws).project, None);
121
122        c.set(ws, Field::Project, Some(false), true).unwrap();
123        c.set(ws, Field::Container, Some(true), true).unwrap();
124        let again = Choices::new(Some(file.clone()));
125        assert_eq!(again.get(ws), Choice { project: Some(false), container: Some(true) });
126        assert_eq!(again.get(Path::new("/other")), Choice::default());
127
128        again.set(ws, Field::Project, None, true).unwrap();
129        assert_eq!(Choices::new(Some(file.clone())).get(ws), Choice { project: None, container: Some(true) });
130        again.set(ws, Field::Container, None, true).unwrap();
131        assert!(!std::fs::read_to_string(&file).unwrap().contains("proj"), "forgotten workspaces are dropped");
132    }
133
134    #[test]
135    fn without_a_data_folder_everything_is_per_session() {
136        let c = Choices::new(None);
137        let ws = Path::new("/w");
138        c.set(ws, Field::Container, Some(true), true).unwrap();
139        assert_eq!(c.get(ws).container, Some(true), "kept for the session");
140        c.set(ws, Field::Container, None, true).unwrap();
141        assert_eq!(c.get(ws).container, None);
142    }
143}