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
use thiserror::Error;

/// Represents an error condition
#[derive(Error, Debug, PartialEq, Eq)]
pub enum Error {
    /// The last request was denied but situation is recoverable
    #[error("RequestDenied: {}", .0)]
    RequestDenied(String),
    /// A fatal error occurred. This could be an unexpected disconnection
    #[error("Fatal: {}", .0)]
    Fatal(String),
    /// The session is in non-blocking mode and the call must be tried again
    #[error("TryAgain")]
    TryAgain,

    #[error("SftpError: {}", .0)]
    Sftp(crate::sftp::SftpError),
}

/// Represents the result of a fallible operation
pub type SshResult<T> = Result<T, Error>;

impl Error {
    pub fn is_try_again(&self) -> bool {
        matches!(self, Self::TryAgain)
    }

    pub fn fatal<S: Into<String>>(s: S) -> Self {
        Self::Fatal(s.into())
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Error {
        Error::fatal(err.to_string())
    }
}

impl From<Error> for std::io::Error {
    fn from(err: Error) -> std::io::Error {
        match err {
            Error::TryAgain => std::io::Error::new(std::io::ErrorKind::WouldBlock, "TryAgain"),
            Error::RequestDenied(msg) | Error::Fatal(msg) => {
                std::io::Error::new(std::io::ErrorKind::Other, msg)
            }
            Error::Sftp(err) => std::io::Error::new(std::io::ErrorKind::Other, err.to_string()),
        }
    }
}

impl From<std::ffi::NulError> for Error {
    fn from(err: std::ffi::NulError) -> Error {
        Error::Fatal(err.to_string())
    }
}