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/// 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 contents = locked_read(path)?;
66    String::from_utf8(contents).map_err(|err| FsPathError::read(std::io::Error::other(err), path))
67}
68
69/// Reads the entire contents of a locked shared file into a bytes vector.
70pub fn locked_read(path: impl AsRef<Path>) -> Result<Vec<u8>> {
71    let path = path.as_ref();
72    let mut file =
73        fs::OpenOptions::new().read(true).open(path).map_err(|err| FsPathError::open(err, path))?;
74    file.lock_shared().map_err(|err| FsPathError::lock(err, path))?;
75    let contents = read_inner(path, &mut file)?;
76    file.unlock().map_err(|err| FsPathError::unlock(err, path))?;
77    Ok(contents)
78}
79
80fn read_inner(path: &Path, file: &mut File) -> Result<Vec<u8>> {
81    let file_len = file.metadata().map_err(|err| FsPathError::open(err, path))?.len() as usize;
82    let mut buffer = Vec::with_capacity(file_len);
83    file.read_to_end(&mut buffer).map_err(|err| FsPathError::read(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: &str) -> Result<()> {
140    let path = path.as_ref();
141    if cfg!(windows) {
142        return locked_write_line_windows(path, line);
143    }
144
145    let mut file = std::fs::OpenOptions::new()
146        .append(true)
147        .create(true)
148        .open(path)
149        .map_err(|err| FsPathError::open(err, path))?;
150
151    file.lock().map_err(|err| FsPathError::lock(err, path))?;
152    writeln!(file, "{line}").map_err(|err| FsPathError::write(err, path))?;
153    file.unlock().map_err(|err| FsPathError::unlock(err, path))
154}
155
156// Locking fails on Windows if the file is opened in append mode.
157fn locked_write_line_windows(path: &Path, line: &str) -> Result<()> {
158    let mut file = std::fs::OpenOptions::new()
159        .write(true)
160        .truncate(false)
161        .create(true)
162        .open(path)
163        .map_err(|err| FsPathError::open(err, path))?;
164    file.lock().map_err(|err| FsPathError::lock(err, path))?;
165
166    file.seek(SeekFrom::End(0)).map_err(|err| FsPathError::write(err, path))?;
167    writeln!(file, "{line}").map_err(|err| FsPathError::write(err, path))?;
168
169    file.unlock().map_err(|err| FsPathError::unlock(err, path))
170}
171
172/// Wrapper for `std::fs::copy`
173pub fn copy(from: impl AsRef<Path>, to: impl AsRef<Path>) -> Result<u64> {
174    let from = from.as_ref();
175    let to = to.as_ref();
176    fs::copy(from, to).map_err(|err| FsPathError::copy(err, from, to))
177}
178
179/// Wrapper for `std::fs::create_dir`
180pub fn create_dir(path: impl AsRef<Path>) -> Result<()> {
181    let path = path.as_ref();
182    fs::create_dir(path).map_err(|err| FsPathError::create_dir(err, path))
183}
184
185/// Wrapper for `std::fs::create_dir_all`
186pub fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
187    let path = path.as_ref();
188    fs::create_dir_all(path).map_err(|err| FsPathError::create_dir(err, path))
189}
190
191/// Wrapper for `std::fs::remove_dir`
192pub fn remove_dir(path: impl AsRef<Path>) -> Result<()> {
193    let path = path.as_ref();
194    fs::remove_dir(path).map_err(|err| FsPathError::remove_dir(err, path))
195}
196
197/// Wrapper for `std::fs::remove_dir_all`
198pub fn remove_dir_all(path: impl AsRef<Path>) -> Result<()> {
199    let path = path.as_ref();
200    fs::remove_dir_all(path).map_err(|err| FsPathError::remove_dir(err, path))
201}
202
203/// Wrapper for `std::fs::File::open`
204pub fn open(path: impl AsRef<Path>) -> Result<fs::File> {
205    let path = path.as_ref();
206    fs::File::open(path).map_err(|err| FsPathError::open(err, path))
207}
208
209/// Normalize a path, removing things like `.` and `..`.
210///
211/// NOTE: This does not return symlinks and does not touch the filesystem at all (unlike
212/// [`std::fs::canonicalize`])
213///
214/// ref: <https://github.com/rust-lang/cargo/blob/9ded34a558a900563b0acf3730e223c649cf859d/crates/cargo-util/src/paths.rs#L81>
215pub fn normalize_path(path: &Path) -> PathBuf {
216    let mut components = path.components().peekable();
217    let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() {
218        components.next();
219        PathBuf::from(c.as_os_str())
220    } else {
221        PathBuf::new()
222    };
223
224    for component in components {
225        match component {
226            Component::Prefix(..) => unreachable!(),
227            Component::RootDir => {
228                ret.push(component.as_os_str());
229            }
230            Component::CurDir => {}
231            Component::ParentDir => {
232                ret.pop();
233            }
234            Component::Normal(c) => {
235                ret.push(c);
236            }
237        }
238    }
239    ret
240}
241
242/// Returns an iterator over all files with the given extension under the `root` dir.
243pub fn files_with_ext<'a>(root: &Path, ext: &'a str) -> impl Iterator<Item = PathBuf> + 'a {
244    walkdir::WalkDir::new(root)
245        .sort_by_file_name()
246        .into_iter()
247        .filter_map(walkdir::Result::ok)
248        .filter(|e| e.file_type().is_file() && e.path().extension() == Some(ext.as_ref()))
249        .map(walkdir::DirEntry::into_path)
250}
251
252/// Returns an iterator over all JSON files under the `root` dir.
253pub fn json_files(root: &Path) -> impl Iterator<Item = PathBuf> {
254    files_with_ext(root, "json")
255}
256
257/// Canonicalize a path, returning an error if the path does not exist.
258///
259/// Mainly useful to apply canonicalization to paths obtained from project files but still error
260/// properly instead of flattening the errors.
261pub fn canonicalize_path(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
262    dunce::canonicalize(path)
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    #[test]
270    fn test_normalize_path() {
271        let p = Path::new("/a/../file.txt");
272        let normalized = normalize_path(p);
273        assert_eq!(normalized, PathBuf::from("/file.txt"));
274    }
275}