1 /*!
2 fs-err is a drop-in replacement for [`std::fs`][std::fs] that provides more
3 helpful messages on errors. Extra information includes which operations was
4 attmpted and any involved paths.
5 
6 # Error Messages
7 
8 Using [`std::fs`][std::fs], if this code fails:
9 
10 ```no_run
11 # use std::fs::File;
12 let file = File::open("does not exist.txt")?;
13 # Ok::<(), std::io::Error>(())
14 ```
15 
16 The error message that Rust gives you isn't very useful:
17 
18 ```txt
19 The system cannot find the file specified. (os error 2)
20 ```
21 
22 ...but if we use fs-err instead, our error contains more actionable information:
23 
24 ```txt
25 failed to open file `does not exist.txt`
26     caused by: The system cannot find the file specified. (os error 2)
27 ```
28 
29 # Usage
30 
31 fs-err's API is the same as [`std::fs`][std::fs], so migrating code to use it is easy.
32 
33 ```no_run
34 // use std::fs;
35 use fs_err as fs;
36 
37 let contents = fs::read_to_string("foo.txt")?;
38 
39 println!("Read foo.txt: {}", contents);
40 
41 # Ok::<(), std::io::Error>(())
42 ```
43 
44 fs-err uses [`std::io::Error`][std::io::Error] for all errors. This helps fs-err
45 compose well with traits from the standard library like
46 [`std::io::Read`][std::io::Read] and crates that use them like
47 [`serde_json`][serde_json]:
48 
49 ```no_run
50 use fs_err::File;
51 
52 let file = File::open("my-config.json")?;
53 
54 // If an I/O error occurs inside serde_json, the error will include a file path
55 // as well as what operation was being performed.
56 let decoded: Vec<String> = serde_json::from_reader(file)?;
57 
58 println!("Program config: {:?}", decoded);
59 
60 # Ok::<(), Box<dyn std::error::Error>>(())
61 ```
62 
63 [std::fs]: https://doc.rust-lang.org/stable/std/fs/
64 [std::io::Error]: https://doc.rust-lang.org/stable/std/io/struct.Error.html
65 [std::io::Read]: https://doc.rust-lang.org/stable/std/io/trait.Read.html
66 [serde_json]: https://crates.io/crates/serde_json
67 */
68 
69 #![doc(html_root_url = "https://docs.rs/fs-err/2.5.0")]
70 #![deny(missing_debug_implementations, missing_docs)]
71 
72 mod dir;
73 mod errors;
74 mod file;
75 mod open_options;
76 pub mod os;
77 mod path;
78 
79 use std::fs;
80 use std::io::{self, Read, Write};
81 use std::path::{Path, PathBuf};
82 
83 use errors::{Error, ErrorKind, SourceDestError, SourceDestErrorKind};
84 
85 pub use dir::*;
86 pub use file::*;
87 pub use open_options::OpenOptions;
88 pub use path::PathExt;
89 
90 /// Wrapper for [`fs::read`](https://doc.rust-lang.org/stable/std/fs/fn.read.html).
read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>>91 pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
92     let path = path.as_ref();
93     let mut file = file::open(path.as_ref()).map_err(|err_gen| err_gen(path.to_path_buf()))?;
94     let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
95     file.read_to_end(&mut bytes)
96         .map_err(|err| Error::new(err, ErrorKind::Read, path))?;
97     Ok(bytes)
98 }
99 
100 /// Wrapper for [`fs::read_to_string`](https://doc.rust-lang.org/stable/std/fs/fn.read_to_string.html).
read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String>101 pub fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
102     let path = path.as_ref();
103     let mut file = file::open(path.as_ref()).map_err(|err_gen| err_gen(path.to_path_buf()))?;
104     let mut string = String::with_capacity(initial_buffer_size(&file));
105     file.read_to_string(&mut string)
106         .map_err(|err| Error::new(err, ErrorKind::Read, path))?;
107     Ok(string)
108 }
109 
110 /// Wrapper for [`fs::write`](https://doc.rust-lang.org/stable/std/fs/fn.write.html).
write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()>111 pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
112     let path = path.as_ref();
113     file::create(path)
114         .map_err(|err_gen| err_gen(path.to_path_buf()))?
115         .write_all(contents.as_ref())
116         .map_err(|err| Error::new(err, ErrorKind::Write, path))
117 }
118 
119 /// Wrapper for [`fs::copy`](https://doc.rust-lang.org/stable/std/fs/fn.copy.html).
copy<P, Q>(from: P, to: Q) -> io::Result<u64> where P: AsRef<Path>, Q: AsRef<Path>,120 pub fn copy<P, Q>(from: P, to: Q) -> io::Result<u64>
121 where
122     P: AsRef<Path>,
123     Q: AsRef<Path>,
124 {
125     let from = from.as_ref();
126     let to = to.as_ref();
127     fs::copy(from, to)
128         .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::Copy, from, to))
129 }
130 
131 /// Wrapper for [`fs::create_dir`](https://doc.rust-lang.org/stable/std/fs/fn.create_dir.html).
create_dir<P>(path: P) -> io::Result<()> where P: AsRef<Path>,132 pub fn create_dir<P>(path: P) -> io::Result<()>
133 where
134     P: AsRef<Path>,
135 {
136     let path = path.as_ref();
137     fs::create_dir(path).map_err(|source| Error::new(source, ErrorKind::CreateDir, path))
138 }
139 
140 /// Wrapper for [`fs::create_dir_all`](https://doc.rust-lang.org/stable/std/fs/fn.create_dir_all.html).
create_dir_all<P>(path: P) -> io::Result<()> where P: AsRef<Path>,141 pub fn create_dir_all<P>(path: P) -> io::Result<()>
142 where
143     P: AsRef<Path>,
144 {
145     let path = path.as_ref();
146     fs::create_dir_all(path).map_err(|source| Error::new(source, ErrorKind::CreateDir, path))
147 }
148 
149 /// Wrapper for [`fs::remove_dir`](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir.html).
remove_dir<P>(path: P) -> io::Result<()> where P: AsRef<Path>,150 pub fn remove_dir<P>(path: P) -> io::Result<()>
151 where
152     P: AsRef<Path>,
153 {
154     let path = path.as_ref();
155     fs::remove_dir(path).map_err(|source| Error::new(source, ErrorKind::RemoveDir, path))
156 }
157 
158 /// Wrapper for [`fs::remove_dir_all`](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir_all.html).
remove_dir_all<P>(path: P) -> io::Result<()> where P: AsRef<Path>,159 pub fn remove_dir_all<P>(path: P) -> io::Result<()>
160 where
161     P: AsRef<Path>,
162 {
163     let path = path.as_ref();
164     fs::remove_dir_all(path).map_err(|source| Error::new(source, ErrorKind::RemoveDir, path))
165 }
166 
167 /// Wrapper for [`fs::remove_file`](https://doc.rust-lang.org/stable/std/fs/fn.remove_file.html).
remove_file<P>(path: P) -> io::Result<()> where P: AsRef<Path>,168 pub fn remove_file<P>(path: P) -> io::Result<()>
169 where
170     P: AsRef<Path>,
171 {
172     let path = path.as_ref();
173     fs::remove_file(path).map_err(|source| Error::new(source, ErrorKind::RemoveFile, path))
174 }
175 
176 /// Wrapper for [`fs::metadata`](https://doc.rust-lang.org/stable/std/fs/fn.metadata.html).
metadata<P: AsRef<Path>>(path: P) -> io::Result<fs::Metadata>177 pub fn metadata<P: AsRef<Path>>(path: P) -> io::Result<fs::Metadata> {
178     let path = path.as_ref();
179     fs::metadata(path).map_err(|source| Error::new(source, ErrorKind::Metadata, path))
180 }
181 
182 /// Wrapper for [`fs::canonicalize`](https://doc.rust-lang.org/stable/std/fs/fn.canonicalize.html).
canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf>183 pub fn canonicalize<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
184     let path = path.as_ref();
185     fs::canonicalize(path).map_err(|source| Error::new(source, ErrorKind::Canonicalize, path))
186 }
187 
188 /// Wrapper for [`fs::hard_link`](https://doc.rust-lang.org/stable/std/fs/fn.hard_link.html).
hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>189 pub fn hard_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
190     let src = src.as_ref();
191     let dst = dst.as_ref();
192     fs::hard_link(src, dst)
193         .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::HardLink, src, dst))
194 }
195 
196 /// Wrapper for [`fs::read_link`](https://doc.rust-lang.org/stable/std/fs/fn.read_link.html).
read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf>197 pub fn read_link<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
198     let path = path.as_ref();
199     fs::read_link(path).map_err(|source| Error::new(source, ErrorKind::ReadLink, path))
200 }
201 
202 /// Wrapper for [`fs::rename`](https://doc.rust-lang.org/stable/std/fs/fn.rename.html).
rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()>203 pub fn rename<P: AsRef<Path>, Q: AsRef<Path>>(from: P, to: Q) -> io::Result<()> {
204     let from = from.as_ref();
205     let to = to.as_ref();
206     fs::rename(from, to)
207         .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::Rename, from, to))
208 }
209 
210 /// Wrapper for [`fs::soft_link`](https://doc.rust-lang.org/stable/std/fs/fn.soft_link.html).
211 #[deprecated = "replaced with std::os::unix::fs::symlink and \
212 std::os::windows::fs::{symlink_file, symlink_dir}"]
soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()>213 pub fn soft_link<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> io::Result<()> {
214     let src = src.as_ref();
215     let dst = dst.as_ref();
216     #[allow(deprecated)]
217     fs::soft_link(src, dst)
218         .map_err(|source| SourceDestError::new(source, SourceDestErrorKind::SoftLink, src, dst))
219 }
220 
221 /// Wrapper for [`fs::symlink_metadata`](https://doc.rust-lang.org/stable/std/fs/fn.symlink_metadata.html).
symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<fs::Metadata>222 pub fn symlink_metadata<P: AsRef<Path>>(path: P) -> io::Result<fs::Metadata> {
223     let path = path.as_ref();
224     fs::symlink_metadata(path)
225         .map_err(|source| Error::new(source, ErrorKind::SymlinkMetadata, path))
226 }
227 
228 /// Wrapper for [`fs::set_permissions`](https://doc.rust-lang.org/stable/std/fs/fn.set_permissions.html).
set_permissions<P: AsRef<Path>>(path: P, perm: fs::Permissions) -> io::Result<()>229 pub fn set_permissions<P: AsRef<Path>>(path: P, perm: fs::Permissions) -> io::Result<()> {
230     let path = path.as_ref();
231     fs::set_permissions(path, perm)
232         .map_err(|source| Error::new(source, ErrorKind::SetPermissions, path))
233 }
234 
initial_buffer_size(file: &std::fs::File) -> usize235 fn initial_buffer_size(file: &std::fs::File) -> usize {
236     file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0)
237 }
238 
239 pub(crate) use private::Sealed;
240 mod private {
241     pub trait Sealed {}
242 
243     impl Sealed for crate::File {}
244     impl Sealed for std::path::Path {}
245     impl Sealed for crate::OpenOptions {}
246 }
247