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    /// Keys and values saved under a Space's former id are read as the
237    /// Space's own (see [`crate::former_ids`]); the file is not changed.
238    pub fn load(file: &Path) -> Self {
239        Self::load_with(file, &crate::former_ids::installed())
240    }
241
242    /// As [`State::load`], with the former ids `renames`.
243    pub(crate) fn load_with(file: &Path, renames: &crate::former_ids::Renames) -> Self {
244        let mut state = read_state(file);
245        state.rename_board_ids(renames);
246        state
247    }
248
249    /// Moves the keys and values saved under a former Space id in `renames`
250    /// to the Space's id (see [`crate::former_ids`]). A key the Space's id
251    /// already has wins, and the former key is dropped. True when anything
252    /// changed.
253    pub(crate) fn rename_board_ids(&mut self, renames: &crate::former_ids::Renames) -> bool {
254        let keys =
255            crate::former_ids::state_moves(self.values.keys().chain(self.invalid.keys()), renames);
256        let values = self.renamed_values(renames);
257        let changed = !keys.is_empty() || !values.is_empty();
258        self.move_keys(keys);
259        self.values.extend(values);
260        changed
261    }
262
263    /// The string values that name a former Space id, under their keys.
264    fn renamed_values(&self, renames: &crate::former_ids::Renames) -> Vec<(String, String)> {
265        self.values
266            .iter()
267            .filter_map(|(key, value)| {
268                Some((
269                    key.clone(),
270                    crate::former_ids::renamed_value(key, value, renames)?,
271                ))
272            })
273            .collect()
274    }
275
276    /// Moves each `(from, to)` key, a string or a raw JSON value alike,
277    /// unless `to` already holds a value; `from` is removed either way.
278    fn move_keys(&mut self, moves: Vec<(String, String)>) {
279        for (from, to) in moves {
280            let text = self.values.remove(&from);
281            let raw = self.invalid.remove(&from);
282            if self.values.contains_key(&to) || self.invalid.contains_key(&to) {
283                continue;
284            }
285            if let Some(text) = text {
286                self.values.insert(to, text);
287            } else if let Some(raw) = raw {
288                self.invalid.insert(to, raw);
289            }
290        }
291    }
292
293    /// The string value of `key`. `None` for a missing key and for a key
294    /// whose stored value is not a string: use [`State::has_invalid_value`]
295    /// to tell them apart before calling [`State::set`].
296    pub fn get(&self, key: &str) -> Option<&str> {
297        self.values.get(key).map(String::as_str)
298    }
299
300    /// True when the file holds a non-string value for `key` that has not
301    /// been replaced or removed. A caller that must not overwrite unreadable
302    /// data skips [`State::set`] while this is true; calling [`State::set`] or
303    /// [`State::remove`] is the explicit reset.
304    pub fn has_invalid_value(&self, key: &str) -> bool {
305        self.invalid.contains_key(key)
306    }
307
308    /// Stores `value`, replacing any value, including an invalid one.
309    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
310        let key = key.into();
311        self.invalid.remove(&key);
312        self.values.insert(key, value.into());
313    }
314
315    /// Deletes `key`, including an invalid value.
316    pub fn remove(&mut self, key: &str) {
317        self.invalid.remove(key);
318        self.values.remove(key);
319    }
320
321    fn document(&self) -> BTreeMap<&str, Entry<'_>> {
322        let kept = self
323            .invalid
324            .iter()
325            .map(|(key, raw)| (key.as_str(), Entry::Raw(raw)));
326        let strings = self
327            .values
328            .iter()
329            .map(|(key, text)| (key.as_str(), Entry::Text(text.as_str())));
330        kept.chain(strings).collect()
331    }
332
333    /// Writes the file atomically: a temporary file in the same directory,
334    /// then a rename over the old file. Invalid entries read by
335    /// [`State::load`] are written back with their exact JSON text. A current
336    /// file that is not a JSON object, or that differs from this state after
337    /// a failed load, is copied aside first (see [`State::load`]). The first
338    /// successful save after a failed load ends the check, so later saves
339    /// make no more copies.
340    pub fn save(&self, file: &Path) -> io::Result<()> {
341        let dir = file.parent().ok_or_else(|| {
342            io::Error::new(
343                io::ErrorKind::InvalidInput,
344                "the state file has no directory",
345            )
346        })?;
347        fs::create_dir_all(dir)?;
348        keep_unreadable_file(file, self.load_failed.is_set().then_some(self))?;
349        let mut temp = tempfile::NamedTempFile::new_in(dir)?;
350        serde_json::to_writer_pretty(&mut temp, &self.document())?;
351        temp.write_all(b"\n")?;
352        temp.as_file().sync_all()?;
353        temp.persist(file).map_err(|error| error.error)?;
354        self.load_failed.clear();
355        Ok(())
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use std::fs;
362
363    use subspace_product::Channel;
364
365    use super::{State, directory_name};
366
367    #[test]
368    fn the_core_state_of_a_process_that_names_nothing_is_under_subspace() {
369        assert_eq!(directory_name(), Channel::current().name("subspace"));
370    }
371
372    #[test]
373    fn values_survive_a_save_and_load() {
374        let dir = tempfile::tempdir().unwrap();
375        let file = dir.path().join("subspace").join("state.json");
376        let mut state = State::default();
377        state.set("board.layout", "board");
378        state.set("github.collapsed", r#"["mine"]"#);
379        state.save(&file).unwrap();
380
381        state.set("board.layout", "list");
382        state.remove("github.collapsed");
383        state.save(&file).unwrap();
384
385        let loaded = State::load(&file);
386        assert_eq!(loaded, state);
387        assert_eq!(loaded.get("board.layout"), Some("list"));
388        assert_eq!(loaded.get("github.collapsed"), None);
389        // Only the state file is left: the temporary file was renamed.
390        assert_eq!(fs::read_dir(file.parent().unwrap()).unwrap().count(), 1);
391    }
392
393    #[test]
394    fn write_atomic_replaces_the_file() {
395        let dir = tempfile::tempdir().unwrap();
396        let file = dir.path().join("sub").join("cache.json");
397        super::write_atomic(&file, "one").unwrap();
398        super::write_atomic(&file, "two").unwrap();
399        assert_eq!(fs::read_to_string(&file).unwrap(), "two");
400        assert_eq!(fs::read_dir(file.parent().unwrap()).unwrap().count(), 1);
401    }
402
403    #[cfg(unix)]
404    #[test]
405    fn atomic_cache_replaces_permissive_files_with_private_files() {
406        use std::os::unix::fs::PermissionsExt as _;
407        let dir = tempfile::tempdir().unwrap();
408        let file = dir.path().join("cache.json");
409        fs::write(&file, "old").unwrap();
410        fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
411        super::write_atomic(&file, "private").unwrap();
412        assert_eq!(
413            fs::metadata(file).unwrap().permissions().mode() & 0o777,
414            0o600
415        );
416    }
417
418    #[test]
419    fn a_missing_or_broken_file_gives_the_defaults_and_is_replaced() {
420        let dir = tempfile::tempdir().unwrap();
421        let file = dir.path().join("state.json");
422        assert_eq!(State::load(&file), State::default());
423
424        fs::write(&file, "{ broken").unwrap();
425        let mut state = State::load(&file);
426        assert!(state.values.is_empty() && state.invalid.is_empty());
427        state.set("wrap", "true");
428        state.save(&file).unwrap();
429        assert_eq!(State::load(&file).get("wrap"), Some("true"));
430    }
431
432    fn saved_json(file: &std::path::Path) -> serde_json::Value {
433        serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap()
434    }
435
436    #[test]
437    fn a_non_string_entry_is_kept_and_other_values_stay_usable() {
438        let dir = tempfile::tempdir().unwrap();
439        let file = dir.path().join("state.json");
440        fs::write(
441            &file,
442            r#"{"wrap":"true","example.dock-layout":{"version":1},"count":3}"#,
443        )
444        .unwrap();
445
446        let mut state = State::load(&file);
447        assert_eq!(state.get("wrap"), Some("true"));
448        assert_eq!(state.get("example.dock-layout"), None);
449        assert!(state.has_invalid_value("example.dock-layout"));
450        assert!(state.has_invalid_value("count"));
451        assert!(!state.has_invalid_value("wrap"));
452        assert!(!state.has_invalid_value("missing"));
453
454        state.set("board.layout", "list");
455        state.save(&file).unwrap();
456
457        assert_eq!(
458            saved_json(&file),
459            serde_json::json!({
460                "wrap": "true",
461                "board.layout": "list",
462                "example.dock-layout": {"version": 1},
463                "count": 3,
464            })
465        );
466        assert!(State::load(&file).has_invalid_value("example.dock-layout"));
467        // A readable file needs no copy.
468        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
469    }
470
471    #[test]
472    fn set_and_remove_explicitly_replace_a_non_string_entry() {
473        let dir = tempfile::tempdir().unwrap();
474        let file = dir.path().join("state.json");
475        fs::write(&file, r#"{"a":[1],"b":null,"keep":"yes"}"#).unwrap();
476
477        let mut state = State::load(&file);
478        state.set("a", "reset");
479        state.remove("b");
480        assert!(!state.has_invalid_value("a"));
481        assert!(!state.has_invalid_value("b"));
482        assert_eq!(state.get("a"), Some("reset"));
483        state.save(&file).unwrap();
484
485        assert_eq!(
486            saved_json(&file),
487            serde_json::json!({"a": "reset", "keep": "yes"})
488        );
489    }
490
491    #[test]
492    fn a_file_that_is_not_a_json_object_is_copied_aside_before_it_is_replaced() {
493        for broken in ["{ broken", "[\"not\",\"an object\"]"] {
494            let dir = tempfile::tempdir().unwrap();
495            let file = dir.path().join("state.json");
496            fs::write(&file, broken).unwrap();
497
498            let mut state = State::load(&file);
499            assert!(state.values.is_empty() && state.invalid.is_empty());
500            state.set("wrap", "true");
501            state.save(&file).unwrap();
502
503            assert_eq!(State::load(&file).get("wrap"), Some("true"));
504            assert_eq!(copy_contents(dir.path()), [broken]);
505        }
506    }
507
508    /// The contents of the `state.json.invalid-*` copies in `dir`, oldest name first.
509    fn copy_contents(dir: &std::path::Path) -> Vec<String> {
510        let mut copies: Vec<_> = fs::read_dir(dir)
511            .unwrap()
512            .map(|entry| entry.unwrap().path())
513            .filter(|path| {
514                path.file_name()
515                    .and_then(|name| name.to_str())
516                    .is_some_and(|name| name.starts_with("state.json.invalid-"))
517            })
518            .collect();
519        copies.sort();
520        copies
521            .iter()
522            .map(|path| fs::read_to_string(path).unwrap())
523            .collect()
524    }
525
526    #[test]
527    fn a_file_unreadable_at_load_but_valid_at_save_is_copied_before_it_is_replaced() {
528        let dir = tempfile::tempdir().unwrap();
529        let file = dir.path().join("state.json");
530        // Reading a directory fails with an error other than "not found".
531        fs::create_dir(&file).unwrap();
532        let mut state = State::load(&file);
533        assert!(state.values.is_empty() && state.invalid.is_empty());
534        fs::remove_dir(&file).unwrap();
535        let original = r#"{"keep":"yes","count":3}"#;
536        fs::write(&file, original).unwrap();
537
538        state.set("a", "b");
539        state.save(&file).unwrap();
540        assert_eq!(saved_json(&file), serde_json::json!({"a": "b"}));
541        assert_eq!(copy_contents(dir.path()), [original]);
542
543        // Saving the same document again loses nothing: no further copy.
544        state.save(&file).unwrap();
545        assert_eq!(copy_contents(dir.path()), [original]);
546
547        // The first successful save ended the check: later changes make no copy.
548        state.set("a", "c");
549        state.save(&file).unwrap();
550        assert_eq!(saved_json(&file), serde_json::json!({"a": "c"}));
551        assert_eq!(copy_contents(dir.path()), [original]);
552    }
553
554    #[test]
555    fn non_string_entries_keep_their_exact_json_text() {
556        let dir = tempfile::tempdir().unwrap();
557        let file = dir.path().join("state.json");
558        let numbers = [
559            "18446744073709551617",
560            "-9223372036854775809",
561            "1.000000000000000000001",
562            "0.1000000000000000055511151231257827",
563        ];
564        fs::write(
565            &file,
566            format!(
567                r#"{{"u":{},"i":{},"d":{},"f":{},"nested":{{"n":{}}},"keep":"x"}}"#,
568                numbers[0], numbers[1], numbers[2], numbers[3], numbers[0]
569            ),
570        )
571        .unwrap();
572
573        let mut state = State::load(&file);
574        assert!(state.has_invalid_value("u"));
575        state.set("other", "y");
576        state.save(&file).unwrap();
577
578        let saved = fs::read_to_string(&file).unwrap();
579        for number in numbers {
580            assert!(saved.contains(number), "{number} missing from {saved}");
581        }
582        assert!(saved.contains(&format!(r#"{{"n":{}}}"#, numbers[0])));
583        assert_eq!(State::load(&file), state);
584        // The file was already valid: no copy.
585        assert!(copy_contents(dir.path()).is_empty());
586    }
587
588    #[test]
589    fn only_json_whitespace_makes_a_file_blank() {
590        for content in ["\u{c}", "\u{b}", " \u{c}\n", "\u{b}\t"] {
591            let dir = tempfile::tempdir().unwrap();
592            let file = dir.path().join("state.json");
593            fs::write(&file, content).unwrap();
594
595            let mut state = State::load(&file);
596            state.set("a", "b");
597            state.save(&file).unwrap();
598
599            assert_eq!(copy_contents(dir.path()), [content]);
600        }
601        for content in [" ", "\t\r\n ", ""] {
602            let dir = tempfile::tempdir().unwrap();
603            let file = dir.path().join("state.json");
604            fs::write(&file, content).unwrap();
605            State::load(&file).save(&file).unwrap();
606            assert!(copy_contents(dir.path()).is_empty());
607        }
608    }
609
610    #[test]
611    fn a_normal_load_never_makes_a_copy() {
612        for content in [None, Some(""), Some(" \n"), Some(r#"{"a":"1","n":2}"#)] {
613            let dir = tempfile::tempdir().unwrap();
614            let file = dir.path().join("state.json");
615            if let Some(content) = content {
616                fs::write(&file, content).unwrap();
617            }
618            let mut state = State::load(&file);
619            state.set("a", "x");
620            state.save(&file).unwrap();
621            state.set("a", "y");
622            state.save(&file).unwrap();
623
624            assert!(copy_contents(dir.path()).is_empty());
625            assert_eq!(State::load(&file).get("a"), Some("y"));
626        }
627    }
628
629    #[test]
630    fn successive_copies_never_replace_an_earlier_copy() {
631        let dir = tempfile::tempdir().unwrap();
632        let file = dir.path().join("state.json");
633        for broken in ["{ first", "{ second", "{ third"] {
634            fs::write(&file, broken).unwrap();
635            // The same stamp each time forces the name collision.
636            super::keep_unreadable_file_stamped(&file, 7, None).unwrap();
637        }
638        for (index, broken) in ["{ first", "{ second", "{ third"].into_iter().enumerate() {
639            let copy = dir.path().join(format!("state.json.invalid-7-{index}"));
640            assert_eq!(fs::read_to_string(copy).unwrap(), broken);
641        }
642        // The state file and three copies; no temporary file is left.
643        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 4);
644    }
645
646    #[cfg(unix)]
647    #[test]
648    fn a_copy_is_private() {
649        use std::os::unix::fs::PermissionsExt as _;
650        let dir = tempfile::tempdir().unwrap();
651        let file = dir.path().join("state.json");
652        fs::write(&file, "{ broken").unwrap();
653        fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
654        super::keep_unreadable_file_stamped(&file, 1, None).unwrap();
655        let copy = dir.path().join("state.json.invalid-1-0");
656        assert_eq!(
657            fs::metadata(copy).unwrap().permissions().mode() & 0o777,
658            0o600
659        );
660    }
661
662    #[test]
663    fn a_file_that_cannot_be_inspected_is_not_treated_as_missing() {
664        let dir = tempfile::tempdir().unwrap();
665        // Reading a directory fails with an error other than "not found".
666        let file = dir.path().join("state.json");
667        fs::create_dir(&file).unwrap();
668        assert!(super::keep_unreadable_file(&file, None).is_err());
669        assert!(State::default().save(&file).is_err());
670        assert!(file.is_dir());
671
672        let missing = dir.path().join("absent.json");
673        assert!(super::keep_unreadable_file(&missing, None).is_ok());
674    }
675
676    #[cfg(unix)]
677    #[test]
678    fn a_failed_copy_fails_the_save_and_keeps_the_file() {
679        use std::os::unix::fs::PermissionsExt as _;
680        let dir = tempfile::tempdir().unwrap();
681        let file = dir.path().join("state.json");
682        fs::write(&file, "{ broken").unwrap();
683        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o500)).unwrap();
684
685        // Running as root ignores directory permissions: nothing to prove.
686        let can_write = tempfile::NamedTempFile::new_in(dir.path()).is_ok();
687        let result = State::default().save(&file);
688        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o700)).unwrap();
689
690        if !can_write {
691            assert!(result.is_err());
692            assert_eq!(fs::read_to_string(&file).unwrap(), "{ broken");
693        }
694    }
695}