oma_apt/
error.rs

1//! There be Errors here.
2
3use std::fmt;
4
5use cxx::Exception;
6#[doc(inline)]
7pub use raw::{AptError, empty, pending_error};
8
9#[cxx::bridge]
10pub(crate) mod raw {
11    /// Representation of a single Apt Error or Warning
12    #[derive(Debug)]
13    struct AptError {
14        /// * [`true`] = Error.
15        /// * [`false`] = Warning, Notice, etc.
16        pub is_error: bool,
17        /// The String version of the Error.
18        pub msg: String,
19    }
20
21    unsafe extern "C++" {
22        include!("oma-apt/apt-pkg-c/error.h");
23
24        /// Returns [`true`] if there are any pending Apt Errors.
25        pub fn pending_error() -> bool;
26
27        /// Returns [`true`] if there are no Errors or Warnings.
28        pub fn empty() -> bool;
29
30        /// Returns all Apt Errors or Warnings.
31        pub fn get_all() -> Vec<AptError>;
32    }
33}
34
35impl fmt::Display for AptError {
36    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
37        if self.is_error {
38            write!(f, "E: {}", self.msg)?;
39        } else {
40            write!(f, "W: {}", self.msg)?;
41        }
42
43        Ok(())
44    }
45}
46
47impl std::error::Error for AptError {}
48
49/// Struct that represents multiple apt errors and warnings.
50///
51/// This is essentially just a wrapper around [`Vec<AptError>`]
52#[derive(Debug)]
53pub struct AptErrors {
54    pub(crate) ptr: Vec<AptError>,
55}
56
57impl AptErrors {
58    pub fn new() -> AptErrors {
59        AptErrors {
60            ptr: raw::get_all(),
61        }
62    }
63}
64
65impl Default for AptErrors {
66    fn default() -> Self {
67        Self::new()
68    }
69}
70
71impl fmt::Display for AptErrors {
72    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73        for error in self.iter() {
74            writeln!(f, "{error}")?;
75        }
76        Ok(())
77    }
78}
79
80impl From<String> for AptErrors {
81    fn from(err: String) -> Self {
82        AptErrors {
83            ptr: vec![AptError {
84                is_error: true,
85                msg: err,
86            }],
87        }
88    }
89}
90
91impl From<Exception> for AptErrors {
92    fn from(err: Exception) -> Self {
93        if err.what() == "convert to AptErrors" {
94            return AptErrors::new();
95        }
96        // The times where it's not an Apt error to be converted are slim
97        AptErrors::from(err.what().to_string())
98    }
99}
100
101impl From<std::io::Error> for AptErrors {
102    fn from(err: std::io::Error) -> Self {
103        AptErrors::from(err.to_string())
104    }
105}
106
107impl std::error::Error for AptErrors {}