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    /// "Check this address" answers per host (#47). Absent: none yet.
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub address_check_hosts: Option<AddressCheckHosts>,
104    /// Every other key, kept as it is (`[snyk_agent_scan]` of 0.7.0 among
105    /// them: `scan::external::snyk_leftover` removes it).
106    #[serde(flatten)]
107    pub extra: toml::Table,
108}
109
110/// `[skillspector]`: SkillSpector on this machine (#30).
111#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
112pub struct SkillSpectorSettings {
113    /// Run it on skill installs and updates. Absent means off.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub enabled: Option<bool>,
116    /// Seconds per scan (default 120, at most 3540: see
117    /// `skillspector::MAX_TIMEOUT`).
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub timeout_secs: Option<u64>,
120}
121
122/// `[address_check_hosts]`: the hosts the user answered for "Check this
123/// address" (#47). A host in neither list was never asked about; the
124/// check contacts only `allowed` hosts.
125#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
126pub struct AddressCheckHosts {
127    #[serde(default, skip_serializing_if = "Vec::is_empty")]
128    pub allowed: Vec<String>,
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub denied: Vec<String>,
131}
132
133impl Default for LocalSettings {
134    fn default() -> Self {
135        Self {
136            schema: SCHEMA_VERSION,
137            backup_remote_offer: None,
138            welcome: None,
139            check_for_updates: None,
140            agent_skill_notice: None,
141            online_catalogs: None,
142            online_catalog_hosts: None,
143            online_catalog_hosts_not_now: None,
144            skillspector: None,
145            loadout_migration: None,
146            address_check_hosts: None,
147            extra: toml::Table::new(),
148        }
149    }
150}
151
152impl LocalSettings {
153    /// The settings of this machine; defaults when the file is absent.
154    pub fn load(fs: &dyn Fs, state_dir: &Path) -> Result<Self, CoreError> {
155        let path = state_dir.join(LOCAL_SETTINGS_FILE);
156        if !fs.exists(&path) {
157            return Ok(Self::default());
158        }
159        let text = fs.read_to_string(&path).map_err(|err| {
160            CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(&path)
161        })?;
162        let settings: Self = toml::from_str(&text).map_err(|err| {
163            CoreError::new(ErrorCode::ParseError, err.message().to_owned()).with_path(&path)
164        })?;
165        if settings.schema != SCHEMA_VERSION {
166            return Err(CoreError::new(
167                ErrorCode::UnsupportedSchema,
168                format!("schema {} is not read by this build", settings.schema),
169            )
170            .with_path(&path));
171        }
172        Ok(settings)
173    }
174
175    pub fn save(&self, fs: &dyn Fs, state_dir: &Path) -> Result<(), CoreError> {
176        let text = toml::to_string_pretty(self).map_err(|err| {
177            CoreError::new(
178                ErrorCode::InvalidValue,
179                format!("cannot write local settings: {err}"),
180            )
181        })?;
182        fs.create_dir_all(state_dir).map_err(|err| {
183            CoreError::new(
184                ErrorCode::IoError,
185                format!("cannot create directory: {err}"),
186            )
187            .with_path(state_dir)
188        })?;
189        crate::apply::write_atomic(fs, &state_dir.join(LOCAL_SETTINGS_FILE), text.as_bytes())
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    fn welcome_answers_round_trip_and_older_files_parse() {
199        let older: LocalSettings =
200            toml::from_str("schema = 1\nbackup_remote_offer = \"not-now\"\n").unwrap();
201        assert_eq!(older.welcome, None);
202        assert_eq!(older.backup_remote_offer, Some(BackupRemoteOffer::NotNow));
203
204        for answer in [WelcomeAnswer::Skipped, WelcomeAnswer::Finished] {
205            let settings = LocalSettings {
206                welcome: Some(answer.clone()),
207                ..LocalSettings::default()
208            };
209            let text = toml::to_string_pretty(&settings).unwrap();
210            let back: LocalSettings = toml::from_str(&text).unwrap();
211            assert_eq!(back.welcome, Some(answer));
212        }
213    }
214
215    #[test]
216    fn a_welcome_value_from_a_newer_build_counts_as_answered_and_round_trips() {
217        let newer: LocalSettings =
218            toml::from_str("schema = 1\nwelcome = \"replayed\"\nfuture = 3\n").unwrap();
219        assert_eq!(
220            newer.welcome,
221            Some(WelcomeAnswer::Other("replayed".to_owned()))
222        );
223        assert!(newer.extra.contains_key("future"), "other keys are kept");
224        let text = toml::to_string_pretty(&newer).unwrap();
225        assert!(text.contains("welcome = \"replayed\""), "{text}");
226        let back: LocalSettings = toml::from_str(&text).unwrap();
227        assert_eq!(back, newer);
228    }
229
230    #[test]
231    fn catalog_host_answers_parse_from_every_release() {
232        // 0.6 to 0.8: on, no hosts.
233        let pre: LocalSettings = toml::from_str("schema = 1\nonline_catalogs = true\n").unwrap();
234        assert_eq!(pre.online_catalog_hosts, None);
235        assert_eq!(pre.online_catalog_hosts_not_now, None);
236        // 0.9 to 1.0.0: hosts, no "Not now".
237        let text = "schema = 1\nonline_catalogs = true\nonline_catalog_hosts = [\"github.com\"]\n";
238        let hosts: LocalSettings = toml::from_str(text).unwrap();
239        assert_eq!(
240            hosts.online_catalog_hosts,
241            Some(vec!["github.com".to_owned()])
242        );
243        // 1.0.1: "Not now" round-trips.
244        let settings = LocalSettings {
245            online_catalog_hosts_not_now: Some(vec!["skills.sh".to_owned()]),
246            ..hosts
247        };
248        let back: LocalSettings =
249            toml::from_str(&toml::to_string_pretty(&settings).unwrap()).unwrap();
250        assert_eq!(back, settings);
251        assert!(back.extra.is_empty(), "a known key, not an extra one");
252    }
253}