Skip to main content

surjection_core/
local_settings.rs

1//! `state/local-settings.toml` (SPEC 4.5): this machine's own settings,
2//! never synced. Only the keys this build reads are typed; every other key
3//! is kept as it is when the file is written.
4
5use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8
9use crate::error::{CoreError, ErrorCode};
10use crate::fs::Fs;
11use crate::model::SCHEMA_VERSION;
12
13/// The file in `state/`.
14pub const LOCAL_SETTINGS_FILE: &str = "local-settings.toml";
15
16/// What the user answered to the first run's "Add a backup remote" step
17/// (SPEC 15.2).
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "kebab-case")]
20pub enum BackupRemoteOffer {
21    /// "Not now": the store stays local-only; Settings still offers Add.
22    NotNow,
23    /// A remote was added from the step.
24    Added,
25}
26
27/// What the user did with the app's first-run welcome (M58). Any value
28/// means "answered": the welcome is not shown again on this machine.
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(from = "String", into = "String")]
31pub enum WelcomeAnswer {
32    /// Skipped or closed before the end (`skipped`).
33    Skipped,
34    /// Reached Finish (`finished`).
35    Finished,
36    /// A value a newer build wrote, kept as written: still answered, the
37    /// file stays readable, and saving it writes the value back unchanged.
38    Other(String),
39}
40
41impl From<String> for WelcomeAnswer {
42    fn from(text: String) -> Self {
43        match text.as_str() {
44            "skipped" => Self::Skipped,
45            "finished" => Self::Finished,
46            _ => Self::Other(text),
47        }
48    }
49}
50
51impl From<WelcomeAnswer> for String {
52    fn from(answer: WelcomeAnswer) -> Self {
53        match answer {
54            WelcomeAnswer::Skipped => "skipped".to_owned(),
55            WelcomeAnswer::Finished => "finished".to_owned(),
56            WelcomeAnswer::Other(text) => text,
57        }
58    }
59}
60
61#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
62pub struct LocalSettings {
63    pub schema: i64,
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub backup_remote_offer: Option<BackupRemoteOffer>,
66    /// The first-run welcome was answered (M58). Absent in files written
67    /// before it existed: the app then decides from the store alone.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub welcome: Option<WelcomeAnswer>,
70    /// Settings > Updates switch (SPEC 16.4). Absent means on; read only
71    /// by builds that carry the updater.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub check_for_updates: Option<bool>,
74    /// The bundled Surjection skill version this machine already reported as
75    /// "customized, not updated" (#8), so the note is shown once per
76    /// version.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub agent_skill_notice: Option<String>,
79    /// The "Online catalogs" switch (#26). Absent means off: nothing
80    /// contacts a catalog until the user turns it on (the first time they
81    /// open Install > Browse, or `surject catalog online on`).
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub online_catalogs: Option<bool>,
84    /// The hosts the user approved for online catalogs: named when they
85    /// turned them on (M53) or allowed since (M60). A file from before
86    /// 0.9.0 has no list: its "on" approved `catalog::LEGACY_HOSTS`.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub online_catalog_hosts: Option<Vec<String>>,
89    /// Hosts the user answered "Not now" (M60, #40): not contacted, and
90    /// Browse does not ask about them again. Absent in older files.
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub online_catalog_hosts_not_now: Option<Vec<String>>,
93    /// SkillSpector, the optional external scanner (#30). Absent means
94    /// off.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub skillspector: Option<SkillSpectorSettings>,
97    /// `surject migrate loadout` finished on this machine (the Surjection
98    /// version that ran it): the automatic run at start is not repeated.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub loadout_migration: Option<String>,
101    /// Every other key, kept as it is (`[snyk_agent_scan]` of 0.7.0 among
102    /// them: `scan::external::snyk_leftover` removes it).
103    #[serde(flatten)]
104    pub extra: toml::Table,
105}
106
107/// `[skillspector]`: SkillSpector on this machine (#30).
108#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
109pub struct SkillSpectorSettings {
110    /// Run it on skill installs and updates. Absent means off.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub enabled: Option<bool>,
113    /// Seconds per scan (default 120, at most 3540: see
114    /// `skillspector::MAX_TIMEOUT`).
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub timeout_secs: Option<u64>,
117}
118
119impl Default for LocalSettings {
120    fn default() -> Self {
121        Self {
122            schema: SCHEMA_VERSION,
123            backup_remote_offer: None,
124            welcome: None,
125            check_for_updates: None,
126            agent_skill_notice: None,
127            online_catalogs: None,
128            online_catalog_hosts: None,
129            online_catalog_hosts_not_now: None,
130            skillspector: None,
131            loadout_migration: None,
132            extra: toml::Table::new(),
133        }
134    }
135}
136
137impl LocalSettings {
138    /// The settings of this machine; defaults when the file is absent.
139    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
140        let path = state_dir.join(LOCAL_SETTINGS_FILE);
141        if !fs.exists(&path) {
142            return Ok(Self::default());
143        }
144        let text = fs.read_to_string(&path).map_err(|err| {
145            CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
146        })?;
147        let settings: Self = toml::from_str(&text).map_err(|err| {
148            CoreError::new(ErrorCode::ParseError, err.message().to_owned()).with_path(&path)
149        })?;
150        if settings.schema != SCHEMA_VERSION {
151            return Err(CoreError::new(
152                ErrorCode::UnsupportedSchema,
153                format!("schema {} is not read by this build", settings.schema),
154            )
155            .with_path(&path));
156        }
157        Ok(settings)
158    }
159
160    pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
161        let text = toml::to_string_pretty(self).map_err(|err| {
162            CoreError::new(
163                ErrorCode::InvalidValue,
164                format!("cannot write local settings: {err}"),
165            )
166        })?;
167        fs.create_dir_all(state_dir).map_err(|err| {
168            CoreError::new(
169                ErrorCode::IoError,
170                format!("cannot create directory: {err}"),
171            )
172            .with_path(state_dir)
173        })?;
174        crate::apply::write_atomic(fs, &state_dir.join(LOCAL_SETTINGS_FILE), text.as_bytes())
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    #[test]
183    fn welcome_answers_round_trip_and_older_files_parse() {
184        let older: LocalSettings =
185            toml::from_str("schema = 1\nbackup_remote_offer = \"not-now\"\n").unwrap();
186        assert_eq!(older.welcome, None);
187        assert_eq!(older.backup_remote_offer, Some(BackupRemoteOffer::NotNow));
188
189        for answer in [WelcomeAnswer::Skipped, WelcomeAnswer::Finished] {
190            let settings = LocalSettings {
191                welcome: Some(answer.clone()),
192                ..LocalSettings::default()
193            };
194            let text = toml::to_string_pretty(&settings).unwrap();
195            let back: LocalSettings = toml::from_str(&text).unwrap();
196            assert_eq!(back.welcome, Some(answer));
197        }
198    }
199
200    #[test]
201    fn a_welcome_value_from_a_newer_build_counts_as_answered_and_round_trips() {
202        let newer: LocalSettings =
203            toml::from_str("schema = 1\nwelcome = \"replayed\"\nfuture = 3\n").unwrap();
204        assert_eq!(
205            newer.welcome,
206            Some(WelcomeAnswer::Other("replayed".to_owned()))
207        );
208        assert!(newer.extra.contains_key("future"), "other keys are kept");
209        let text = toml::to_string_pretty(&newer).unwrap();
210        assert!(text.contains("welcome = \"replayed\""), "{text}");
211        let back: LocalSettings = toml::from_str(&text).unwrap();
212        assert_eq!(back, newer);
213    }
214
215    #[test]
216    fn catalog_host_answers_parse_from_every_release() {
217        // 0.6 to 0.8: on, no hosts.
218        let pre: LocalSettings = toml::from_str("schema = 1\nonline_catalogs = true\n").unwrap();
219        assert_eq!(pre.online_catalog_hosts, None);
220        assert_eq!(pre.online_catalog_hosts_not_now, None);
221        // 0.9 to 1.0.0: hosts, no "Not now".
222        let text = "schema = 1\nonline_catalogs = true\nonline_catalog_hosts = [\"github.com\"]\n";
223        let hosts: LocalSettings = toml::from_str(text).unwrap();
224        assert_eq!(
225            hosts.online_catalog_hosts,
226            Some(vec!["github.com".to_owned()])
227        );
228        // 1.0.1: "Not now" round-trips.
229        let settings = LocalSettings {
230            online_catalog_hosts_not_now: Some(vec!["skills.sh".to_owned()]),
231            ..hosts
232        };
233        let back: LocalSettings =
234            toml::from_str(&toml::to_string_pretty(&settings).unwrap()).unwrap();
235        assert_eq!(back, settings);
236        assert!(back.extra.is_empty(), "a known key, not an extra one");
237    }
238}