Skip to main content

foundry_common/
fs.rs

1//! Contains various `std::fs` wrapper functions that also contain the target path in their errors.
2
3use crate::errors::FsPathError;
4use flate2::{Compression, read::GzDecoder, write::GzEncoder};
5use serde::{Serialize, de::DeserializeOwned};
6use std::{
7    fs::{self, File},
8    io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write},
9    path::{Component, Path, PathBuf},
10};
11
12#[cfg(unix)]
13use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
14
15/// The [`fs`](self) result type.
16pub type Result<T> = std::result::Result<T, FsPathError>;
17
18/// Wrapper for [`File::create`].
19pub fn create_file(path: impl AsRef<Path>) -> Result<fs::File> {
20    let path = path.as_ref();
21    File::create(path).map_err(|err| FsPathError::create_file(err, path))
22}
23
24/// Wrapper for [`std::fs::remove_file`].
25pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
26    let path = path.as_ref();
27    fs::remove_file(path).map_err(|err| FsPathError::remove_file(err, path))
28}
29
30/// Wrapper for [`std::fs::read`].
31pub fn read(path: impl AsRef<Path>) -> Result<Vec<u8>> {
32    let path = path.as_ref();
33    fs::read(path).map_err(|err| FsPathError::read(err, path))
34}
35
36/// Wrapper for [`std::fs::read_link`].
37pub fn read_link(path: impl AsRef<Path>) -> Result<PathBuf> {
38    let path = path.as_ref();
39    fs::read_link(path).map_err(|err| FsPathError::read_link(err, path))
40}
41
42/// Wrapper for [`std::fs::read_to_string`].
43pub fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
44    let path = path.as_ref();
45    fs::read_to_string(path).map_err(|err| FsPathError::read(err, path))
46}
47
48/// Reads the JSON file and deserialize it into the provided type.
49pub fn read_json_file<T: DeserializeOwned>(path: &Path) -> Result<T> {
50    // read the file into a byte array first
51    // https://github.com/serde-rs/json/issues/160
52    let s = read_to_string(path)?;
53    serde_json::from_str(&s).map_err(|source| FsPathError::ReadJson { source, path: path.into() })
54}
55
56/// Reads and decodes the json gzip file, then deserialize it into the provided type.
57pub fn read_json_gzip_file<T: DeserializeOwned>(path: &Path) -> Result<T> {
58    let file = open(path)?;
59    let reader = BufReader::new(file);
60    let decoder = GzDecoder::new(reader);
61    serde_json::from_reader(decoder)
62        .map_err(|source| FsPathError::ReadJson { source, path: path.into() })
63}
64
65/// Reads the entire contents of a locked shared file into a string.
66pub fn locked_read_to_string(path: impl AsRef<Path>) -> Result<String> {
67    let path = path.as_ref();
68    let contents = locked_read(path)?;
69    String::from_utf8(contents).map_err(|err| FsPathError::read(std::io::Error::other(err), path))
70}
71
72/// Reads the entire contents of a locked shared file into a bytes vector.
73pub fn locked_read(path: impl AsRef<Path>) -> Result<Vec<u8>> {
74    let path = path.as_ref();
75    let mut file =
76        fs::OpenOptions::new().read(true).open(path).map_err(|err| FsPathError::open(err, path))?;
77    file.lock_shared().map_err(|err| FsPathError::lock(err, path))?;
78    let contents = read_inner(path, &mut file)?;
79    file.unlock().map_err(|err| FsPathError::unlock(err, path))?;
80    Ok(contents)
81}
82
83fn read_inner(path: &Path, file: &mut File) -> Result<Vec<u8>> {
84    let file_len = file.metadata().map_err(|err| FsPathError::open(err, path))?.len() as usize;
85    let mut buffer = Vec::with_capacity(file_len);
86    file.read_to_end(&mut buffer).map_err(|err| FsPathError::read(err, path))?;
87    Ok(buffer)
88}
89
90/// Writes the object as a JSON object.
91pub fn write_json_file<T: Serialize>(path: &Path, obj: &T) -> Result<()> {
92    let file = create_file(path)?;
93    let mut writer = BufWriter::new(file);
94    serde_json::to_writer(&mut writer, obj)
95        .map_err(|source| FsPathError::WriteJson { source, path: path.into() })?;
96    writer.flush().map_err(|e| FsPathError::write(e, path))
97}
98
99/// Writes the object as a pretty JSON object.
100pub fn write_pretty_json_file<T: Serialize>(path: &Path, obj: &T) -> Result<()> {
101    write_pretty_json(path, obj, create_file(path)?)
102}
103
104/// Writes an object as pretty JSON with owner-only permissions on Unix.
105pub fn write_sensitive_json_file<T: Serialize>(path: &Path, obj: &T) -> Result<()> {
106    let mut options = File::options();
107    options.write(true).create(true).truncate(true);
108    #[cfg(unix)]
109    options.mode(0o600);
110
111    let file = options.open(path).map_err(|err| FsPathError::create_file(err, path))?;
112    #[cfg(unix)]
113    file.set_permissions(fs::Permissions::from_mode(0o600))
114        .map_err(|err| FsPathError::write(err, path))?;
115
116    write_pretty_json(path, obj, file)
117}
118
119fn write_pretty_json<T: Serialize>(path: &Path, obj: &T, file: File) -> Result<()> {
120    let mut writer = BufWriter::new(file);
121    serde_json::to_writer_pretty(&mut writer, obj)
122        .map_err(|source| FsPathError::WriteJson { source, path: path.into() })?;
123    writer.flush().map_err(|e| FsPathError::write(e, path))
124}
125
126/// Writes the object as a gzip compressed file.
127pub fn write_json_gzip_file<T: Serialize>(path: &Path, obj: &T) -> Result<()> {
128    let file = create_file(path)?;
129    let writer = BufWriter::new(file);
130    let mut encoder = GzEncoder::new(writer, Compression::default());
131    serde_json::to_writer(&mut encoder, obj)
132        .map_err(|source| FsPathError::WriteJson { source, path: path.into() })?;
133    // Ensure we surface any I/O errors on final gzip write and buffer flush.
134    let mut inner_writer = encoder.finish().map_err(|e| FsPathError::write(e, path))?;
135    inner_writer.flush().map_err(|e| FsPathError::write(e, path))?;
136    Ok(())
137}
138
139/// Wrapper for `std::fs::write`
140pub fn write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
141    let path = path.as_ref();
142    fs::write(path, contents).map_err(|err| FsPathError::write(err, path))
143}
144
145/// Writes all content in an exclusive locked file.
146pub fn locked_write(path: impl AsRef<Path>, contents: impl AsRef<[u8]>) -> Result<()> {
147    let path = path.as_ref();
148    let mut file = fs::OpenOptions::new()
149        .write(true)
150        .create(true)
151        .truncate(true)
152        .open(path)
153        .map_err(|err| FsPathError::open(err, path))?;
154    file.lock().map_err(|err| FsPathError::lock(err, path))?;
155    file.write_all(contents.as_ref()).map_err(|err| FsPathError::write(err, path))?;
156    file.unlock().map_err(|err| FsPathError::unlock(err, path))
157}
158
159/// Writes a line in an exclusive locked file.
160pub fn locked_write_line(path: impl AsRef<Path>, line: &str) -> Result<()> {
161    let path = path.as_ref();
162    if cfg!(windows) {
163        return locked_write_line_windows(path, line);
164    }
165
166    let mut file = std::fs::OpenOptions::new()
167        .append(true)
168        .create(true)
169        .open(path)
170        .map_err(|err| FsPathError::open(err, path))?;
171
172    file.lock().map_err(|err| FsPathError::lock(err, path))?;
173    writeln!(file, "{line}").map_err(|err| FsPathError::write(err, path))?;
174    file.unlock().map_err(|err| FsPathError::unlock(err, path))
175}
176
177// Locking fails on Windows if the file is opened in append mode.
178fn locked_write_line_windows(path: &Path, line: &str) -> Result<()> {
179    let mut file = std::fs::OpenOptions::new()
180        .write(true)
181        .truncate(false)
182        .create(true)
183        .open(path)
184        .map_err(|err| FsPathError::open(err, path))?;
185    file.lock().map_err(|err| FsPathError::lock(err, path))?;
186
187    file.seek(SeekFrom::End(0)).map_err(|err| FsPathError::write(err, path))?;
188    writeln!(file, "{line}").map_err(|err| FsPathError::write(err, path))?;
189
190    file.unlock().map_err(|err| FsPathError::unlock(err, path))
191}
192
193/// Wrapper for `std::fs::copy`
194pub fn copy(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<u64> {
195    let from = from.as_ref();
196    let to = to.as_ref();
197    fs::copy(from, to).map_err(|err| FsPathError::copy(err, from, to))
198}
199
200/// Wrapper for `std::fs::create_dir`
201pub fn create_dir(path: impl AsRef<Path>) -> Result<()> {
202    let path = path.as_ref();
203    fs::create_dir(path).map_err(|err| FsPathError::create_dir(err, path))
204}
205
206/// Wrapper for `std::fs::create_dir_all`
207pub fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
208    let path = path.as_ref();
209    fs::create_dir_all(path).map_err(|err| FsPathError::create_dir(err, path))
210}
211
212/// Wrapper for `std::fs::remove_dir`
213pub fn remove_dir(path: impl AsRef<Path>) -> Result<()> {
214    let path = path.as_ref();
215    fs::remove_dir(path).map_err(|err| FsPathError::remove_dir(err, path))
216}
217
218/// Wrapper for `std::fs::remove_dir_all`
219pub fn remove_dir_all(path: impl AsRef<Path>) -> Result<()> {
220    let path = path.as_ref();
221    fs::remove_dir_all(path).map_err(|err| FsPathError::remove_dir(err, path))
222}
223
224/// Wrapper for `std::fs::File::open`
225pub fn open(path: impl AsRef<Path>) -> Result<fs::File> {
226    let path = path.as_ref();
227    fs::File::open(path).map_err(|err| FsPathError::open(err, path))
228}
229
230/// Normalize a path, removing things like `.` and `..`.
231///
232/// NOTE: This does not return symlinks and does not touch the filesystem at all (unlike
233/// [`std::fs::canonicalize`])
234///
235/// ref: <https://github.com/rust-lang/cargo/blob/9ded34a558a900563b0acf3730e223c649cf859d/crates/cargo-util/src/paths.rs#L81>
236pub fn normalize_path(path: &Path) -> PathBuf {
237    let mut components = path.components().peekable();
238    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
239        components.next();
240        PathBuf::from(c.as_os_str())
241    } else {
242        PathBuf::new()
243    };
244
245    for component in components {
246        match component {
247            Component::Prefix(..) => unreachable!(),
248            Component::RootDir => {
249                ret.push(component.as_os_str());
250            }
251            Component::CurDir => {}
252            Component::ParentDir => {
253                ret.pop();
254            }
255            Component::Normal(c) => {
256                ret.push(c);
257            }
258        }
259    }
260    ret
261}
262
263/// Returns an iterator over all files with the given extension under the `root` dir.
264pub fn files_with_ext<'a>(root: &Path, ext: &'a str) -> impl Iterator<Item = PathBuf> + 'a {
265    walkdir::WalkDir::new(root)
266        .sort_by_file_name()
267        .into_iter()
268        .filter_map(walkdir::Result::ok)
269        .filter(|e| e.file_type().is_file() && e.path().extension() == Some(ext.as_ref()))
270        .map(walkdir::DirEntry::into_path)
271}
272
273/// Returns an iterator over all JSON files under the `root` dir.
274pub fn json_files(root: &Path) -> impl Iterator<Item = PathBuf> {
275    files_with_ext(root, "json")
276}
277
278/// Canonicalize a path, returning an error if the path does not exist.
279///
280/// Mainly useful to apply canonicalization to paths obtained from project files but still error
281/// properly instead of flattening the errors.
282pub fn canonicalize_path(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
283    dunce::canonicalize(path)
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    #[cfg(unix)]
291    #[test]
292    fn test_write_sensitive_json_file_permissions() {
293        let dir = tempfile::tempdir().unwrap();
294        for name in ["new", "existing"] {
295            let path = dir.path().join(name);
296            if name == "existing" {
297                fs::write(&path, []).unwrap();
298                fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();
299            }
300
301            write_sensitive_json_file(&path, &()).unwrap();
302            assert_eq!(fs::metadata(path).unwrap().permissions().mode() & 0o777, 0o600);
303        }
304    }
305
306    #[test]
307    fn test_normalize_path() {
308        let p = Path::new("/a/../file.txt");
309        let normalized = normalize_path(p);
310        assert_eq!(normalized, PathBuf::from("/file.txt"));
311    }
312}