Skip to main content

subspace_core/settings/
web_boards.rs

1//! Checked immediate web-board edits and narrow rebasing of an open editor.
2
3use super::{SettingsError, SettingsFile};
4use crate::config::web_boards::valid_web_board_id;
5use serde_json::{Map, Value};
6
7impl SettingsFile {
8    /// Raw native entry, including source provenance and unknown fields.
9    pub fn web_board(&self, id: &str) -> Option<Map<String, Value>> {
10        self.root
11            .get("webBoards")?
12            .as_object()?
13            .get(id)?
14            .as_object()
15            .cloned()
16    }
17
18    /// Immediately writes one complete entry, or unregisters it when absent.
19    /// The caller supplies the full raw entry to retain its existing fields.
20    /// Board enablement, ordering, other entries and unrelated JSON are untouched.
21    // qual:api
22    pub fn update_web_board(
23        &mut self,
24        id: &str,
25        entry: Option<Map<String, Value>>,
26    ) -> Result<(), SettingsError> {
27        if !valid_web_board_id(id) {
28            return Err(SettingsError::Validation {
29                field: "board id",
30                reason: "use a short lower-case name starting with a letter",
31            });
32        }
33        self.check_current()?;
34        let mut root = self.root.clone();
35        let boards = root
36            .entry("webBoards")
37            .or_insert_with(|| Value::Object(Map::new()));
38        let boards = boards.as_object_mut().ok_or(SettingsError::Invalid)?;
39        match entry {
40            Some(entry) => {
41                boards.insert(id.into(), Value::Object(entry));
42            }
43            None => {
44                boards.remove(id);
45            }
46        }
47        self.write_root(root)
48    }
49
50    /// Accepts immediate `webBoards` changes without accepting unrelated edits.
51    /// The caller retains its draft inputs. A conflict leaves this snapshot intact.
52    pub fn rebase_web_boards(&mut self) -> Result<(), SettingsError> {
53        let current = Self::open(&self.file)?;
54        validate_rebase(self, &current)?;
55        *self = current;
56        Ok(())
57    }
58}
59
60fn validate_rebase(previous: &SettingsFile, current: &SettingsFile) -> Result<(), SettingsError> {
61    let mut before = previous.root.clone();
62    let mut after = current.root.clone();
63    before.remove("webBoards");
64    after.remove("webBoards");
65    if before != after || (previous.original.is_some() && current.original.is_none()) {
66        return Err(SettingsError::Stale);
67    }
68    Ok(())
69}
70
71#[cfg(test)]
72mod tests {
73    use crate::settings::{SettingsError, SettingsFile};
74    use serde_json::{Map, Value, json};
75    use std::fs;
76
77    fn entry(value: Value) -> Map<String, Value> {
78        value.as_object().unwrap().clone()
79    }
80
81    #[test]
82    fn immediate_edits_preserve_raw_fields_order_enablement_and_secrets() {
83        let directory = tempfile::tempdir().unwrap();
84        let path = directory.path().join("config.json");
85        fs::write(&path, r#"{"webBoards":{"notes":{"url":"https://notes.example","settings":{"limit":7},"secrets":{"token":"test-only-not-working"},"sourceRecord":{"kind":"folder"}}},"boards":{"notes":false},"boardOrder":["notes"],"unknown":{"keep":true}}"#).unwrap();
86        let mut file = SettingsFile::open(&path).unwrap();
87        let mut notes = file.web_board("notes").unwrap();
88        notes.insert("title".into(), json!("New notes"));
89        file.update_web_board("notes", Some(notes)).unwrap();
90        file.update_web_board("wiki", Some(entry(json!({"url":"https://wiki.example"}))))
91            .unwrap();
92        let saved: Value = serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
93        assert_eq!(saved["webBoards"]["notes"]["settings"]["limit"], 7);
94        assert_eq!(
95            saved["webBoards"]["notes"]["secrets"]["token"],
96            "test-only-not-working"
97        );
98        assert_eq!(
99            saved["webBoards"]["notes"]["sourceRecord"]["kind"],
100            "folder"
101        );
102        assert_eq!(saved["boards"]["notes"], false);
103        assert_eq!(saved["boardOrder"], json!(["notes"]));
104        assert_eq!(saved["unknown"], json!({"keep":true}));
105        file.update_web_board("notes", None).unwrap();
106        assert!(file.web_board("notes").is_none());
107        assert!(file.web_board("wiki").is_some());
108    }
109
110    #[test]
111    fn invalid_and_stale_immediate_edits_do_not_write() {
112        let directory = tempfile::tempdir().unwrap();
113        let path = directory.path().join("config.json");
114        fs::write(&path, "{}").unwrap();
115        let mut file = SettingsFile::open(&path).unwrap();
116        assert!(
117            file.update_web_board("bad", Some(entry(json!({"url":"http://remote.example"}))))
118                .is_err()
119        );
120        assert_eq!(fs::read_to_string(&path).unwrap(), "{}");
121        fs::write(&path, r#"{"external":true}"#).unwrap();
122        assert!(matches!(
123            file.update_web_board("notes", Some(entry(json!({"url":"https://notes.example"})))),
124            Err(SettingsError::Stale)
125        ));
126        assert_eq!(fs::read_to_string(&path).unwrap(), r#"{"external":true}"#);
127    }
128
129    #[test]
130    fn rebase_keeps_a_dirty_draft_and_save_or_cancel_cannot_undo_immediate_edits() {
131        let directory = tempfile::tempdir().unwrap();
132        let path = directory.path().join("config.json");
133        fs::write(&path, r#"{"repos":["owner/original"]}"#).unwrap();
134        let mut editor = SettingsFile::open(&path).unwrap();
135        let mut draft = editor.values().clone();
136        draft.repos = vec!["owner/dirty".into()];
137        let mut manager = SettingsFile::open(&path).unwrap();
138        manager
139            .update_web_board("notes", Some(entry(json!({"url":"https://notes.example"}))))
140            .unwrap();
141        editor.rebase_web_boards().unwrap();
142        editor.save(&draft).unwrap();
143        assert!(
144            SettingsFile::open(&path)
145                .unwrap()
146                .web_board("notes")
147                .is_some()
148        );
149        assert_eq!(
150            SettingsFile::open(&path).unwrap().values().repos,
151            ["owner/dirty"]
152        );
153        let mut cancel = SettingsFile::open(&path).unwrap();
154        manager = SettingsFile::open(&path).unwrap();
155        manager.update_web_board("notes", None).unwrap();
156        cancel.rebase_web_boards().unwrap();
157        drop(cancel);
158        assert!(
159            SettingsFile::open(&path)
160                .unwrap()
161                .web_board("notes")
162                .is_none()
163        );
164    }
165
166    #[test]
167    fn rebase_refuses_unrelated_external_edits_without_accepting_the_new_snapshot() {
168        let directory = tempfile::tempdir().unwrap();
169        let path = directory.path().join("config.json");
170        fs::write(&path, "{}").unwrap();
171        let mut editor = SettingsFile::open(&path).unwrap();
172        fs::write(
173            &path,
174            r#"{"unknown":7,"webBoards":{"notes":{"url":"https://notes.example"}}}"#,
175        )
176        .unwrap();
177        assert!(matches!(
178            editor.rebase_web_boards(),
179            Err(SettingsError::Stale)
180        ));
181        assert!(editor.web_board("notes").is_none());
182        assert!(matches!(
183            editor.save(&editor.values().clone()),
184            Err(SettingsError::Stale)
185        ));
186    }
187}