1use std::cell::RefCell;
6use std::fmt;
7use thiserror::Error;
8
9thread_local! {
10 static LAST_ERROR: RefCell<Option<XetError>> = const { RefCell::new(None) };
11}
12
13#[derive(Debug, Clone, Error)]
15#[error("{kind}: {message}")]
16pub struct XetError {
17 message: String,
18 kind: XetErrorKind,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum XetErrorKind {
24 StorageNotInitialized,
26 UploadFailed,
28 DownloadFailed,
30 InvalidPointer,
32 IoError,
34 RuntimeError,
36 InvalidConfig,
38}
39
40impl fmt::Display for XetErrorKind {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 match self {
43 Self::StorageNotInitialized => write!(f, "StorageNotInitialized"),
44 Self::UploadFailed => write!(f, "UploadFailed"),
45 Self::DownloadFailed => write!(f, "DownloadFailed"),
46 Self::InvalidPointer => write!(f, "InvalidPointer"),
47 Self::IoError => write!(f, "IoError"),
48 Self::RuntimeError => write!(f, "RuntimeError"),
49 Self::InvalidConfig => write!(f, "InvalidConfig"),
50 }
51 }
52}
53
54impl XetError {
55 pub fn new(kind: XetErrorKind, message: impl Into<String>) -> Self {
57 Self {
58 kind,
59 message: message.into(),
60 }
61 }
62
63 pub fn kind(&self) -> XetErrorKind {
65 self.kind
66 }
67
68 pub fn message(&self) -> &str {
70 &self.message
71 }
72
73 pub fn to_ffi_code(self) -> libc::c_int {
75 to_ffi_error(self)
76 }
77}
78
79impl From<git2::Error> for XetError {
80 fn from(e: git2::Error) -> Self {
81 Self::new(XetErrorKind::IoError, format!("Git error: {e}"))
82 }
83}
84
85pub(crate) fn set_last_error(error: XetError) {
87 LAST_ERROR.with(|e| {
88 *e.borrow_mut() = Some(error);
89 });
90}
91
92pub fn get_last_error() -> Option<XetError> {
94 LAST_ERROR.with(|e| e.borrow().clone())
95}
96
97pub fn clear_last_error() {
99 LAST_ERROR.with(|e| {
100 *e.borrow_mut() = None;
101 });
102}
103
104pub(crate) fn to_ffi_error(error: XetError) -> libc::c_int {
106 tracing::error!("XET filter error: {}", error);
107 set_last_error(error);
108 -1
109}
110
111pub type Result<T> = std::result::Result<T, XetError>;
113
114pub trait FfiResult<T> {
116 fn to_ffi_code(self) -> libc::c_int;
117}
118
119impl<T> FfiResult<T> for Result<T> {
120 fn to_ffi_code(self) -> libc::c_int {
121 match self {
122 Ok(_) => 0,
123 Err(e) => to_ffi_error(e),
124 }
125 }
126}