// Copyright 2019-2024 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use std::{fmt::Display, path::PathBuf}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("{0}: {1}")] Context(String, Box), #[error("{0}")] GenericError(String), #[error("failed to bundle project {0}")] Bundler(#[from] Box), #[error("{context} {path}: {error}")] Fs { context: &'static str, path: PathBuf, error: std::io::Error, }, #[error("failed to run command {command}: {error}")] CommandFailed { command: String, error: std::io::Error, }, #[cfg(target_os = "macos")] #[error(transparent)] MacosSign(#[from] Box), } /// Convenient type alias of Result type. pub type Result = std::result::Result; pub trait Context { // Required methods fn context(self, context: C) -> Result where C: Display + Send + Sync + 'static; fn with_context(self, f: F) -> Result where C: Display + Send + Sync + 'static, F: FnOnce() -> C; } impl Context for std::result::Result { fn context(self, context: C) -> Result where C: Display + Send + Sync + 'static, { self.map_err(|e| Error::Context(context.to_string(), Box::new(e))) } fn with_context(self, f: F) -> Result where C: Display + Send + Sync + 'static, F: FnOnce() -> C, { self.map_err(|e| Error::Context(f().to_string(), Box::new(e))) } } impl Context for Option { fn context(self, context: C) -> Result where C: Display + Send + Sync + 'static, { self.ok_or_else(|| Error::GenericError(context.to_string())) } fn with_context(self, f: F) -> Result where C: Display + Send + Sync + 'static, F: FnOnce() -> C, { self.ok_or_else(|| Error::GenericError(f().to_string())) } } pub trait ErrorExt { fn fs_context(self, context: &'static str, path: impl Into) -> Result; } impl ErrorExt for std::result::Result { fn fs_context(self, context: &'static str, path: impl Into) -> Result { self.map_err(|error| Error::Fs { context, path: path.into(), error, }) } } macro_rules! bail { ($msg:literal $(,)?) => { return Err(crate::Error::GenericError($msg.into())) }; ($err:expr $(,)?) => { return Err(crate::Error::GenericError($err)) }; ($fmt:expr, $($arg:tt)*) => { return Err(crate::Error::GenericError(format!($fmt, $($arg)*))) }; } pub(crate) use bail;