shell-rs 0.2.6

Rust reimplementation of common coreutils APIs
Documentation
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.

use std::fmt::{self, Display};

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ErrorKind {
    IoError,
    ParameterError,
    Utf8Error,
    SyscallError,
    InvalidArchError,
    ParseNumError,

    PwdError,
    PwdGroupError,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Error {
    pub kind: ErrorKind,
    pub message: String,
}

impl Error {
    pub fn new(kind: ErrorKind, message: &str) -> Self {
        Error {
            kind,
            message: message.to_owned(),
        }
    }

    pub fn from_string(kind: ErrorKind, message: String) -> Self {
        Error { kind, message }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}: {}", self.kind, self.message)
    }
}

impl std::error::Error for Error {}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Error::from_string(ErrorKind::IoError, format!("IoError {}", err))
    }
}

impl From<std::string::FromUtf8Error> for Error {
    fn from(err: std::string::FromUtf8Error) -> Self {
        Error::from_string(ErrorKind::Utf8Error, format!("err: {}", err))
    }
}

impl From<std::str::Utf8Error> for Error {
    fn from(err: std::str::Utf8Error) -> Self {
        Error::from_string(ErrorKind::Utf8Error, format!("err: {}", err))
    }
}

impl From<std::ffi::IntoStringError> for Error {
    fn from(err: std::ffi::IntoStringError) -> Self {
        Error::from_string(ErrorKind::Utf8Error, format!("err: {}", err))
    }
}

impl From<std::num::ParseIntError> for Error {
    fn from(err: std::num::ParseIntError) -> Self {
        Error::from_string(ErrorKind::ParseNumError, format!("err: {}", err))
    }
}

impl From<std::num::ParseFloatError> for Error {
    fn from(err: std::num::ParseFloatError) -> Self {
        Error::from_string(ErrorKind::ParseNumError, format!("err: {}", err))
    }
}

impl From<nc::Errno> for Error {
    fn from(errno: nc::Errno) -> Self {
        Error::from_string(
            ErrorKind::SyscallError,
            format!("error: {:?}", nc::strerror(errno)),
        )
    }
}