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    pub fn board_permission(&self, section: &[String], key: &str) -> bool {
145        board_fields::permission(&self.root, section, key)
146    }
147    pub fn token_present(&self, section: &str) -> bool {
148        section == "github" && self.github_token_present
149    }
150    /// Writes the config file, then each changed board file. Every file is
151    /// checked before the first write, so a conflict writes nothing.
152    pub fn save(&mut self, values: &ServiceSettings) -> Result<(), SettingsError> {
153        self.check_current()?;
154        let mut root = self.root.clone();
155        merge(&mut root, values, self.github_token_present)?;
156        let boards = self.edited_board_files(&values.board_files)?;
157        self.write_root(root)?;
158        self.write_board_files(boards)
159    }
160
161    /// Persist the switcher order without changing other settings.
162    pub fn save_board_order(&mut self, order: &[String]) -> Result<(), SettingsError> {
163        let mut root = self.root.clone();
164        merge::write_board_order(&mut root, order);
165        self.write_root(root)
166    }
167
168    fn check_current(&self) -> Result<(), SettingsError> {
169        if read_existing(&self.file)? != self.original {
170            return Err(SettingsError::Stale);
171        }
172        Ok(())
173    }
174
175    fn edited_board_files(
176        &mut self,
177        edits: &BTreeMap<String, Map<String, Value>>,
178    ) -> Result<Vec<(String, Map<String, Value>)>, SettingsError> {
179        let mut edited = Vec::with_capacity(edits.len());
180        for (id, changes) in edits {
181            self.open_board_file(id)?;
182            let Some(board) = self.boards.get(id) else {
183                continue;
184            };
185            let root = board
186                .edited(changes)
187                .map_err(|error| board_error(board.path(), error))?;
188            edited.push((id.clone(), root));
189        }
190        Ok(edited)
191    }
192
193    fn write_board_files(
194        &mut self,
195        edited: Vec<(String, Map<String, Value>)>,
196    ) -> Result<(), SettingsError> {
197        for (id, root) in edited {
198            if let Some(board) = self.boards.get_mut(&id) {
199                let file = board.path().to_owned();
200                board
201                    .write(root)
202                    .map_err(|error| board_error(&file, error))?;
203            }
204        }
205        Ok(())
206    }
207
208    fn write_root(&mut self, root: Map<String, Value>) -> Result<(), SettingsError> {
209        let text = serde_json::to_string_pretty(&Value::Object(root.clone()))? + "\n";
210        let (config, notices) = config::parse(&text, &self.file);
211        if notices
212            .iter()
213            .any(|notice| notice.kind == NoticeKind::Warning)
214        {
215            return Err(SettingsError::Validation {
216                field: "settings",
217                reason: "values do not satisfy config constraints",
218            });
219        }
220        self.check_current()?;
221        state::write_atomic(&self.file, &text)?;
222        self.original = Some(text);
223        self.root = root;
224        self.github_token_present = config.github.token.is_some();
225        self.values = from_config(config, &self.root);
226        Ok(())
227    }
228}
229fn from_config(c: Config, root: &Map<String, Value>) -> ServiceSettings {
230    let repos = root
231        .get("repos")
232        .and_then(Value::as_array)
233        .filter(|items| items.iter().all(Value::is_string))
234        .map(|items| {
235            items
236                .iter()
237                .filter_map(Value::as_str)
238                .map(str::to_owned)
239                .collect()
240        })
241        .unwrap_or_default();
242    ServiceSettings {
243        mcp: c.mcp,
244        chat_engine: c.chat.engine,
245        acp_agent: c.chat.acp.agent,
246        board_order: c.board_order,
247        auto_refresh: c.auto_refresh,
248        terminal: c.terminal,
249        boards: c.boards,
250        features: c.features,
251        repos,
252        github_token: TokenEdit::Keep,
253        board_fields: Vec::new(),
254        board_files: BTreeMap::new(),
255    }
256}
257/// The file's text, or `None` when it does not exist.
258fn read_existing(file: &Path) -> io::Result<Option<String>> {
259    match fs::read_to_string(file) {
260        Ok(text) => Ok(Some(text)),
261        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
262        Err(error) => Err(error),
263    }
264}
265fn board_error(file: &Path, error: SettingsError) -> SettingsError {
266    SettingsError::BoardFile {
267        file: file.to_owned(),
268        error: Box::new(error),
269    }
270}
271fn section(root: &Map<String, Value>, key: &str) -> Map<String, Value> {
272    root.get(key)
273        .and_then(Value::as_object)
274        .cloned()
275        .unwrap_or_default()
276}
277fn token(section: &mut Map<String, Value>, edit: &TokenEdit, present: bool) {
278    match edit {
279        TokenEdit::Keep => {
280            if !present {
281                section.remove("token");
282            }
283        }
284        TokenEdit::Replace(v) => {
285            section.insert("token".into(), Value::String(v.expose().into()));
286        }
287        TokenEdit::Clear => {
288            section.remove("token");
289        }
290    }
291}
292fn merge(
293    root: &mut Map<String, Value>,
294    v: &ServiceSettings,
295    github_token_present: bool,
296) -> Result<(), SettingsError> {
297    merge::validate(v)?;
298    board_fields::validate(&v.board_fields)?;
299    merge::write_values(root, v, github_token_present)?;
300    board_fields::write(root, &v.board_fields)
301}
302
303#[cfg(test)]
304mod tests {
305    use super::{ChatEngine, ServiceSettings, SettingsError, SettingsFile, TokenEdit};
306    use crate::Secret;
307    use serde_json::Value;
308    use std::collections::BTreeMap;
309    use std::fs;
310
311    fn values() -> ServiceSettings {
312        ServiceSettings {
313            mcp: crate::config::McpSettings::default(),
314            chat_engine: ChatEngine::Copilot,
315            acp_agent: crate::config::AcpAgent::OpenCode,
316            board_order: Vec::new(),
317            auto_refresh: true,
318            terminal: serde_json::Map::new(),
319            boards: BTreeMap::new(),
320            features: BTreeMap::new(),
321            repos: vec!["owner/repo".into()],
322            github_token: TokenEdit::Keep,
323            board_fields: Vec::new(),
324            board_files: BTreeMap::new(),
325        }
326    }
327
328    #[test]
329    fn board_fields_are_saved_in_the_same_write() {
330        let dir = tempfile::tempdir().unwrap();
331        let path = dir.path().join("config.json");
332        fs::write(
333            &path,
334            r#"{"webBoards": {"notes": {"url": "https://notes.example"}}}"#,
335        )
336        .unwrap();
337        let mut file = SettingsFile::open(&path).unwrap();
338        let section = vec!["webBoards".to_owned(), "notes".to_owned()];
339        let mut settings = values();
340        settings.board_fields = vec![super::BoardFieldEdits {
341            section: section.clone(),
342            values: BTreeMap::from([("limit".into(), Some(Value::from(5)))]),
343            secrets: BTreeMap::from([("token".into(), TokenEdit::Replace(Secret::new("t")))]),
344            permissions: BTreeMap::new(),
345        }];
346        file.save(&settings).unwrap();
347        assert_eq!(file.board_values(&section)["limit"], Value::from(5));
348        assert!(file.board_secret_present(&section, "token"));
349        let (config, notices) = crate::config::load(&path);
350        assert!(notices.is_empty(), "{notices:?}");
351        assert_eq!(config.web_boards[0].secrets["token"].expose(), "t");
352        assert!(file.values().board_fields.is_empty());
353    }
354
355    #[test]
356    fn mcp_round_trips_every_key_and_preserves_extensions() {
357        let dir = tempfile::tempdir().unwrap();
358        let path = dir.path().join("config.json");
359        fs::write(&path, r#"{"mcp":{"extension":7},"unknown":true}"#).unwrap();
360        let mut file = SettingsFile::open(&path).unwrap();
361        let mut settings = file.values().clone();
362        settings.mcp.enabled = true;
363        settings.mcp.bind = "::1".parse().unwrap();
364        settings.mcp.port = 7400;
365        settings.mcp.require_token = true;
366        settings.mcp.groups.insert("github".into(), false);
367        file.save(&settings).unwrap();
368        let reopened = SettingsFile::open(&path).unwrap();
369        assert_eq!(reopened.values().mcp, settings.mcp);
370        assert_eq!(json(&path)["mcp"]["extension"], 7);
371        assert_eq!(json(&path)["unknown"], true);
372        let before = fs::read(&path).unwrap();
373        settings.mcp.bind = "0.0.0.0".parse().unwrap();
374        settings.mcp.require_token = false;
375        assert!(file.save(&settings).is_err());
376        assert_eq!(fs::read(&path).unwrap(), before);
377    }
378
379    #[test]
380    fn board_order_refresh_and_terminal_settings_round_trip() {
381        let dir = tempfile::tempdir().unwrap();
382        let file = dir.path().join("config.json");
383        fs::write(&file, "{}\n").unwrap();
384        let mut settings = SettingsFile::open(&file).unwrap();
385        let mut values = settings.values().clone();
386        values.board_order = vec!["irc".into(), "github".into()];
387        values.auto_refresh = false;
388        values.terminal = serde_json::json!({"fontFamily": "Menlo", "fontSize": null})
389            .as_object()
390            .cloned()
391            .unwrap();
392        settings.save(&values).unwrap();
393
394        let reopened = SettingsFile::open(&file).unwrap();
395        assert_eq!(reopened.values().board_order, ["irc", "github"]);
396        assert!(!reopened.values().auto_refresh);
397        assert_eq!(
398            Value::Object(reopened.values().terminal.clone()),
399            serde_json::json!({"fontFamily": "Menlo"})
400        );
401    }
402
403    fn source() -> &'static str {
404        r#"{
405          "unknown": {"keep": true, "nested": {"value": 7}},
406          "github": {"token":"gh", "other": {"keep": "yes"}},
407          "terminal": {"fontSize": 13, "extension": {"keep": 7}},
408          "repos": ["owner/repo"]
409        }"#
410    }
411    fn json(file: &std::path::Path) -> Value {
412        serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap()
413    }
414
415    #[test]
416    fn preserves_unknown_properties_and_all_kept_tokens() {
417        let dir = tempfile::tempdir().unwrap();
418        let file = dir.path().join("config.json");
419        fs::write(&file, source()).unwrap();
420        let mut editor = SettingsFile::open(&file).unwrap();
421        let kept = editor.values().clone();
422        editor.save(&kept).unwrap();
423        let root = json(&file);
424        assert_eq!(
425            root["unknown"],
426            serde_json::json!({"keep":true,"nested":{"value":7}})
427        );
428        assert_eq!(root["github"]["other"], serde_json::json!({"keep":"yes"}));
429        assert_eq!(root["github"]["token"], "gh");
430        assert_eq!(root["terminal"]["fontSize"], 13);
431        assert_eq!(root["terminal"]["extension"], serde_json::json!({"keep":7}));
432        assert_eq!(root["repos"], serde_json::json!(["owner/repo"]));
433        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
434    }
435
436    #[test]
437    fn chat_engine_saves_without_replacing_unknown_chat_settings() {
438        let dir = tempfile::tempdir().unwrap();
439        let file = dir.path().join("config.json");
440        fs::write(
441            &file,
442            r#"{"chat":{"engine":"copilot","extension":{"keep":true}},"other":7}"#,
443        )
444        .unwrap();
445        let mut editor = SettingsFile::open(&file).unwrap();
446        let mut edited = editor.values().clone();
447        edited.chat_engine = crate::config::ChatEngine::Pi;
448        editor.save(&edited).unwrap();
449
450        let saved = json(&file);
451        assert_eq!(saved["chat"]["engine"], "pi");
452        assert_eq!(saved["chat"]["extension"], serde_json::json!({"keep":true}));
453        assert_eq!(saved["other"], 7);
454        assert_eq!(
455            crate::config::load(&file).0.chat.engine,
456            crate::config::ChatEngine::Pi
457        );
458    }
459
460    #[test]
461    fn acp_agent_saves_without_replacing_its_command_overrides() {
462        let dir = tempfile::tempdir().unwrap();
463        let file = dir.path().join("config.json");
464        fs::write(
465            &file,
466            r#"{"chat":{"engine":"copilot","acp":{"agent":"opencode","command":"/opt/agent","args":["acp"]}}}"#,
467        )
468        .unwrap();
469        let mut editor = SettingsFile::open(&file).unwrap();
470        let mut edited = editor.values().clone();
471        edited.chat_engine = ChatEngine::Acp;
472        edited.acp_agent = crate::config::AcpAgent::Claude;
473        editor.save(&edited).unwrap();
474
475        let saved = json(&file);
476        assert_eq!(saved["chat"]["engine"], "acp");
477        assert_eq!(saved["chat"]["acp"]["agent"], "claude");
478        assert_eq!(saved["chat"]["acp"]["command"], "/opt/agent");
479        assert_eq!(saved["chat"]["acp"]["args"], serde_json::json!(["acp"]));
480        let config = crate::config::load(&file).0;
481        assert_eq!(config.chat.acp.agent, crate::config::AcpAgent::Claude);
482    }
483
484    #[test]
485    fn cancelling_or_conflicting_chat_engine_edits_does_not_write_them() {
486        let dir = tempfile::tempdir().unwrap();
487        let file = dir.path().join("config.json");
488        let original = b"{\"chat\":{\"engine\":\"copilot\"}}\n";
489        fs::write(&file, original).unwrap();
490        let editor = SettingsFile::open(&file).unwrap();
491        let mut cancelled = editor.values().clone();
492        cancelled.chat_engine = crate::config::ChatEngine::Pi;
493        drop(editor);
494        assert_eq!(fs::read(&file).unwrap(), original);
495
496        let mut editor = SettingsFile::open(&file).unwrap();
497        let mut edited = editor.values().clone();
498        edited.chat_engine = crate::config::ChatEngine::Pi;
499        fs::write(&file, r#"{"external":true}"#).unwrap();
500        assert!(matches!(editor.save(&edited), Err(SettingsError::Stale)));
501        assert_eq!(json(&file), serde_json::json!({"external":true}));
502    }
503
504    #[test]
505    fn board_choices_save_transactionally_and_omitted_boards_stay_enabled() {
506        let dir = tempfile::tempdir().unwrap();
507        let file = dir.path().join("config.json");
508        fs::write(
509            &file,
510            r#"{"boards":{"irc":false,"excluded":true},"extension":{"keep":true}}"#,
511        )
512        .unwrap();
513        let mut editor = SettingsFile::open(&file).unwrap();
514        assert!(!editor.values().boards["irc"]);
515        assert!(!editor.values().boards.contains_key("github"));
516
517        let mut edited = editor.values().clone();
518        edited.boards.remove("irc");
519        edited.boards.insert("github".into(), false);
520        editor.save(&edited).unwrap();
521
522        let saved = json(&file);
523        assert_eq!(
524            saved["boards"],
525            serde_json::json!({"excluded": true, "github": false})
526        );
527        assert_eq!(saved["extension"], serde_json::json!({"keep": true}));
528        let config = crate::config::load(&file).0;
529        assert!(config.board_enabled("irc"));
530        assert!(!config.board_enabled("github"));
531        assert!(config.board_enabled("actions"));
532    }
533
534    #[test]
535    fn opening_and_cancelling_board_edits_does_not_write_the_file() {
536        let dir = tempfile::tempdir().unwrap();
537        let file = dir.path().join("config.json");
538        let original = b"{\n  \"boards\": {\"github-copilot-agents\": false}\n}\n";
539        fs::write(&file, original).unwrap();
540        let editor = SettingsFile::open(&file).unwrap();
541        let mut cancelled = editor.values().clone();
542        cancelled.boards.remove("github-copilot-agents");
543        drop(editor);
544        assert_eq!(fs::read(&file).unwrap(), original);
545    }
546
547    #[test]
548    fn feature_choices_preserve_unknown_flags_and_save_transactionally() {
549        let dir = tempfile::tempdir().unwrap();
550        let file = dir.path().join("config.json");
551        fs::write(
552            &file,
553            r#"{"features":{"app.pi-chat":false,"board.future.preview":true},"extension":{"keep":7}}"#,
554        )
555        .unwrap();
556        let mut editor = SettingsFile::open(&file).unwrap();
557        assert!(editor.values().features["board.future.preview"]);
558        let mut edited = editor.values().clone();
559        edited.features.insert("app.pi-chat".into(), true);
560        editor.save(&edited).unwrap();
561
562        let saved = json(&file);
563        assert_eq!(saved["features"]["app.pi-chat"], true);
564        assert_eq!(saved["features"]["board.future.preview"], true);
565        assert_eq!(saved["extension"]["keep"], 7);
566        assert!(crate::config::load(&file).0.features["board.future.preview"]);
567    }
568
569    #[test]
570    fn cancelling_or_conflicting_feature_edits_does_not_write_them() {
571        let dir = tempfile::tempdir().unwrap();
572        let file = dir.path().join("config.json");
573        let original = b"{\"features\":{\"app.pi-chat\":false}}\n";
574        fs::write(&file, original).unwrap();
575        let editor = SettingsFile::open(&file).unwrap();
576        let mut cancelled = editor.values().clone();
577        cancelled.features.insert("app.pi-chat".into(), true);
578        drop(editor);
579        assert_eq!(fs::read(&file).unwrap(), original);
580
581        let mut editor = SettingsFile::open(&file).unwrap();
582        let mut edited = editor.values().clone();
583        edited.features.insert("app.pi-chat".into(), true);
584        fs::write(&file, r#"{"external":true}"#).unwrap();
585        assert!(matches!(editor.save(&edited), Err(SettingsError::Stale)));
586        assert_eq!(json(&file), serde_json::json!({"external":true}));
587    }
588
589    #[test]
590    fn malformed_feature_keys_or_values_refuse_settings_file() {
591        let dir = tempfile::tempdir().unwrap();
592        for source in [
593            r#"{"features":{"not-namespaced":true}}"#,
594            r#"{"features":{"app.pi-chat":"true"}}"#,
595        ] {
596            let file = dir.path().join(format!("{}.json", source.len()));
597            fs::write(&file, source).unwrap();
598            assert!(matches!(
599                SettingsFile::open(&file),
600                Err(SettingsError::Invalid)
601            ));
602        }
603    }
604
605    #[test]
606    fn replaces_and_clears_tokens_without_retaining_secret() {
607        let dir = tempfile::tempdir().unwrap();
608        let file = dir.path().join("config.json");
609        fs::write(&file, source()).unwrap();
610        let mut editor = SettingsFile::open(&file).unwrap();
611        let mut edited = editor.values().clone();
612        edited.github_token = TokenEdit::Replace(Secret::new("replacement"));
613        editor.save(&edited).unwrap();
614        assert_eq!(json(&file)["github"]["token"], "replacement");
615        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
616        edited = editor.values().clone();
617        edited.github_token = TokenEdit::Clear;
618        editor.save(&edited).unwrap();
619        assert!(json(&file)["github"].get("token").is_none());
620        assert!(matches!(editor.values().github_token, TokenEdit::Keep));
621    }
622
623    #[test]
624    fn distinguishes_missing_empty_and_externally_created_files() {
625        let dir = tempfile::tempdir().unwrap();
626        let missing = dir.path().join("missing.json");
627        let mut editor = SettingsFile::open(&missing).unwrap();
628        fs::write(&missing, "").unwrap();
629        assert!(matches!(editor.save(&values()), Err(SettingsError::Stale)));
630        assert!(matches!(
631            SettingsFile::open(&missing),
632            Err(SettingsError::Json(_))
633        ));
634        let empty = dir.path().join("empty.json");
635        fs::write(&empty, "").unwrap();
636        assert!(matches!(
637            SettingsFile::open(&empty),
638            Err(SettingsError::Json(_))
639        ));
640    }
641
642    #[test]
643    fn detects_deleted_files_as_stale() {
644        let dir = tempfile::tempdir().unwrap();
645        let file = dir.path().join("config.json");
646        fs::write(&file, "{}").unwrap();
647        let mut editor = SettingsFile::open(&file).unwrap();
648        fs::remove_file(&file).unwrap();
649        assert!(matches!(editor.save(&values()), Err(SettingsError::Stale)));
650    }
651
652    #[test]
653    fn invalid_edits_are_safe_and_leave_original_bytes() {
654        let dir = tempfile::tempdir().unwrap();
655        let file = dir.path().join("config.json");
656        fs::write(&file, source()).unwrap();
657        let original = fs::read(&file).unwrap();
658        let mut editor = SettingsFile::open(&file).unwrap();
659        let mut invalid = editor.values().clone();
660        invalid.github_token = TokenEdit::Replace(Secret::new(""));
661        assert!(matches!(
662            editor.save(&invalid),
663            Err(SettingsError::Validation { .. })
664        ));
665        assert_eq!(fs::read(&file).unwrap(), original);
666        invalid = editor.values().clone();
667        invalid.repos = vec!["not a repo".into()];
668        assert!(matches!(
669            editor.save(&invalid),
670            Err(SettingsError::Validation { .. })
671        ));
672        assert_eq!(fs::read(&file).unwrap(), original);
673    }
674
675    #[cfg(unix)]
676    #[test]
677    fn new_and_existing_files_are_private_and_loadable() {
678        use std::os::unix::fs::PermissionsExt;
679        let dir = tempfile::tempdir().unwrap();
680        let existing = dir.path().join("existing.json");
681        fs::write(&existing, r#"{"github":{"token":"old"}}"#).unwrap();
682        fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
683        let mut existing_editor = SettingsFile::open(&existing).unwrap();
684        let existing_values = existing_editor.values().clone();
685        existing_editor.save(&existing_values).unwrap();
686        assert_eq!(
687            fs::metadata(&existing).unwrap().permissions().mode() & 0o777,
688            0o600
689        );
690        assert_eq!(
691            crate::config::load(&existing)
692                .0
693                .github
694                .token
695                .unwrap()
696                .expose(),
697            "old"
698        );
699        let new_file = dir.path().join("new.json");
700        let mut new_editor = SettingsFile::open(&new_file).unwrap();
701        let mut new_values = values();
702        new_values.github_token = TokenEdit::Replace(Secret::new("new"));
703        new_editor.save(&new_values).unwrap();
704        assert_eq!(
705            fs::metadata(&new_file).unwrap().permissions().mode() & 0o777,
706            0o600
707        );
708        assert_eq!(
709            crate::config::load(&new_file)
710                .0
711                .github
712                .token
713                .unwrap()
714                .expose(),
715            "new"
716        );
717    }
718}