1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//! Common error types.
//!
//! See [`InstallerError`] and [`InstallerErrorKind`] for details.
use std::fmt::Display;
/// Main error type for this crate.
#[derive(Debug, thiserror::Error)]
pub struct InstallerError {
kind: InstallerErrorKind,
context: String,
source: Option<Box<dyn std::error::Error + 'static + Send + Sync>>,
}
impl InstallerError {
/// Creates a new error with the given error kind.
pub fn new(kind: InstallerErrorKind) -> Self {
Self {
kind,
context: String::new(),
source: None,
}
}
/// Adds a source error.
pub fn with_source<S>(mut self, source: S) -> Self
where
S: std::error::Error + 'static + Send + Sync,
{
self.source = Some(Box::new(source));
self
}
/// Adds a string with a contextual description of the error.
pub fn with_context<C>(mut self, value: C) -> Self
where
C: AsRef<str>,
{
if !self.context.is_empty() {
self.context.push_str(": ");
}
self.context.push_str(value.as_ref());
self
}
/// Returns the error kind.
pub fn kind(&self) -> &InstallerErrorKind {
&self.kind
}
/// Returns the contextual description.
pub fn context(&self) -> &str {
&self.context
}
/// Returns whether the error kind is [`InstallerErrorKind::Io`].
pub fn is_io(&self) -> bool {
self.as_io().is_some()
}
/// Returns a reference to the IO error when the kind is [`InstallerErrorKind::Io`].
pub fn as_io(&self) -> Option<&std::io::Error> {
if self.kind.is_io() {
if let Some(source) = &self.source {
if let Some(error) = source.downcast_ref() {
return Some(error);
}
}
}
None
}
}
impl Display for InstallerError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if !self.context.is_empty() {
f.write_str(&self.context)?;
f.write_str(": ")?;
}
self.kind.fmt(f)?;
Ok(())
}
}
impl From<InstallerErrorKind> for InstallerError {
fn from(value: InstallerErrorKind) -> Self {
Self::new(value)
}
}
impl From<std::io::Error> for InstallerError {
fn from(value: std::io::Error) -> Self {
Self::new(InstallerErrorKind::Io).with_source(value)
}
}
impl From<AdditionalContext> for InstallerError {
fn from(value: AdditionalContext) -> Self {
Self::new(InstallerErrorKind::Other).with_source(value)
}
}
/// Error category for [`InstallerError`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum InstallerErrorKind {
/// Input/Output error usually from [`std::io::Error`].
#[error("input/output error")]
Io,
/// Invalid input or argument type to a function.
#[error("invalid input or argument")]
InvalidInput,
/// Invalid data or value provided to a function.
#[error("invalid data or value")]
InvalidData,
/// Unsupported OS family ("windows", "unix", etc.).
#[error("unsupported OS family")]
UnsupportedOsFamily,
/// Environment variable was missing or malformed.
#[error("invalid environment variable")]
InvalidEnvironmentVariable,
/// Filename of the binary could not be determined.
#[error("unknown executable path")]
UnknownExecutablePath,
/// [`crate::inst::PackageManifest`] has a invalid value.
#[error("invalid package manifest")]
InvalidPackageManifest,
/// Could not locate the [`DiskManifest`](crate::manifest::DiskManifest)
#[error("disk manifest not found")]
DiskManifestNotFound,
/// [`DiskManifest`](crate::manifest::DiskManifest) could not be parsed.
///
/// It may be tampered, corrupted, or an incompatible version.
#[error("malformed disk manifest")]
MalformedDiskManifest,
/// [`DiskManifest`](crate::manifest::DiskManifest) has an invalid value.
#[error("invalid disk manifest")]
InvalidDiskManifest,
/// The [`DiskManifest`](crate::manifest::DiskManifest) installed does not match this binary.
///
/// The given application ID needs to match to the one installed.
#[error("mismatched disk manifest")]
MismatchedDiskManifest,
/// There was a file in the destination that does not match the expected checksum.
#[error("unknown file in destination")]
UnknownFileInDestination,
/// Internal console/terminal library returned an error.
#[error("console/terminal error")]
Terminal,
/// Indicates an installation attempt when the application is (likely) already installed.
///
/// It may return a false positive on a prior failed install/uninstall.
#[error("application is already installed")]
AlreadyInstalled,
/// Indicates an uninstallation attempt when the application is (likely) not installed.
///
/// It may return a false positive on a prior failed install/uninstall.
#[error("application is not installed")]
NotInstalled,
/// Indicates a guided interactive session was aborted by the user.
#[error("interrupted by user")]
InterruptedByUser,
/// Any other error.
#[error("other")]
Other,
}
impl InstallerErrorKind {
/// Returns whether it is the Io variant.
pub fn is_io(&self) -> bool {
matches!(self, Self::Io)
}
}
/// Modify `Result<T, InstallerError>` with context.
pub(crate) trait AddInstallerContext<T> {
/// Add context using the given string when Err.
fn inst_context<C>(self, context: C) -> Result<T, InstallerError>
where
C: AsRef<str>;
/// Add context using the evaluated function when Err.
fn inst_contextc<C, CT>(self, context: C) -> Result<T, InstallerError>
where
C: FnOnce() -> CT,
CT: AsRef<str>;
}
impl<T> AddInstallerContext<T> for Result<T, InstallerError> {
fn inst_context<C>(self, context: C) -> Result<T, InstallerError>
where
C: AsRef<str>,
{
self.map_err(|error| error.with_context(context.as_ref()))
}
fn inst_contextc<C, CT>(self, context: C) -> Result<T, InstallerError>
where
C: FnOnce() -> CT,
CT: AsRef<str>,
{
self.map_err(|error| error.with_context(context().as_ref()))
}
}
/// Contains a contextual description of an error.
///
/// This isn't a real error, but allows injecting context in the error stack.
#[derive(Debug, thiserror::Error)]
#[error("{message}")]
pub(crate) struct AdditionalContext {
message: String,
#[source]
source: Box<dyn std::error::Error + Sync + Send + 'static>,
}
impl AdditionalContext {
/// Creates a new context error with the given message and source error.
pub fn new<E>(message: String, source: E) -> Self
where
E: std::error::Error + Sync + Send + 'static,
{
Self {
message,
source: Box::new(source),
}
}
}
/// Trait for wrapping errors in Result with descriptive context strings.
pub(crate) trait AddContext<T, E, A> {
/// Map the error with an error containing the context string.
#[allow(dead_code)]
fn with_context<C>(self, context: C) -> Result<T, A>
where
C: Into<String>;
/// Map the error with an error containing the context string evaluated from a function.
fn with_contextc<C, CT>(self, context: C) -> Result<T, A>
where
C: FnOnce(&E) -> CT,
CT: Into<String>;
}
impl<T, E> AddContext<T, E, AdditionalContext> for Result<T, E>
where
E: std::error::Error + Sync + Send + 'static,
{
fn with_context<C>(self, context: C) -> Result<T, AdditionalContext>
where
C: Into<String>,
{
self.map_err(|error| AdditionalContext::new(context.into(), error))
}
fn with_contextc<C, CT>(self, context: C) -> Result<T, AdditionalContext>
where
C: FnOnce(&E) -> CT,
CT: Into<String>,
{
self.map_err(|error| AdditionalContext::new(context(&error).into(), error))
}
}
pub(crate) fn format_error<E>(error: E) -> String
where
E: std::error::Error,
{
let mut buf = error.to_string();
let mut error: Box<&dyn std::error::Error> = Box::new(&error);
while let Some(source) = error.source() {
error = Box::new(source);
buf.push_str("\n↳");
buf.push_str(&error.to_string());
}
buf
}