Skip to main content

subspace_core/
state.rs

1//! The state file (REQ-08): UI choices kept between runs. Keys are
2//! namespaced `<dashboard>.<name>`, such as `board.layout`. Values are
3//! strings; structured values are JSON text.
4
5use std::collections::BTreeMap;
6use std::fs;
7use std::io::{self, Write};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10
11use serde::Serialize;
12use serde_json::value::RawValue;
13
14/// `<directory>/state.json` in the platform state directory:
15/// `$XDG_STATE_HOME` on Linux, the local data directory elsewhere
16/// (Application Support on macOS, `%LOCALAPPDATA%` on Windows).
17/// [`directory_name`] gives the directory.
18pub fn path() -> Option<PathBuf> {
19    dirs::state_dir()
20        .or_else(dirs::data_local_dir)
21        .map(|dir| dir.join(directory_name()).join("state.json"))
22}
23
24/// The data directory name, [`subspace_product::product_data_name`]: the
25/// app's data name on stable, `<name>-<type>` for a pre-release type. The
26/// data name is the one the app set with
27/// [`subspace_product::configure_data_name`], else its binary name, which
28/// `launch`, `prepare_context` and `record_new_install_theme` set; a
29/// process that reads a path before any of them uses `subspace`. Config,
30/// state, caches and logs use it, and so do the Keychain service
31/// `<data name>.github` and any service an app derives from this name.
32pub fn directory_name() -> String {
33    subspace_product::product_data_name()
34}
35
36/// `name` beside the state file, such as `github-cache.json`. Large
37/// caches live in files of their own, so `state.json` stays small.
38pub fn sibling(name: &str) -> Option<PathBuf> {
39    path().and_then(|state| Some(state.parent()?.join(name)))
40}
41
42/// Writes `text` to `file` atomically: a temporary file in the same
43/// directory, then a rename over the old file.
44pub fn write_atomic(file: &Path, text: &str) -> io::Result<()> {
45    let dir = file
46        .parent()
47        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the file has no directory"))?;
48    fs::create_dir_all(dir)?;
49    let mut temp = tempfile::NamedTempFile::new_in(dir)?;
50    crate::private_file::set_owner_only(temp.path())?;
51    temp.write_all(text.as_bytes())?;
52    temp.as_file().sync_all()?;
53    temp.persist(file).map_err(|error| error.error)?;
54    Ok(())
55}
56
57/// True for bytes that hold only JSON whitespace (RFC 8259: space, tab,
58/// carriage return, line feed). Form feed and vertical tab are not JSON
59/// whitespace, so a file that holds only those is not blank.
60fn is_blank(bytes: &[u8]) -> bool {
61    bytes
62        .iter()
63        .all(|&byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n'))
64}
65
66/// The exact JSON text of a value that is not a string, so a save writes
67/// back every digit and is not limited to `f64` or `u64`/`i64`.
68#[derive(Debug, Clone, Serialize)]
69#[serde(transparent)]
70struct RawJson(Box<RawValue>);
71
72impl PartialEq for RawJson {
73    fn eq(&self, other: &Self) -> bool {
74        self.0.get() == other.0.get()
75    }
76}
77
78impl Eq for RawJson {}
79
80/// One value of the document that [`State::save`] writes.
81#[derive(Serialize)]
82#[serde(untagged)]
83enum Entry<'a> {
84    Text(&'a str),
85    Raw(&'a RawJson),
86}
87
88/// Whether [`State::load`] found a file it could not use, until a save
89/// succeeds. Interior mutability lets `save(&self)` clear it. It is not part
90/// of a state's equality.
91#[derive(Debug, Default)]
92struct LoadFailed(AtomicBool);
93
94impl LoadFailed {
95    fn new(failed: bool) -> Self {
96        Self(AtomicBool::new(failed))
97    }
98
99    fn is_set(&self) -> bool {
100        self.0.load(Ordering::Relaxed)
101    }
102
103    fn clear(&self) {
104        self.0.store(false, Ordering::Relaxed);
105    }
106}
107
108impl Clone for LoadFailed {
109    fn clone(&self) -> Self {
110        Self::new(self.is_set())
111    }
112}
113
114impl PartialEq for LoadFailed {
115    fn eq(&self, _: &Self) -> bool {
116        true
117    }
118}
119
120impl Eq for LoadFailed {}
121
122/// The state in the JSON object `bytes`, or `None` when they are not one.
123/// A string value is a usable value; every other value is kept as raw JSON.
124fn parse_state(bytes: &[u8]) -> Option<State> {
125    let fields: BTreeMap<String, Box<RawValue>> = serde_json::from_slice(bytes).ok()?;
126    let mut state = State::default();
127    for (key, raw) in fields {
128        if let Ok(text) = serde_json::from_str::<String>(raw.get()) {
129            state.values.insert(key, text);
130        } else {
131            state.invalid.insert(key, RawJson(raw));
132        }
133    }
134    Some(state)
135}
136
137/// The state of the file. A missing or blank file is a normal first run. A
138/// read error other than "not found", or content that is not a JSON object,
139/// gives an empty state with the failure recorded.
140fn read_state(file: &Path) -> State {
141    let unusable = |failed: bool| State {
142        load_failed: LoadFailed::new(failed),
143        ..State::default()
144    };
145    match fs::read(file) {
146        Ok(bytes) => parse_state(&bytes).unwrap_or_else(|| unusable(!is_blank(&bytes))),
147        Err(error) if error.kind() == io::ErrorKind::NotFound => State::default(),
148        Err(_) => unusable(true),
149    }
150}
151
152/// Copies the current state file to `<name>.invalid-<unix seconds>-<n>`
153/// beside it, so a save cannot destroy it, when it is not a JSON object or,
154/// given `unless_equal` (the state about to be saved), when it holds
155/// anything else. A missing or blank file needs no copy. Any other failure to
156/// read the file, or to write the copy, is an error and the caller must not
157/// replace the file.
158fn keep_unreadable_file(file: &Path, unless_equal: Option<&State>) -> io::Result<()> {
159    let seconds = std::time::SystemTime::now()
160        .duration_since(std::time::UNIX_EPOCH)
161        .map_or(0, |elapsed| elapsed.as_secs());
162    keep_unreadable_file_stamped(file, seconds, unless_equal)
163}
164
165fn keep_unreadable_file_stamped(
166    file: &Path,
167    stamp: u64,
168    unless_equal: Option<&State>,
169) -> io::Result<()> {
170    let bytes = match fs::read(file) {
171        Ok(bytes) => bytes,
172        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
173        Err(error) => return Err(error),
174    };
175    let nothing_to_lose = parse_state(&bytes)
176        .is_some_and(|current| unless_equal.is_none_or(|state| *state == current));
177    if is_blank(&bytes) || nothing_to_lose {
178        return Ok(());
179    }
180    let dir = file
181        .parent()
182        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the file has no directory"))?;
183    let name = file.file_name().unwrap_or_default().to_string_lossy();
184    // Written and synced under a private temporary name, then linked to the
185    // first free `<name>.invalid-<stamp>-<n>`: an earlier copy is never replaced.
186    let mut temp = tempfile::NamedTempFile::new_in(dir)?;
187    crate::private_file::set_owner_only(temp.path())?;
188    temp.write_all(&bytes)?;
189    temp.as_file().sync_all()?;
190    for attempt in 0_u32.. {
191        let copy = dir.join(format!("{name}.invalid-{stamp}-{attempt}"));
192        match temp.persist_noclobber(&copy) {
193            Ok(_) => return Ok(()),
194            Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {
195                temp = error.file;
196            }
197            Err(error) => return Err(error.error),
198        }
199    }
200    Err(io::Error::new(
201        io::ErrorKind::AlreadyExists,
202        "no free name for the state file copy",
203    ))
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Default)]
207pub struct State {
208    values: BTreeMap<String, String>,
209    /// File entries whose value is not a string. They are not readable
210    /// through [`State::get`], but [`State::save`] writes them back
211    /// with their exact JSON text until [`State::set`] or [`State::remove`]
212    /// replaces them.
213    invalid: BTreeMap<String, RawJson>,
214    /// [`State::load`] found a file it could not use. Until a save succeeds,
215    /// [`State::save`] keeps a copy of any different file it finds on disk.
216    /// Ignored by equality.
217    load_failed: LoadFailed,
218}
219
220impl State {
221    /// Reads the state file. A missing or unreadable file gives the defaults.
222    /// An entry whose value is not a string is kept apart (see
223    /// [`State::has_invalid_value`]) and does not affect the other entries.
224    /// A file that cannot be used gives the defaults: a read error other than
225    /// "not found", or content that is not a JSON object. A missing or blank
226    /// file is a normal first run. After an unusable file, the next
227    /// [`State::save`] first copies whatever file it finds, unless it already
228    /// holds exactly the document to save, to
229    /// `<name>.invalid-<unix seconds>-<n>`. That covers a file that was
230    /// malformed, and one that was only unreadable or half-written at load
231    /// time and is valid by the time of the save. [`State::save`] fails,
232    /// without replacing the file, if it cannot read the file or write the
233    /// copy. Only space, tab, carriage return and line feed count as blank.
234    /// A non-string value keeps its exact JSON text, such as a number with
235    /// more digits than `u64` or `f64` hold.
236    pub fn load(file: &Path) -> Self {
237        read_state(file)
238    }
239
240    /// The string value of `key`. `None` for a missing key and for a key
241    /// whose stored value is not a string: use [`State::has_invalid_value`]
242    /// to tell them apart before calling [`State::set`].
243    pub fn get(&self, key: &str) -> Option<&str> {
244        self.values.get(key).map(String::as_str)
245    }
246
247    /// True when the file holds a non-string value for `key` that has not
248    /// been replaced or removed. A caller that must not overwrite unreadable
249    /// data skips [`State::set`] while this is true; calling [`State::set`] or
250    /// [`State::remove`] is the explicit reset.
251    pub fn has_invalid_value(&self, key: &str) -> bool {
252        self.invalid.contains_key(key)
253    }
254
255    /// Stores `value`, replacing any value, including an invalid one.
256    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
257        let key = key.into();
258        self.invalid.remove(&key);
259        self.values.insert(key, value.into());
260    }
261
262    /// Deletes `key`, including an invalid value.
263    pub fn remove(&mut self, key: &str) {
264        self.invalid.remove(key);
265        self.values.remove(key);
266    }
267
268    fn document(&self) -> BTreeMap<&str, Entry<'_>> {
269        let kept = self
270            .invalid
271            .iter()
272            .map(|(key, raw)| (key.as_str(), Entry::Raw(raw)));
273        let strings = self
274            .values
275            .iter()
276            .map(|(key, text)| (key.as_str(), Entry::Text(text.as_str())));
277        kept.chain(strings).collect()
278    }
279
280    /// Writes the file atomically: a temporary file in the same directory,
281    /// then a rename over the old file. Invalid entries read by
282    /// [`State::load`] are written back with their exact JSON text. A current
283    /// file that is not a JSON object, or that differs from this state after
284    /// a failed load, is copied aside first (see [`State::load`]). The first
285    /// successful save after a failed load ends the check, so later saves
286    /// make no more copies.
287    pub fn save(&self, file: &Path) -> io::Result<()> {
288        let dir = file.parent().ok_or_else(|| {
289            io::Error::new(
290                io::ErrorKind::InvalidInput,
291                "the state file has no directory",
292            )
293        })?;
294        fs::create_dir_all(dir)?;
295        keep_unreadable_file(file, self.load_failed.is_set().then_some(self))?;
296        let mut temp = tempfile::NamedTempFile::new_in(dir)?;
297        serde_json::to_writer_pretty(&mut temp, &self.document())?;
298        temp.write_all(b"\n")?;
299        temp.as_file().sync_all()?;
300        temp.persist(file).map_err(|error| error.error)?;
301        self.load_failed.clear();
302        Ok(())
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use std::fs;
309
310    use subspace_product::Channel;
311
312    use super::{State, directory_name};
313
314    #[test]
315    fn the_core_state_of_a_process_that_names_nothing_is_under_subspace() {
316        assert_eq!(directory_name(), Channel::current().name("subspace"));
317    }
318
319    #[test]
320    fn values_survive_a_save_and_load() {
321        let dir = tempfile::tempdir().unwrap();
322        let file = dir.path().join("subspace").join("state.json");
323        let mut state = State::default();
324        state.set("board.layout", "board");
325        state.set("github.collapsed", r#"["mine"]"#);
326        state.save(&file).unwrap();
327
328        state.set("board.layout", "list");
329        state.remove("github.collapsed");
330        state.save(&file).unwrap();
331
332        let loaded = State::load(&file);
333        assert_eq!(loaded, state);
334        assert_eq!(loaded.get("board.layout"), Some("list"));
335        assert_eq!(loaded.get("github.collapsed"), None);
336        // Only the state file is left: the temporary file was renamed.
337        assert_eq!(fs::read_dir(file.parent().unwrap()).unwrap().count(), 1);
338    }
339
340    #[test]
341    fn write_atomic_replaces_the_file() {
342        let dir = tempfile::tempdir().unwrap();
343        let file = dir.path().join("sub").join("cache.json");
344        super::write_atomic(&file, "one").unwrap();
345        super::write_atomic(&file, "two").unwrap();
346        assert_eq!(fs::read_to_string(&file).unwrap(), "two");
347        assert_eq!(fs::read_dir(file.parent().unwrap()).unwrap().count(), 1);
348    }
349
350    #[cfg(unix)]
351    #[test]
352    fn atomic_cache_replaces_permissive_files_with_private_files() {
353        use std::os::unix::fs::PermissionsExt as _;
354        let dir = tempfile::tempdir().unwrap();
355        let file = dir.path().join("cache.json");
356        fs::write(&file, "old").unwrap();
357        fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
358        super::write_atomic(&file, "private").unwrap();
359        assert_eq!(
360            fs::metadata(file).unwrap().permissions().mode() & 0o777,
361            0o600
362        );
363    }
364
365    #[test]
366    fn a_missing_or_broken_file_gives_the_defaults_and_is_replaced() {
367        let dir = tempfile::tempdir().unwrap();
368        let file = dir.path().join("state.json");
369        assert_eq!(State::load(&file), State::default());
370
371        fs::write(&file, "{ broken").unwrap();
372        let mut state = State::load(&file);
373        assert!(state.values.is_empty() && state.invalid.is_empty());
374        state.set("wrap", "true");
375        state.save(&file).unwrap();
376        assert_eq!(State::load(&file).get("wrap"), Some("true"));
377    }
378
379    fn saved_json(file: &std::path::Path) -> serde_json::Value {
380        serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap()
381    }
382
383    #[test]
384    fn a_non_string_entry_is_kept_and_other_values_stay_usable() {
385        let dir = tempfile::tempdir().unwrap();
386        let file = dir.path().join("state.json");
387        fs::write(
388            &file,
389            r#"{"wrap":"true","example.dock-layout":{"version":1},"count":3}"#,
390        )
391        .unwrap();
392
393        let mut state = State::load(&file);
394        assert_eq!(state.get("wrap"), Some("true"));
395        assert_eq!(state.get("example.dock-layout"), None);
396        assert!(state.has_invalid_value("example.dock-layout"));
397        assert!(state.has_invalid_value("count"));
398        assert!(!state.has_invalid_value("wrap"));
399        assert!(!state.has_invalid_value("missing"));
400
401        state.set("board.layout", "list");
402        state.save(&file).unwrap();
403
404        assert_eq!(
405            saved_json(&file),
406            serde_json::json!({
407                "wrap": "true",
408                "board.layout": "list",
409                "example.dock-layout": {"version": 1},
410                "count": 3,
411            })
412        );
413        assert!(State::load(&file).has_invalid_value("example.dock-layout"));
414        // A readable file needs no copy.
415        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
416    }
417
418    #[test]
419    fn set_and_remove_explicitly_replace_a_non_string_entry() {
420        let dir = tempfile::tempdir().unwrap();
421        let file = dir.path().join("state.json");
422        fs::write(&file, r#"{"a":[1],"b":null,"keep":"yes"}"#).unwrap();
423
424        let mut state = State::load(&file);
425        state.set("a", "reset");
426        state.remove("b");
427        assert!(!state.has_invalid_value("a"));
428        assert!(!state.has_invalid_value("b"));
429        assert_eq!(state.get("a"), Some("reset"));
430        state.save(&file).unwrap();
431
432        assert_eq!(
433            saved_json(&file),
434            serde_json::json!({"a": "reset", "keep": "yes"})
435        );
436    }
437
438    #[test]
439    fn a_file_that_is_not_a_json_object_is_copied_aside_before_it_is_replaced() {
440        for broken in ["{ broken", "[\"not\",\"an object\"]"] {
441            let dir = tempfile::tempdir().unwrap();
442            let file = dir.path().join("state.json");
443            fs::write(&file, broken).unwrap();
444
445            let mut state = State::load(&file);
446            assert!(state.values.is_empty() && state.invalid.is_empty());
447            state.set("wrap", "true");
448            state.save(&file).unwrap();
449
450            assert_eq!(State::load(&file).get("wrap"), Some("true"));
451            assert_eq!(copy_contents(dir.path()), [broken]);
452        }
453    }
454
455    /// The contents of the `state.json.invalid-*` copies in `dir`, oldest name first.
456    fn copy_contents(dir: &std::path::Path) -> Vec<String> {
457        let mut copies: Vec<_> = fs::read_dir(dir)
458            .unwrap()
459            .map(|entry| entry.unwrap().path())
460            .filter(|path| {
461                path.file_name()
462                    .and_then(|name| name.to_str())
463                    .is_some_and(|name| name.starts_with("state.json.invalid-"))
464            })
465            .collect();
466        copies.sort();
467        copies
468            .iter()
469            .map(|path| fs::read_to_string(path).unwrap())
470            .collect()
471    }
472
473    #[test]
474    fn a_file_unreadable_at_load_but_valid_at_save_is_copied_before_it_is_replaced() {
475        let dir = tempfile::tempdir().unwrap();
476        let file = dir.path().join("state.json");
477        // Reading a directory fails with an error other than "not found".
478        fs::create_dir(&file).unwrap();
479        let mut state = State::load(&file);
480        assert!(state.values.is_empty() && state.invalid.is_empty());
481        fs::remove_dir(&file).unwrap();
482        let original = r#"{"keep":"yes","count":3}"#;
483        fs::write(&file, original).unwrap();
484
485        state.set("a", "b");
486        state.save(&file).unwrap();
487        assert_eq!(saved_json(&file), serde_json::json!({"a": "b"}));
488        assert_eq!(copy_contents(dir.path()), [original]);
489
490        // Saving the same document again loses nothing: no further copy.
491        state.save(&file).unwrap();
492        assert_eq!(copy_contents(dir.path()), [original]);
493
494        // The first successful save ended the check: later changes make no copy.
495        state.set("a", "c");
496        state.save(&file).unwrap();
497        assert_eq!(saved_json(&file), serde_json::json!({"a": "c"}));
498        assert_eq!(copy_contents(dir.path()), [original]);
499    }
500
501    #[test]
502    fn non_string_entries_keep_their_exact_json_text() {
503        let dir = tempfile::tempdir().unwrap();
504        let file = dir.path().join("state.json");
505        let numbers = [
506            "18446744073709551617",
507            "-9223372036854775809",
508            "1.000000000000000000001",
509            "0.1000000000000000055511151231257827",
510        ];
511        fs::write(
512            &file,
513            format!(
514                r#"{{"u":{},"i":{},"d":{},"f":{},"nested":{{"n":{}}},"keep":"x"}}"#,
515                numbers[0], numbers[1], numbers[2], numbers[3], numbers[0]
516            ),
517        )
518        .unwrap();
519
520        let mut state = State::load(&file);
521        assert!(state.has_invalid_value("u"));
522        state.set("other", "y");
523        state.save(&file).unwrap();
524
525        let saved = fs::read_to_string(&file).unwrap();
526        for number in numbers {
527            assert!(saved.contains(number), "{number} missing from {saved}");
528        }
529        assert!(saved.contains(&format!(r#"{{"n":{}}}"#, numbers[0])));
530        assert_eq!(State::load(&file), state);
531        // The file was already valid: no copy.
532        assert!(copy_contents(dir.path()).is_empty());
533    }
534
535    #[test]
536    fn only_json_whitespace_makes_a_file_blank() {
537        for content in ["\u{c}", "\u{b}", " \u{c}\n", "\u{b}\t"] {
538            let dir = tempfile::tempdir().unwrap();
539            let file = dir.path().join("state.json");
540            fs::write(&file, content).unwrap();
541
542            let mut state = State::load(&file);
543            state.set("a", "b");
544            state.save(&file).unwrap();
545
546            assert_eq!(copy_contents(dir.path()), [content]);
547        }
548        for content in [" ", "\t\r\n ", ""] {
549            let dir = tempfile::tempdir().unwrap();
550            let file = dir.path().join("state.json");
551            fs::write(&file, content).unwrap();
552            State::load(&file).save(&file).unwrap();
553            assert!(copy_contents(dir.path()).is_empty());
554        }
555    }
556
557    #[test]
558    fn a_normal_load_never_makes_a_copy() {
559        for content in [None, Some(""), Some(" \n"), Some(r#"{"a":"1","n":2}"#)] {
560            let dir = tempfile::tempdir().unwrap();
561            let file = dir.path().join("state.json");
562            if let Some(content) = content {
563                fs::write(&file, content).unwrap();
564            }
565            let mut state = State::load(&file);
566            state.set("a", "x");
567            state.save(&file).unwrap();
568            state.set("a", "y");
569            state.save(&file).unwrap();
570
571            assert!(copy_contents(dir.path()).is_empty());
572            assert_eq!(State::load(&file).get("a"), Some("y"));
573        }
574    }
575
576    #[test]
577    fn successive_copies_never_replace_an_earlier_copy() {
578        let dir = tempfile::tempdir().unwrap();
579        let file = dir.path().join("state.json");
580        for broken in ["{ first", "{ second", "{ third"] {
581            fs::write(&file, broken).unwrap();
582            // The same stamp each time forces the name collision.
583            super::keep_unreadable_file_stamped(&file, 7, None).unwrap();
584        }
585        for (index, broken) in ["{ first", "{ second", "{ third"].into_iter().enumerate() {
586            let copy = dir.path().join(format!("state.json.invalid-7-{index}"));
587            assert_eq!(fs::read_to_string(copy).unwrap(), broken);
588        }
589        // The state file and three copies; no temporary file is left.
590        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 4);
591    }
592
593    #[cfg(unix)]
594    #[test]
595    fn a_copy_is_private() {
596        use std::os::unix::fs::PermissionsExt as _;
597        let dir = tempfile::tempdir().unwrap();
598        let file = dir.path().join("state.json");
599        fs::write(&file, "{ broken").unwrap();
600        fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
601        super::keep_unreadable_file_stamped(&file, 1, None).unwrap();
602        let copy = dir.path().join("state.json.invalid-1-0");
603        assert_eq!(
604            fs::metadata(copy).unwrap().permissions().mode() & 0o777,
605            0o600
606        );
607    }
608
609    #[test]
610    fn a_file_that_cannot_be_inspected_is_not_treated_as_missing() {
611        let dir = tempfile::tempdir().unwrap();
612        // Reading a directory fails with an error other than "not found".
613        let file = dir.path().join("state.json");
614        fs::create_dir(&file).unwrap();
615        assert!(super::keep_unreadable_file(&file, None).is_err());
616        assert!(State::default().save(&file).is_err());
617        assert!(file.is_dir());
618
619        let missing = dir.path().join("absent.json");
620        assert!(super::keep_unreadable_file(&missing, None).is_ok());
621    }
622
623    #[cfg(unix)]
624    #[test]
625    fn a_failed_copy_fails_the_save_and_keeps_the_file() {
626        use std::os::unix::fs::PermissionsExt as _;
627        let dir = tempfile::tempdir().unwrap();
628        let file = dir.path().join("state.json");
629        fs::write(&file, "{ broken").unwrap();
630        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o500)).unwrap();
631
632        // Running as root ignores directory permissions: nothing to prove.
633        let can_write = tempfile::NamedTempFile::new_in(dir.path()).is_ok();
634        let result = State::default().save(&file);
635        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o700)).unwrap();
636
637        if !can_write {
638            assert!(result.is_err());
639            assert_eq!(fs::read_to_string(&file).unwrap(), "{ broken");
640        }
641    }
642}