Skip to main content

refix_codegen/package/
error.rs

1use std::fmt;
2use std::io;
3use std::path::{Path, PathBuf};
4
5/// A file or directory of a package that could not be written.
6#[derive(Debug)]
7pub struct WriteError {
8    action: &'static str,
9    path: PathBuf,
10    source: io::Error,
11}
12
13impl WriteError {
14    /// `action` is the verb of what failed at `path`.
15    pub(super) fn new(action: &'static str, path: &Path, source: io::Error) -> Self {
16        Self {
17            action,
18            path: path.to_owned(),
19            source,
20        }
21    }
22}
23
24impl fmt::Display for WriteError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        let Self {
27            action,
28            path,
29            source,
30        } = self;
31        write!(f, "cannot {action} '{}': {source}", path.display())
32    }
33}
34
35impl std::error::Error for WriteError {
36    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
37        Some(&self.source)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use std::io;
44    use std::path::Path;
45
46    use super::WriteError;
47
48    #[test]
49    fn names_what_failed_and_where() {
50        let source = io::Error::other("disk full");
51        let error = WriteError::new("write", Path::new("fix44/enums.py"), source);
52
53        assert_eq!(
54            error.to_string(),
55            "cannot write 'fix44/enums.py': disk full"
56        );
57    }
58}