use std::{fmt, io};
pub(crate) const GPG_ERR_TIMEOUT: u16 = 62;
pub(crate) const GPG_ERR_CANCELED: u16 = 99;
pub(crate) const GPG_ERR_NOT_CONFIRMED: u16 = 114;
#[derive(Debug)]
pub struct GpgError {
code: u16,
description: Option<String>,
}
impl fmt::Display for GpgError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Code {}", self.code)?;
if let Some(desc) = &self.description {
write!(f, ": {}", desc)?;
}
Ok(())
}
}
impl GpgError {
pub(super) fn new(code: u16, description: Option<String>) -> Self {
GpgError { code, description }
}
pub fn code(&self) -> u16 {
self.code
}
}
#[derive(Debug)]
pub enum Error {
Cancelled,
Timeout,
Io(io::Error),
Gpg(GpgError),
Encoding(std::str::Utf8Error),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Timeout => write!(f, "Operation timed out"),
Error::Cancelled => write!(f, "Operation cancelled"),
Error::Gpg(e) => e.fmt(f),
Error::Io(e) => e.fmt(f),
Error::Encoding(e) => e.fmt(f),
}
}
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::Io(e)
}
}
impl From<std::str::Utf8Error> for Error {
fn from(e: std::str::Utf8Error) -> Self {
Error::Encoding(e)
}
}
impl Error {
pub(crate) fn from_parts(code: u16, description: Option<String>) -> Self {
match code {
GPG_ERR_TIMEOUT => Error::Timeout,
GPG_ERR_CANCELED => Error::Cancelled,
_ => Error::Gpg(GpgError::new(code, description)),
}
}
}