Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
settings.rs

1//! A small JSON file in the app's data folder (the scope, the app's settings), read leniently and written atomically.
2//!
3//! A file that is missing or unreadable reads as the default: a damaged settings file never stops the app from opening.
4//! A write goes to a temporary file in the same folder, then a rename, so a crash mid-write never leaves half a file.
5
6use serde::de::DeserializeOwned;
7use serde::Serialize;
8use std::fmt;
9use std::fs;
10use std::io::Write;
11use std::path::Path;
12
13/// Why a settings file could not be written.
14#[derive(Debug)]
15pub enum SettingsError {
16    /// The path has no folder to write in.
17    NoFolder,
18    /// The path does not end in a file name.
19    NotAFileName,
20    /// Creating the folder, writing, syncing or renaming failed.
21    Io(std::io::Error),
22    /// The value cannot be written as JSON.
23    Encode(serde_json::Error),
24}
25
26impl SettingsError {
27    /// The stable code the page reads.
28    pub fn code(&self) -> &'static str {
29        match self {
30            SettingsError::NoFolder => "settings_no_folder",
31            SettingsError::NotAFileName => "settings_not_a_file_name",
32            SettingsError::Io(_) => "settings_io",
33            SettingsError::Encode(_) => "settings_encode",
34        }
35    }
36}
37
38impl fmt::Display for SettingsError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(match self {
41            SettingsError::NoFolder => "the settings path has no folder",
42            SettingsError::NotAFileName => "the settings path is not a file name",
43            SettingsError::Io(_) => "the settings file could not be written",
44            SettingsError::Encode(_) => "the settings could not be encoded",
45        })
46    }
47}
48
49impl std::error::Error for SettingsError {
50    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
51        match self {
52            SettingsError::Io(e) => Some(e),
53            SettingsError::Encode(e) => Some(e),
54            SettingsError::NoFolder | SettingsError::NotAFileName => None,
55        }
56    }
57}
58
59impl From<std::io::Error> for SettingsError {
60    fn from(error: std::io::Error) -> Self {
61        SettingsError::Io(error)
62    }
63}
64
65/// The value stored in `file`, or the default when the file is missing or is not that value.
66pub fn load<T: DeserializeOwned + Default>(file: &Path) -> T {
67    fs::read_to_string(file)
68        .ok()
69        .and_then(|raw| serde_json::from_str(&raw).ok())
70        .unwrap_or_default()
71}
72
73/// Writes `value` as pretty JSON, atomically (temporary file, `fsync`, rename), creating the folder if needed.
74pub fn save<T: Serialize>(file: &Path, value: &T) -> Result<(), SettingsError> {
75    let dir = file
76        .parent()
77        .filter(|d| !d.as_os_str().is_empty())
78        .ok_or(SettingsError::NoFolder)?;
79    fs::create_dir_all(dir)?;
80    let json = serde_json::to_string_pretty(value).map_err(SettingsError::Encode)?;
81    let name = file.file_name().ok_or(SettingsError::NotAFileName)?;
82    let temporary = dir.join(format!(".{}.tmp", name.to_string_lossy()));
83    {
84        let mut out = fs::File::create(&temporary)?;
85        out.write_all(json.as_bytes())?;
86        out.sync_all()?;
87    }
88    fs::rename(&temporary, file).map_err(|e| {
89        let _ = fs::remove_file(&temporary);
90        SettingsError::Io(e)
91    })
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use serde::Deserialize;
98    use tempfile::tempdir;
99
100    #[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
101    struct Prefs {
102        channel: String,
103        count: u32,
104    }
105
106    #[test]
107    fn a_saved_value_reads_back_and_leaves_no_temporary_file() {
108        let d = tempdir().unwrap();
109        let file = d.path().join("nested").join("settings.json");
110        let prefs = Prefs {
111            channel: "beta".into(),
112            count: 3,
113        };
114        save(&file, &prefs).unwrap();
115        assert_eq!(load::<Prefs>(&file), prefs);
116        let names: Vec<_> = fs::read_dir(file.parent().unwrap())
117            .unwrap()
118            .map(|e| e.unwrap().file_name())
119            .collect();
120        assert_eq!(names, vec![std::ffi::OsString::from("settings.json")]);
121    }
122
123    #[test]
124    fn a_missing_or_damaged_file_reads_as_the_default() {
125        let d = tempdir().unwrap();
126        assert_eq!(
127            load::<Prefs>(&d.path().join("missing.json")),
128            Prefs::default()
129        );
130        let damaged = d.path().join("damaged.json");
131        fs::write(&damaged, "{ not json").unwrap();
132        assert_eq!(load::<Prefs>(&damaged), Prefs::default());
133    }
134
135    #[test]
136    fn a_path_without_a_folder_is_refused() {
137        assert!(save(Path::new("settings.json"), &Prefs::default()).is_err());
138    }
139}