Skip to main content

utils/
fs.rs

1use serde::Serialize;
2use serde::de::DeserializeOwned;
3use std::fs::{self, OpenOptions};
4use std::io::{self, Write};
5use std::path::{Path, PathBuf};
6use tempfile::NamedTempFile;
7use thiserror::Error;
8
9#[derive(Debug, Error)]
10pub enum JsonFileError {
11    #[error("failed to access {}: {source}", .path.display())]
12    Io { path: PathBuf, source: io::Error },
13    #[error("invalid JSON in {}: {source}", .path.display())]
14    Json { path: PathBuf, source: serde_json::Error },
15}
16
17impl JsonFileError {
18    pub fn path(&self) -> &Path {
19        match self {
20            Self::Io { path, .. } | Self::Json { path, .. } => path,
21        }
22    }
23}
24
25pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
26    let parent = create_parent_dir(path)?;
27    let mut temp = NamedTempFile::new_in(parent)?;
28    temp.write_all(bytes)?;
29    if let Ok(existing) = fs::metadata(path) {
30        temp.as_file().set_permissions(existing.permissions())?;
31    }
32    temp.as_file().sync_all()?;
33    temp.persist(path).map_err(|error| error.error)?;
34    Ok(())
35}
36
37pub fn append_line(path: &Path, line: &str) -> io::Result<()> {
38    create_parent_dir(path)?;
39    OpenOptions::new().create(true).append(true).open(path)?.write_all(format!("{line}\n").as_bytes())
40}
41
42pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, JsonFileError> {
43    match fs::read(path) {
44        Ok(bytes) => serde_json::from_slice(&bytes)
45            .map(Some)
46            .map_err(|source| JsonFileError::Json { path: path.to_path_buf(), source }),
47        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
48        Err(source) => Err(JsonFileError::Io { path: path.to_path_buf(), source }),
49    }
50}
51
52pub fn write_json_atomic<T: Serialize + ?Sized>(path: &Path, value: &T) -> Result<(), JsonFileError> {
53    let mut bytes =
54        serde_json::to_vec_pretty(value).map_err(|source| JsonFileError::Json { path: path.to_path_buf(), source })?;
55    bytes.push(b'\n');
56    write_atomic(path, &bytes).map_err(|source| JsonFileError::Io { path: path.to_path_buf(), source })
57}
58
59pub fn with_file_lock<T, E: From<io::Error>>(path: &Path, f: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
60    create_parent_dir(path)?;
61    let mut lock_path = path.as_os_str().to_owned();
62    lock_path.push(".lock");
63    let lock = OpenOptions::new().create(true).truncate(false).write(true).open(lock_path)?;
64    lock.lock()?;
65    f()
66}
67
68fn create_parent_dir(path: &Path) -> io::Result<&Path> {
69    let parent = path.parent().filter(|parent| !parent.as_os_str().is_empty()).unwrap_or(Path::new("."));
70    fs::create_dir_all(parent)?;
71    Ok(parent)
72}
73
74#[cfg(test)]
75mod tests {
76    use super::*;
77    use tempfile::TempDir;
78
79    #[test]
80    fn append_line_creates_parents_and_appends_newline_terminated_lines() {
81        let dir = TempDir::new().unwrap();
82        let path = dir.path().join("nested/log.jsonl");
83
84        append_line(&path, "first").unwrap();
85        append_line(&path, "second").unwrap();
86
87        assert_eq!(fs::read_to_string(&path).unwrap(), "first\nsecond\n");
88    }
89
90    #[test]
91    fn json_round_trips_and_missing_files_read_as_none() {
92        let dir = TempDir::new().unwrap();
93        let path = dir.path().join("nested/data.json");
94
95        assert_eq!(read_json::<Vec<u32>>(&path).unwrap(), None);
96        write_json_atomic(&path, &[1, 2]).unwrap();
97
98        assert_eq!(read_json::<Vec<u32>>(&path).unwrap(), Some(vec![1, 2]));
99        assert!(fs::read_to_string(&path).unwrap().ends_with("]\n"));
100    }
101
102    #[test]
103    fn read_json_reports_malformed_files_with_their_path() {
104        let dir = TempDir::new().unwrap();
105        let path = dir.path().join("data.json");
106        fs::write(&path, "{").unwrap();
107
108        let error = read_json::<Vec<u32>>(&path).unwrap_err();
109
110        assert!(matches!(error, JsonFileError::Json { path: ref failed, .. } if failed == &path));
111    }
112
113    #[test]
114    fn with_file_lock_runs_the_closure_and_can_be_retaken() {
115        let dir = TempDir::new().unwrap();
116        let path = dir.path().join("nested/data.json");
117
118        let first: io::Result<u32> = with_file_lock(&path, || Ok(1));
119        let second: io::Result<u32> = with_file_lock(&path, || Ok(2));
120
121        assert_eq!((first.unwrap(), second.unwrap()), (1, 2));
122        assert!(dir.path().join("nested/data.json.lock").is_file());
123    }
124
125    #[test]
126    fn write_atomic_creates_parents_and_replaces_contents() {
127        let dir = TempDir::new().unwrap();
128        let path = dir.path().join("nested/file.json");
129
130        write_atomic(&path, b"first").unwrap();
131        write_atomic(&path, b"second").unwrap();
132
133        assert_eq!(fs::read_to_string(&path).unwrap(), "second");
134        let entries: Vec<_> = fs::read_dir(path.parent().unwrap()).unwrap().map(|e| e.unwrap().file_name()).collect();
135        assert_eq!(entries, ["file.json"], "temp files should not be left behind");
136    }
137
138    #[cfg(unix)]
139    #[test]
140    fn write_atomic_creates_private_files_and_keeps_existing_permissions() {
141        use std::os::unix::fs::PermissionsExt;
142        let dir = TempDir::new().unwrap();
143        let path = dir.path().join("file");
144        let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
145
146        write_atomic(&path, b"first").unwrap();
147        assert_eq!(mode(&path), 0o600);
148
149        fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap();
150        write_atomic(&path, b"second").unwrap();
151        assert_eq!(mode(&path), 0o640);
152    }
153
154    #[test]
155    fn write_atomic_failure_leaves_no_temp_file() {
156        let dir = TempDir::new().unwrap();
157        let path = dir.path().join("target");
158        fs::create_dir_all(path.join("occupied")).unwrap();
159
160        assert!(write_atomic(&path, b"data").is_err());
161
162        let entries: Vec<_> = fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name()).collect();
163        assert_eq!(entries, ["target"], "the temp file should be removed after a failed rename");
164    }
165}