rsufw 0.1.0

Linux-only Rust library for managing UFW firewall rules
Documentation
use std::fmt;

#[derive(Debug)]
pub enum UfwError {
    Io(std::io::Error),
    Utf8(std::string::FromUtf8Error),
    CommandFailed {
        program: String,
        args: Vec<String>,
        stderr: String,
        code: Option<i32>,
    },
    InvalidIpv4(String),
    InvalidIpv6(String),
    ParseError(String),
    EmptyOutput,
    UnexpectedStatusLine(String),
}

impl fmt::Display for UfwError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UfwError::Io(e) => write!(f, "I/O error: {e}"),
            UfwError::Utf8(e) => write!(f, "UTF-8 error: {e}"),
            UfwError::CommandFailed {
                program,
                args,
                stderr,
                code,
            } => {
                let args = args.join(" ");
                match code {
                    Some(c) => write!(f, "'{program} {args}' failed with code {c}: {stderr}"),
                    None => write!(f, "'{program} {args}' terminated by signal: {stderr}"),
                }
            }
            UfwError::InvalidIpv4(ip) => write!(f, "invalid IPv4 address: {ip}"),
            UfwError::InvalidIpv6(ip) => write!(f, "invalid IPv6 address: {ip}"),
            UfwError::ParseError(msg) => write!(f, "parse error: {msg}"),
            UfwError::EmptyOutput => write!(f, "empty output from ufw"),
            UfwError::UnexpectedStatusLine(line) => {
                write!(f, "unexpected status line from ufw: {line}")
            }
        }
    }
}

impl std::error::Error for UfwError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            UfwError::Io(e) => Some(e),
            UfwError::Utf8(e) => Some(e),
            _ => None,
        }
    }
}

impl From<std::io::Error> for UfwError {
    fn from(e: std::io::Error) -> Self {
        UfwError::Io(e)
    }
}

impl From<std::string::FromUtf8Error> for UfwError {
    fn from(e: std::string::FromUtf8Error) -> Self {
        UfwError::Utf8(e)
    }
}