1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use std::{fmt, io, path::PathBuf};

use crate::ConfigError;

/// Errors when parsing SSH configuration.
#[derive(Debug)]
pub enum Error {
    /// SSH configuration file contains errors.
    ConfigErrors {
        /// The underlying configuration errors
        errors: Vec<ConfigError>,
    },
    /// Failed to discover the user's home directory.
    HomeDirNotFound,
    /// Failed to read SSH configuration file.
    SshConfigRead {
        /// The path to the SSH file.
        path: PathBuf,
        /// The IO error.
        error: io::Error,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::ConfigErrors { errors } => {
                writeln!(f, "SSH configuration contains the following errors:\n")?;

                errors
                    .iter()
                    .try_for_each(|error| writeln!(f, "* {}", error))?;

                writeln!(f)
            }
            Self::HomeDirNotFound => write!(f, "Failed to determine user's home directory."),
            Self::SshConfigRead { path, .. } => {
                write!(f, "Failed to read `{}`.", path.display())
            }
        }
    }
}

impl From<plain_path::HomeDirNotFound> for Error {
    fn from(_: plain_path::HomeDirNotFound) -> Self {
        Self::HomeDirNotFound
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ConfigErrors { .. } => None,
            Self::HomeDirNotFound => None,
            Self::SshConfigRead { error, .. } => Some(error),
        }
    }
}