From 0a20e4dc26d558bbabe2ffde6a7f3947af7d0657 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ga=C3=ABtan=20Lehmann?= Date: Fri, 2 Feb 2024 01:25:26 +0100 Subject: [PATCH] refactor: rename error type and variants for a more compact code wihout Error repetition --- src/edit.rs | 17 +++++++---------- src/env.rs | 6 +++--- src/error.rs | 38 +++++++++++++++++++------------------- src/util.rs | 18 ++++++++---------- 4 files changed, 37 insertions(+), 42 deletions(-) diff --git a/src/edit.rs b/src/edit.rs index 7bbca03..4616bd8 100644 --- a/src/edit.rs +++ b/src/edit.rs @@ -7,7 +7,7 @@ use treediff::value::Key; use treediff::Mutable; use crate::cli::EditArgs; -use crate::error::{AppError, IOResultExt, Result}; +use crate::error::{IOResultExt, Result, YageError}; use crate::util::{decrypt_yaml, encrypt_yaml, load_identities, load_recipients}; pub fn edit(args: &EditArgs) -> Result<()> { @@ -24,12 +24,9 @@ pub fn edit(args: &EditArgs) -> Result<()> { // original file, but in a temporary directory. This way the user knows which file he is // editing if its editor shows the file name. let dir = tempdir()?; - let filename = args - .file - .file_name() - .ok_or(AppError::InvalidFileNameError { - path: args.file.clone(), - })?; + let filename = args.file.file_name().ok_or(YageError::InvalidFileName { + path: args.file.clone(), + })?; let temp_file = dir.path().join(filename); { let output = File::create(&temp_file).path_ctx(&temp_file)?; @@ -41,7 +38,7 @@ pub fn edit(args: &EditArgs) -> Result<()> { .spawn()? .wait()?; if !status.success() { - return Err(AppError::EditorError); + return Err(YageError::Editor); } // load the data edited by the user let edited_data: sy::Value = sy::from_reader(File::open(&temp_file)?)?; @@ -77,11 +74,11 @@ fn yaml_get<'a>(data: &'a sy::Value, keys: &[Key]) -> Result<&'a sy::Value> { let key = &keys[0]; match key { Key::String(k) => { - let value = data.get(k).ok_or(AppError::KeyNotFoundError)?; + let value = data.get(k).ok_or(YageError::KeyNotFound)?; yaml_get(value, &keys[1..]) } Key::Index(i) => { - let value = data.get(i).ok_or(AppError::KeyNotFoundError)?; + let value = data.get(i).ok_or(YageError::KeyNotFound)?; yaml_get(value, &keys[1..]) } } diff --git a/src/env.rs b/src/env.rs index c4edde9..c0b075e 100644 --- a/src/env.rs +++ b/src/env.rs @@ -4,7 +4,7 @@ use std::process::Command; use serde_yaml as sy; use crate::cli::EnvArgs; -use crate::error::{AppError, Result}; +use crate::error::{Result, YageError}; use crate::util::{decrypt_yaml, load_identities, stdin_or_file}; pub fn env(args: &EnvArgs) -> Result<()> { @@ -38,7 +38,7 @@ fn build_env(data: &sy::Value) -> Result> { env.insert(key, value); } } - _ => Err(AppError::NotAMapError)?, + _ => Err(YageError::NotAMap)?, } Ok(env) } @@ -55,6 +55,6 @@ fn plain_value_to_string(data: &sy::Value) -> Result { n.as_u64().unwrap().to_string() } } - _ => Err(AppError::NotAStringOrNumberError)?, + _ => Err(YageError::NotAStringOrNumber)?, }) } diff --git a/src/error.rs b/src/error.rs index eab0044..d04557f 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,46 +5,46 @@ use serde_yaml as sy; use thiserror::Error; #[derive(Error, Debug)] -pub enum AppError { +pub enum YageError { #[error("{path}: {source}")] - PathIoError { + PathIo { path: PathBuf, source: std::io::Error, }, #[error(transparent)] - IoError(#[from] std::io::Error), + Io(#[from] std::io::Error), #[error(transparent)] - YamlError(#[from] sy::Error), + Yaml(#[from] sy::Error), #[error("can't parse recipient {recipient}: {message}")] - RecipientParseError { recipient: String, message: String }, + RecipientParse { recipient: String, message: String }, #[error("can't parse key: {message}")] - KeyParseError { message: String }, + KeyParse { message: String }, #[error(transparent)] - DecryptError(#[from] age::DecryptError), + Decrypt(#[from] age::DecryptError), #[error(transparent)] - EncryptError(#[from] age::EncryptError), + Encrypt(#[from] age::EncryptError), #[error(transparent)] - Utf8Error(#[from] std::string::FromUtf8Error), + Utf8(#[from] std::string::FromUtf8Error), #[error(transparent)] - Base64DecodeError(#[from] base64::DecodeError), + Base64Decode(#[from] base64::DecodeError), #[error("no recipients provided")] - NoRecipientsError, + NoRecipients, #[error("passphrase not supported")] - PassphraseUnsupportedError, + PassphraseUnsupported, #[error("yaml value is not a map")] - NotAMapError, + NotAMap, #[error("yaml value is not a string or a number")] - NotAStringOrNumberError, + NotAStringOrNumber, #[error("invalid file name: {path:?}")] - InvalidFileNameError { path: PathBuf }, + InvalidFileName { path: PathBuf }, #[error("editor exited with an error status")] - EditorError, + Editor, #[error("key not found")] - KeyNotFoundError, + KeyNotFound, } /// Alias for a `Result` with the error type `AppError`. -pub type Result = result::Result; +pub type Result = result::Result; pub trait IOResultExt { fn path_ctx>(self, path: P) -> Result; @@ -52,7 +52,7 @@ pub trait IOResultExt { impl IOResultExt for io::Result { fn path_ctx>(self, path: P) -> Result { - self.map_err(|source| AppError::PathIoError { + self.map_err(|source| YageError::PathIo { source, path: path.into(), }) diff --git a/src/util.rs b/src/util.rs index c977f51..fd7542b 100644 --- a/src/util.rs +++ b/src/util.rs @@ -9,7 +9,7 @@ use base64::prelude::*; use serde_yaml as sy; use substring::Substring; -use crate::error::{AppError, IOResultExt, Result}; +use crate::error::{IOResultExt, Result, YageError}; pub fn stdout_or_file(path: &Path) -> Result> { Ok(if path == Path::new("-") { @@ -65,7 +65,7 @@ pub fn decrypt_value(s: &str, identities: &[x25519::Identity]) -> Result Ok(d), - _ => Err(AppError::PassphraseUnsupportedError), + _ => Err(YageError::PassphraseUnsupported), }?; let mut decrypted = vec![]; let mut reader = decryptor.decrypt(identities.iter().map(|i| i as &dyn age::Identity))?; @@ -82,7 +82,7 @@ pub fn load_identities(keys: &[String], key_files: &[PathBuf]) -> Result Res .map(|r| Box::new(r.clone()) as Box) .collect::(); let mut encrypted = vec![]; - let encryptor = - age::Encryptor::with_recipients(recipients).ok_or(AppError::NoRecipientsError)?; + let encryptor = age::Encryptor::with_recipients(recipients).ok_or(YageError::NoRecipients)?; // let mut armored = ArmoredWriter::wrap_output(&mut encrypted, Format::AsciiArmor)?; let mut writer = encryptor.wrap_output(&mut encrypted)?; writer.write_all(data.as_bytes())?; @@ -160,7 +159,7 @@ pub fn load_recipients( for recipient in recipients.iter() { debug!("loading recipient: {recipient}"); let recipient = - x25519::Recipient::from_str(recipient).map_err(|e| AppError::RecipientParseError { + x25519::Recipient::from_str(recipient).map_err(|e| YageError::RecipientParse { recipient: recipient.to_owned(), message: e.into(), })?; @@ -172,12 +171,11 @@ pub fn load_recipients( let input = stdin_or_file(path)?; for recipient in input.lines() { let recipient = recipient.path_ctx(path)?; - let recipient = x25519::Recipient::from_str(&recipient).map_err(|e| { - AppError::RecipientParseError { + let recipient = + x25519::Recipient::from_str(&recipient).map_err(|e| YageError::RecipientParse { recipient: recipient.to_owned(), message: e.into(), - } - })?; + })?; res.push(recipient); } }