Skip to main content

subspace_core/
settings.rs

1use crate::{
2    Secret,
3    config::{self, ChatEngine, Config, NoticeKind},
4    state,
5};
6use serde_json::{Map, Value};
7use std::collections::BTreeMap;
8use std::path::{Path, PathBuf};
9use std::{fs, io};
10use thiserror::Error;
11
12mod board_fields;
13mod board_file;
14mod merge;
15#[cfg(test)]
16mod native_board_tests;
17mod repos;
18mod web_boards;
19
20pub use board_fields::BoardFieldEdits;
21
22#[derive(Clone)]
23pub enum TokenEdit {
24    Keep,
25    Replace(Secret),
26    Clear,
27}
28#[derive(Clone)]
29pub struct ServiceSettings {
30    pub mcp: config::McpSettings,
31    pub chat_engine: ChatEngine,
32    /// `chat.acp.agent`. Its command overrides stay as the file has them.
33    pub acp_agent: config::AcpAgent,
34    pub board_order: Vec<String>,
35    pub auto_refresh: bool,
36    /// The config file's `terminal` object. Save sets each key, and removes
37    /// one whose value is `null`.
38    pub terminal: Map<String, Value>,
39    /// Explicit board choices from the config file. A missing id is enabled.
40    pub boards: BTreeMap<String, bool>,
41    /// Explicit registered-feature choices, including valid future flags.
42    pub features: BTreeMap<String, bool>,
43    /// The favourite repositories, `owner/name`, in saved order.
44    pub repos: Vec<String>,
45    pub github_token: TokenEdit,
46    /// Changes to boards' own run-time settings; empty when none changed.
47    pub board_fields: Vec<BoardFieldEdits>,
48    /// Changes to native boards' own settings files, keyed by board id:
49    /// the top-level keys to set. Empty when none changed.
50    pub board_files: BTreeMap<String, Map<String, Value>>,
51}
52#[derive(Debug, Error)]
53pub enum SettingsError {
54    #[error("cannot read settings file: {0}")]
55    Io(#[from] io::Error),
56    #[error("settings file contains invalid JSON")]
57    Json(#[from] serde_json::Error),
58    #[error("settings file has invalid values")]
59    Invalid,
60    #[error("invalid {field}: {reason}")]
61    Validation {
62        field: &'static str,
63        reason: &'static str,
64    },
65    #[error("settings file changed externally; reopen it before saving")]
66    Stale,
67    #[error("{}: {error}", file.display())]
68    BoardFile {
69        file: PathBuf,
70        #[source]
71        error: Box<SettingsError>,
72    },
73}
74pub struct SettingsFile {
75    file: PathBuf,
76    original: Option<String>,
77    root: Map<String, Value>,
78    values: ServiceSettings,
79    github_token_present: bool,
80    /// The native boards' own files opened so far, keyed by board id.
81    boards: BTreeMap<String, board_file::BoardFile>,
82}
83
84impl SettingsFile {
85    pub fn open(file: &Path) -> Result<Self, SettingsError> {
86        let original = read_existing(file)?;
87        let root = match original.as_deref() {
88            None => Map::new(),
89            Some(text) => match serde_json::from_str::<Value>(text)? {
90                Value::Object(v) => v,
91                _ => return Err(SettingsError::Invalid),
92            },
93        };
94        let (config, notices) = match original.as_deref() {
95            None => (Config::default(), Vec::new()),
96            Some(text) => config::parse(text, file),
97        };
98        if notices
99            .iter()
100            .any(|notice| notice.kind == NoticeKind::Warning)
101        {
102            return Err(SettingsError::Invalid);
103        }
104        let github_token_present = config.github.token.is_some();
105        let values = from_config(config, &root);
106        Ok(Self {
107            file: file.into(),
108            original,
109            root,
110            values,
111            github_token_present,
112            boards: BTreeMap::new(),
113        })
114    }
115    pub fn values(&self) -> &ServiceSettings {
116        &self.values
117    }
118    /// Opens native board `id`'s own settings file for this transaction, once,
119    /// and returns its saved settings. A missing file has none.
120    pub fn open_board_file(&mut self, id: &str) -> Result<Map<String, Value>, SettingsError> {
121        if !self.boards.contains_key(id) {
122            let file = config::board_file(&self.file, id);
123            let opened = board_file::BoardFile::open(file.clone())
124                .map_err(|error| board_error(&file, error))?;
125            self.boards.insert(id.to_owned(), opened);
126        }
127        Ok(self.board_file_values(id))
128    }
129    /// The saved settings of native board `id`'s opened file.
130    pub fn board_file_values(&self, id: &str) -> Map<String, Value> {
131        self.boards
132            .get(id)
133            .map(|board| board.values().clone())
134            .unwrap_or_default()
135    }
136    /// The saved values of the board whose config section is `section`.
137    pub fn board_values(&self, section: &[String]) -> Map<String, Value> {
138        board_fields::values(&self.root, section)
139    }
140    /// Whether the board at `section` has a saved secret `key`.
141    pub fn board_secret_present(&self, section: &[String], key: &str) -> bool {
142        board_fields::secret_present(&self.root, section, key)
143    }
144    /// The keys of the secrets saved for the board at `section`, never
145    /// their values.
146    pub fn board_secret_keys(&self, section: &[String]) -> Vec<String> {
147        board_fields::secret_keys(&self.root, section)
148    }
149    pub fn board_permission(&self, section: &[String], key: &str) -> bool {
150        board_fields::permission(&self.root, section, key)
151    }
152    pub fn token_present(&self, section: &str) -> bool {
153        section == "github" && self.github_token_present
154    }
155    /// Writes the config file, then each changed board file. Every file is
156    /// checked before the first write, so a conflict writes nothing.
157    pub fn save(&mut self, values: &ServiceSettings) -> Result<(), SettingsError> {
158        self.check_current()?;
159        let mut root = self.root.clone();
160        merge(&mut root, values, self.github_token_present)?;
161        let boards = self.edited_board_files(&values.board_files)?;
162        self.write_root(root)?;
163        self.write_board_files(boards)
164    }
165
166    /// Persist the switcher order without changing other settings.
167    pub fn save_board_order(&mut self, order: &[String]) -> Result<(), SettingsError> {
168        let mut root = self.root.clone();
169        merge::write_board_order(&mut root, order);
170        self.write_root(root)
171    }
172
173    /// Persist the board choices (`boards`) without changing other settings,
174    /// as Save writes them: a missing id uses the product default.
175    pub fn save_board_choices(
176        &mut self,
177        boards: &BTreeMap<String, bool>,
178    ) -> Result<(), SettingsError> {
179        let mut root = self.root.clone();
180        merge::write_board_choices(&mut root, boards);
181        self.write_root(root)
182    }
183
184    fn check_current(&self) -> Result<(), SettingsError> {
185        if read_existing(&self.file)? != self.original {
186            return Err(SettingsError::Stale);
187        }
188        Ok(())
189    }
190
191    fn edited_board_files(
192        &mut self,
193        edits: &BTreeMap<String, Map<String, Value>>,
194    ) -> Result<Vec<(String, Map<String, Value>)>, SettingsError> {
195        let mut edited = Vec::with_capacity(edits.len());
196        for (id, changes) in edits {
197            self.open_board_file(id)?;
198            let Some(board) = self.boards.get(id) else {
199                continue;
200            };
201            let root = board
202                .edited(changes)
203                .map_err(|error| board_error(board.path(), error))?;
204            edited.push((id.clone(), root));
205        }
206        Ok(edited)
207    }
208
209    fn write_board_files(
210        &mut self,
211        edited: Vec<(String, Map<String, Value>)>,
212    ) -> Result<(), SettingsError> {
213        for (id, root) in edited {
214            if let Some(board) = self.boards.get_mut(&id) {
215                let file = board.path().to_owned();
216                board
217                    .write(root)
218                    .map_err(|error| board_error(&file, error))?;
219            }
220        }
221        Ok(())
222    }
223
224    fn write_root(&mut self, root: Map<String, Value>) -> Result<(), SettingsError> {
225        let text = serde_json::to_string_pretty(&Value::Object(root.clone()))? + "\n";
226        let (config, notices) = config::parse(&text, &self.file);
227        if notices
228            .iter()
229            .any(|notice| notice.kind == NoticeKind::Warning)
230        {
231            return Err(SettingsError::Validation {
232                field: "settings",
233                reason: "values do not satisfy config constraints",
234            });
235        }
236        self.check_current()?;
237        state::write_atomic(&self.file, &text)?;
238        self.original = Some(text);
239        self.root = root;
240        self.github_token_present = config.github.token.is_some();
241        self.values = from_config(config, &self.root);
242        Ok(())
243    }
244}
245fn from_config(c: Config, root: &Map<String, Value>) -> ServiceSettings {
246    let repos = root
247        .get("repos")
248        .and_then(Value::as_array)
249        .filter(|items| items.iter().all(Value::is_string))
250        .map(|items| {
251            items
252                .iter()
253                .filter_map(Value::as_str)
254                .map(str::to_owned)
255                .collect()
256        })
257        .unwrap_or_default();
258    ServiceSettings {
259        mcp: c.mcp,
260        chat_engine: c.chat.engine,
261        acp_agent: c.chat.acp.agent,
262        board_order: c.board_order,
263        auto_refresh: c.auto_refresh,
264        terminal: c.terminal,
265        boards: c.boards,
266        features: c.features,
267        repos,
268        github_token: TokenEdit::Keep,
269        board_fields: Vec::new(),
270        board_files: BTreeMap::new(),
271    }
272}
273/// The file's text, or `None` when it does not exist.
274fn read_existing(file: &Path) -> io::Result<Option<String>> {
275    match fs::read_to_string(file) {
276        Ok(text) => Ok(Some(text)),
277        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
278        Err(error) => Err(error),
279    }
280}
281fn board_error(file: &Path, error: SettingsError) -> SettingsError {
282    SettingsError::BoardFile {
283        file: file.to_owned(),
284        error: Box::new(error),
285    }
286}
287fn section(root: &Map<String, Value>, key: &str) -> Map<String, Value> {
288    root.get(key)
289        .and_then(Value::as_object)
290        .cloned()
291        .unwrap_or_default()
292}
293fn token(section: &mut Map<String, Value>, edit: &TokenEdit, present: bool) {
294    match edit {
295        TokenEdit::Keep => {
296            if !present {
297                section.remove("token");
298            }
299        }
300        TokenEdit::Replace(v) => {
301            section.insert("token".into(), Value::String(v.expose().into()));
302        }
303        TokenEdit::Clear => {
304            section.remove("token");
305        }
306    }
307}
308fn merge(
309    root: &mut Map<String, Value>,
310    v: &ServiceSettings,
311    github_token_present: bool,
312) -> Result<(), SettingsError> {
313    merge::validate(v)?;
314    board_fields::validate(&v.board_fields)?;
315    merge::write_values(root, v, github_token_present)?;
316    board_fields::write(root, &v.board_fields)
317}
318
319#[cfg(test)]
320mod tests {
321    use super::{ChatEngine, ServiceSettings, SettingsError, SettingsFile, TokenEdit};
322    use crate::Secret;
323    use serde_json::Value;
324    use std::collections::BTreeMap;
325    use std::fs;
326
327    fn values() -> ServiceSettings {
328        ServiceSettings {
329            mcp: crate::config::McpSettings::default(),
330            chat_engine: ChatEngine::Copilot,
331            acp_agent: crate::config::AcpAgent::OpenCode,
332            board_order: Vec::new(),
333            auto_refresh: true,
334            terminal: serde_json::Map::new(),
335            boards: BTreeMap::new(),
336            features: BTreeMap::new(),
337            repos: vec!["owner/repo".into()],
338            github_token: TokenEdit::Keep,
339            board_fields: Vec::new(),
340            board_files: BTreeMap::new(),
341        }
342    }
343
344    #[test]
345    fn board_fields_are_saved_in_the_same_write() {
346        let dir = tempfile::tempdir().unwrap();
347        let path = dir.path().join("config.json");
348        fs::write(
349            &path,
350            r#"{"webBoards": {"notes": {"url": "https://notes.example"}}}"#,
351        )
352        .unwrap();
353        let mut file = SettingsFile::open(&path).unwrap();
354        let section = vec!["webBoards".to_owned(), "notes".to_owned()];
355        let mut settings = values();
356        settings.board_fields = vec![super::BoardFieldEdits {
357            section: section.clone(),
358            values: BTreeMap::from([("limit".into(), Some(Value::from(5)))]),
359            secrets: BTreeMap::from([("token".into(), TokenEdit::Replace(Secret::new("t")))]),
360            permissions: BTreeMap::new(),
361        }];
362        file.save(&settings).unwrap();
363        assert_eq!(file.board_values(&section)["limit"], Value::from(5));
364        assert!(file.board_secret_present(&section, "token"));
365        let (config, notices) = crate::config::load(&path);
366        assert!(notices.is_empty(), "{notices:?}");
367        assert_eq!(config.web_boards[0].secrets["token"].expose(), "t");
368        assert!(file.values().board_fields.is_empty());
369    }
370
371    #[test]
372    fn mcp_round_trips_every_key_and_preserves_extensions() {
373        let dir = tempfile::tempdir().unwrap();
374        let path = dir.path().join("config.json");
375        fs::write(&path, r#"{"mcp":{"extension":7},"unknown":true}"#).unwrap();
376        let mut file = SettingsFile::open(&path).unwrap();
377        let mut settings = file.values().clone();
378        settings.mcp.enabled = true;
379        settings.mcp.bind = "::1".parse().unwrap();
380        settings.mcp.port = 7400;
381        settings.mcp.require_token = true;
382        settings.mcp.groups.insert("github".into(), false);
383        file.save(&settings).unwrap();
384        let reopened = SettingsFile::open(&path).unwrap();
385        assert_eq!(reopened.values().mcp, settings.mcp);
386        assert_eq!(json(&path)["mcp"]["extension"], 7);
387        assert_eq!(json(&path)["unknown"], true);
388        let before = fs::read(&path).unwrap();
389        settings.mcp.bind = "0.0.0.0".parse().unwrap();
390        settings.mcp.require_token = false;
391        assert!(file.save(&settings).is_err());
392        assert_eq!(fs::read(&path).unwrap(), before);
393    }
394
395    #[test]
396    fn board_order_refresh_and_terminal_settings_round_trip() {
397        let dir = tempfile::tempdir().unwrap();
398        let file = dir.path().join("config.json");
399        fs::write(&file, "{}\n").unwrap();
400        let mut settings = SettingsFile::open(&file).unwrap();
401        let mut values = settings.values().clone();
402        values.board_order = vec!["irc".into(), "github".into()];
403        values.auto_refresh = false;
404        values.terminal = serde_json::json!({"fontFamily": "Menlo", "fontSize": null})
405            .as_object()
406            .cloned()
407            .unwrap();
408        settings.save(&values).unwrap();
409
410        let reopened = SettingsFile::open(&file).unwrap();
411        assert_eq!(reopened.values().board_order, ["irc", "github"]);
412        assert!(!reopened.values().auto_refresh);
413        assert_eq!(
414            Value::Object(reopened.values().terminal.clone()),
415            serde_json::json!({"fontFamily": "Menlo"})
416        );
417    }
418
419    #[test]
420    fn board_choices_save_alone_and_match_a_full_save() {
421        let dir = tempfile::tempdir().unwrap();
422        let file = dir.path().join("config.json");
423        fs::write(&file, r#"{"boards": {"irc": true}, "autoRefresh": false}"#).unwrap();
424        let mut alone = SettingsFile::open(&file).unwrap();
425        let mut boards = alone.values().boards.clone();
426        boards.insert("github".into(), false);
427        alone.save_board_choices(&boards).unwrap();
428        assert_eq!(
429            json(&file),
430            serde_json::json!({"boards": {"github": false, "irc": true}, "autoRefresh": false})
431        );
432
433        let full = dir.path().join("full.json");
434        fs::write(&full, r#"{"boards": {"irc": true}, "autoRefresh": false}"#).unwrap();
435        let mut saved = SettingsFile::open(&full).unwrap();
436        let mut values = saved.values().clone();
437        values.boards.clone_from(&boards);
438        saved.save(&values).unwrap();
439        assert_eq!(json(&full)["boards"], json(&file)["boards"]);
440        assert_eq!(alone.values().boards, saved.values().boards);
441
442        alone.save_board_choices(&BTreeMap::new()).unwrap();
443        assert!(json(&file).get("boards").is_none());
444    }
445
446    fn source() -> &'static str {
447        r#"{
448          "unknown": {"keep": true, "nested": {"value": 7}},
449          "github": {"token":"gh", "other": {"keep": "yes"}},
450          "terminal": {"fontSize": 13, "extension": {"keep": 7}},
451          "repos": ["owner/repo"]
452        }"#
453    }
454    fn json(file: &std::path::Path) -> Value {
455        serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap()
456    }
457
458    #[test]
459    fn preserves_unknown_properties_and_all_kept_tokens() {
460        let dir = tempfile::tempdir().unwrap();
461        let file = dir.path().join("config.json");
462        fs::write(&file, source()).unwrap();
463        let mut editor = SettingsFile::open(&file).unwrap();
464        let kept = editor.values().clone();
465        editor.save(&kept).unwrap();
466        let root = json(&file);
467        assert_eq!(
468            root["unknown"],
469            serde_json::json!({"keep":true,"nested":{"value":7}})
470        );
471        assert_eq!(root["github"]["other"], serde_json::json!({"keep":"yes"}));
472        assert_eq!(root["github"]["token"], "gh");
473        assert_eq!(root["terminal"]["fontSize"], 13);
474        assert_eq!(root["terminal"]["extension"], serde_json::json!({"keep":7}));
475        assert_eq!(root["repos"], serde_json::json!(["owner/repo"]));
476        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
477    }
478
479    #[test]
480    fn chat_engine_saves_without_replacing_unknown_chat_settings() {
481        let dir = tempfile::tempdir().unwrap();
482        let file = dir.path().join("config.json");
483        fs::write(
484            &file,
485            r#"{"chat":{"engine":"copilot","extension":{"keep":true}},"other":7}"#,
486        )
487        .unwrap();
488        let mut editor = SettingsFile::open(&file).unwrap();
489        let mut edited = editor.values().clone();
490        edited.chat_engine = crate::config::ChatEngine::Pi;
491        editor.save(&edited).unwrap();
492
493        let saved = json(&file);
494        assert_eq!(saved["chat"]["engine"], "pi");
495        assert_eq!(saved["chat"]["extension"], serde_json::json!({"keep":true}));
496        assert_eq!(saved["other"], 7);
497        assert_eq!(
498            crate::config::load(&file).0.chat.engine,
499            crate::config::ChatEngine::Pi
500        );
501    }
502
503    #[test]
504    fn acp_agent_saves_without_replacing_its_command_overrides() {
505        let dir = tempfile::tempdir().unwrap();
506        let file = dir.path().join("config.json");
507        fs::write(
508            &file,
509            r#"{"chat":{"engine":"copilot","acp":{"agent":"opencode","command":"/opt/agent","args":["acp"]}}}"#,
510        )
511        .unwrap();
512        let mut editor = SettingsFile::open(&file).unwrap();
513        let mut edited = editor.values().clone();
514        edited.chat_engine = ChatEngine::Acp;
515        edited.acp_agent = crate::config::AcpAgent::Claude;
516        editor.save(&edited).unwrap();
517
518        let saved = json(&file);
519        assert_eq!(saved["chat"]["engine"], "acp");
520        assert_eq!(saved["chat"]["acp"]["agent"], "claude");
521        assert_eq!(saved["chat"]["acp"]["command"], "/opt/agent");
522        assert_eq!(saved["chat"]["acp"]["args"], serde_json::json!(["acp"]));
523        let config = crate::config::load(&file).0;
524        assert_eq!(config.chat.acp.agent, crate::config::AcpAgent::Claude);
525    }
526
527    #[test]
528    fn cancelling_or_conflicting_chat_engine_edits_does_not_write_them() {
529        let dir = tempfile::tempdir().unwrap();
530        let file = dir.path().join("config.json");
531        let original = b"{\"chat\":{\"engine\":\"copilot\"}}\n";
532        fs::write(&file, original).unwrap();
533        let editor = SettingsFile::open(&file).unwrap();
534        let mut cancelled = editor.values().clone();
535        cancelled.chat_engine = crate::config::ChatEngine::Pi;
536        drop(editor);
537        assert_eq!(fs::read(&file).unwrap(), original);
538
539        let mut editor = SettingsFile::open(&file).unwrap();
540        let mut edited = editor.values().clone();
541        edited.chat_engine = crate::config::ChatEngine::Pi;
542        fs::write(&file, r#"{"external":true}"#).unwrap();
543        assert!(matches!(editor.save(&edited), Err(SettingsError::Stale)));
544        assert_eq!(json(&file), serde_json::json!({"external":true}));
545    }
546
547    #[test]
548    fn board_choices_save_transactionally_and_omitted_boards_stay_enabled() {
549        let dir = tempfile::tempdir().unwrap();
550        let file = dir.path().join("config.json");
551        fs::write(
552            &file,
553            r#"{"boards":{"irc":false,"excluded":true},"extension":{"keep":true}}"#,
554        )
555        .unwrap();
556        let mut editor = SettingsFile::open(&file).unwrap();
557        assert!(!editor.values().boards["irc"]);
558        assert!(!editor.values().boards.contains_key("github"));
559
560        let mut edited = editor.values().clone();
561        edited.boards.remove("irc");
562        edited.boards.insert("github".into(), false);
563        editor.save(&edited).unwrap();
564
565        let saved = json(&file);
566        assert_eq!(
567            saved["boards"],
568            serde_json::json!({"excluded": true, "github": false})
569        );
570        assert_eq!(saved["extension"], serde_json::json!({"keep": true}));
571        let config = crate::config::load(&file).0;
572        assert!(config.board_enabled("irc"));
573        assert!(!config.board_enabled("github"));
574        assert!(config.board_enabled("actions"));
575    }
576
577    #[test]
578    fn opening_and_cancelling_board_edits_does_not_write_the_file() {
579        let dir = tempfile::tempdir().unwrap();
580        let file = dir.path().join("config.json");
581        let original = b"{\n  \"boards\": {\"github-copilot-agents\": false}\n}\n";
582        fs::write(&file, original).unwrap();
583        let editor = SettingsFile::open(&file).unwrap();
584        let mut cancelled = editor.values().clone();
585        cancelled.boards.remove("github-copilot-agents");
586        drop(editor);
587        assert_eq!(fs::read(&file).unwrap(), original);
588    }
589
590    #[test]
591    fn feature_choices_preserve_unknown_flags_and_save_transactionally() {
592        let dir = tempfile::tempdir().unwrap();
593        let file = dir.path().join("config.json");
594        fs::write(
595            &file,
596            r#"{"features":{"app.pi-chat":false,"board.future.preview":true},"extension":{"keep":7}}"#,
597        )
598        .unwrap();
599        let mut editor = SettingsFile::open(&file).unwrap();
600        assert!(editor.values().features["board.future.preview"]);
601        let mut edited = editor.values().clone();
602        edited.features.insert("app.pi-chat".into(), true);
603        editor.save(&edited).unwrap();
604
605        let saved = json(&file);
606        assert_eq!(saved["features"]["app.pi-chat"], true);
607        assert_eq!(saved["features"]["board.future.preview"], true);
608        assert_eq!(saved["extension"]["keep"], 7);
609        assert!(crate::config::load(&file).0.features["board.future.preview"]);
610    }
611
612    #[test]
613    fn cancelling_or_conflicting_feature_edits_does_not_write_them() {
614        let dir = tempfile::tempdir().unwrap();
615        let file = dir.path().join("config.json");
616        let original = b"{\"features\":{\"app.pi-chat\":false}}\n";
617        fs::write(&file, original).unwrap();
618        let editor = SettingsFile::open(&file).unwrap();
619        let mut cancelled = editor.values().clone();
620        cancelled.features.insert("app.pi-chat".into(), true);
621        drop(editor);
622        assert_eq!(fs::read(&file).unwrap(), original);
623
624        let mut editor = SettingsFile::open(&file).unwrap();
625        let mut edited = editor.values().clone();
626        edited.features.insert("app.pi-chat".into(), true);
627        fs::write(&file, r#"{"external":true}"#).unwrap();
628        assert!(matches!(editor.save(&edited), Err(SettingsError::Stale)));
629        assert_eq!(json(&file), serde_json::json!({"external":true}));
630    }
631
632    #[test]
633    fn malformed_feature_keys_or_values_refuse_settings_file() {
634        let dir = tempfile::tempdir().unwrap();
635        for source in [
636            r#"{"features":{"not-namespaced":true}}"#,
637            r#"{"features":{"app.pi-chat":"true"}}"#,
638        ] {
639            let file = dir.path().join(format!("{}.json", source.len()));
640            fs::write(&file, source).unwrap();
641            assert!(matches!(
642                SettingsFile::open(&file),
643                Err(SettingsError::Invalid)
644            ));
645        }
646    }
647
648    #[test]
649    fn replaces_and_clears_tokens_without_retaining_secret() {
650        let dir = tempfile::tempdir().unwrap();
651        let file = dir.path().join("config.json");
652        fs::write(&file, source()).unwrap();
653        let mut editor = SettingsFile::open(&file).unwrap();
654        let mut edited = editor.values().clone();
655        edited.github_token = TokenEdit::Replace(Secret::new("replacement"));
656        editor.save(&edited).unwrap();
657        assert_eq!(json(&file)["github"]["token"], "replacement");
658        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
659        edited = editor.values().clone();
660        edited.github_token = TokenEdit::Clear;
661        editor.save(&edited).unwrap();
662        assert!(json(&file)["github"].get("token").is_none());
663        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
664    }
665
666    #[test]
667    fn distinguishes_missing_empty_and_externally_created_files() {
668        let dir = tempfile::tempdir().unwrap();
669        let missing = dir.path().join("missing.json");
670        let mut editor = SettingsFile::open(&missing).unwrap();
671        fs::write(&missing, "").unwrap();
672        assert!(matches!(editor.save(&values()), Err(SettingsError::Stale)));
673        assert!(matches!(
674            SettingsFile::open(&missing),
675            Err(SettingsError::Json(_))
676        ));
677        let empty = dir.path().join("empty.json");
678        fs::write(&empty, "").unwrap();
679        assert!(matches!(
680            SettingsFile::open(&empty),
681            Err(SettingsError::Json(_))
682        ));
683    }
684
685    #[test]
686    fn detects_deleted_files_as_stale() {
687        let dir = tempfile::tempdir().unwrap();
688        let file = dir.path().join("config.json");
689        fs::write(&file, "{}").unwrap();
690        let mut editor = SettingsFile::open(&file).unwrap();
691        fs::remove_file(&file).unwrap();
692        assert!(matches!(editor.save(&values()), Err(SettingsError::Stale)));
693    }
694
695    #[test]
696    fn invalid_edits_are_safe_and_leave_original_bytes() {
697        let dir = tempfile::tempdir().unwrap();
698        let file = dir.path().join("config.json");
699        fs::write(&file, source()).unwrap();
700        let original = fs::read(&file).unwrap();
701        let mut editor = SettingsFile::open(&file).unwrap();
702        let mut invalid = editor.values().clone();
703        invalid.github_token = TokenEdit::Replace(Secret::new(""));
704        assert!(matches!(
705            editor.save(&invalid),
706            Err(SettingsError::Validation { .. })
707        ));
708        assert_eq!(fs::read(&file).unwrap(), original);
709        invalid = editor.values().clone();
710        invalid.repos = vec!["not a repo".into()];
711        assert!(matches!(
712            editor.save(&invalid),
713            Err(SettingsError::Validation { .. })
714        ));
715        assert_eq!(fs::read(&file).unwrap(), original);
716    }
717
718    #[cfg(unix)]
719    #[test]
720    fn new_and_existing_files_are_private_and_loadable() {
721        use std::os::unix::fs::PermissionsExt;
722        let dir = tempfile::tempdir().unwrap();
723        let existing = dir.path().join("existing.json");
724        fs::write(&existing, r#"{"github":{"token":"old"}}"#).unwrap();
725        fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
726        let mut existing_editor = SettingsFile::open(&existing).unwrap();
727        let existing_values = existing_editor.values().clone();
728        existing_editor.save(&existing_values).unwrap();
729        assert_eq!(
730            fs::metadata(&existing).unwrap().permissions().mode() & 0o777,
731            0o600
732        );
733        assert_eq!(
734            crate::config::load(&existing)
735                .0
736                .github
737                .token
738                .unwrap()
739                .expose(),
740            "old"
741        );
742        let new_file = dir.path().join("new.json");
743        let mut new_editor = SettingsFile::open(&new_file).unwrap();
744        let mut new_values = values();
745        new_values.github_token = TokenEdit::Replace(Secret::new("new"));
746        new_editor.save(&new_values).unwrap();
747        assert_eq!(
748            fs::metadata(&new_file).unwrap().permissions().mode() & 0o777,
749            0o600
750        );
751        assert_eq!(
752            crate::config::load(&new_file)
753                .0
754                .github
755                .token
756                .unwrap()
757                .expose(),
758            "new"
759        );
760    }
761}