Skip to main content

sapphire_framework_settings/
owner.rs

1//! The owner trait and the staged-edit types it validates.
2
3use std::collections::BTreeMap;
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use sapphire_bridge_api::settings::{Scope, SettingDef};
8
9use crate::Result;
10
11/// A process that has settings: it defines them and says where its scope files live.
12pub trait SettingsOwner: Send + Sync {
13    /// The settings this owner defines.
14    fn defs(&self) -> Vec<SettingDef>;
15
16    /// The `config.toml` holding `scope`'s settings. An error means the owner has no such
17    /// scope (the bridge has no workspace).
18    fn file(&self, scope: Scope) -> Result<PathBuf>;
19
20    /// The owner-only file holding the secret `key`.
21    fn secret_file(&self, key: &str) -> Result<PathBuf>;
22
23    /// Check the edited files as a whole, before anything is written.
24    fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>>;
25
26    /// A remark shown beside values that come from `scope`.
27    fn scope_note(&self, _scope: Scope) -> Option<String> {
28        None
29    }
30}
31
32/// The edited text of the files a batch touches, before it is written.
33#[derive(Clone, Debug, Default)]
34pub struct Staged {
35    /// Edited file text by path.
36    pub files: BTreeMap<PathBuf, String>,
37}
38
39impl Staged {
40    /// The edited text of a touched file; `None` means untouched (read it from disk).
41    pub fn text(&self, path: &Path) -> Option<&str> {
42        self.files.get(path).map(String::as_str)
43    }
44
45    /// The staged text if the file is touched, else the file on disk, else `None`.
46    pub fn read(&self, path: &Path) -> Result<Option<String>> {
47        if let Some(text) = self.text(path) {
48            return Ok(Some(text.to_string()));
49        }
50        match std::fs::read_to_string(path) {
51            Ok(text) => Ok(Some(text)),
52            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
53            Err(e) => Err(e.into()),
54        }
55    }
56}
57
58/// One problem an owner found while validating.
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct FieldError {
61    /// The setting at fault, if it is one.
62    pub key: Option<String>,
63    /// The file at fault, if it is one.
64    pub file: Option<PathBuf>,
65    /// What is wrong.
66    pub message: String,
67}
68
69impl fmt::Display for FieldError {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        match (&self.key, &self.file) {
72            (Some(key), _) => write!(f, "{key}: {}", self.message),
73            (None, Some(file)) => write!(f, "{}: {}", file.display(), self.message),
74            (None, None) => f.write_str(&self.message),
75        }
76    }
77}
78
79/// A test owner over a temp dir: `dev.toml` for Device, `wg.toml` for Workgroup, no
80/// Workspace, and secrets under `secret-<key>`.
81#[cfg(test)]
82pub(crate) mod test_support {
83    use super::*;
84    use crate::{Apply, Kind, Process, Scope, SettingDef};
85
86    pub struct TestOwner {
87        pub dir: tempfile::TempDir,
88        pub defs: Vec<SettingDef>,
89    }
90
91    impl TestOwner {
92        pub fn new(defs: Vec<SettingDef>) -> Self {
93            Self {
94                dir: tempfile::tempdir().unwrap(),
95                defs,
96            }
97        }
98        pub fn write(&self, name: &str, text: &str) {
99            std::fs::write(self.dir.path().join(name), text).unwrap();
100        }
101    }
102
103    impl SettingsOwner for TestOwner {
104        fn defs(&self) -> Vec<SettingDef> {
105            self.defs.clone()
106        }
107        fn file(&self, scope: Scope) -> crate::Result<PathBuf> {
108            match scope {
109                Scope::Device => Ok(self.dir.path().join("dev.toml")),
110                Scope::Workgroup => Ok(self.dir.path().join("wg.toml")),
111                Scope::Workspace => Err(crate::Error::Io(std::io::Error::other("no workspace"))),
112            }
113        }
114        fn secret_file(&self, key: &str) -> crate::Result<PathBuf> {
115            Ok(self.dir.path().join(format!("secret-{key}")))
116        }
117        fn validate(&self, _: &Staged) -> std::result::Result<(), Vec<FieldError>> {
118            Ok(())
119        }
120        fn scope_note(&self, scope: Scope) -> Option<String> {
121            (scope == Scope::Workgroup).then(|| "wg note".to_string())
122        }
123    }
124
125    pub fn def(key: &str, kind: Kind) -> SettingDef {
126        SettingDef {
127            key: key.into(),
128            kind,
129            scopes: vec![Scope::Workgroup],
130            overridable: false,
131            apply: Apply::Live,
132            default: None,
133            section: "test".into(),
134            doc: "test".into(),
135            process: Process::Bridge,
136        }
137    }
138}