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