Skip to content

Commit

Permalink
refactor: rename error type and variants
Browse files Browse the repository at this point in the history
for a more compact code wihout Error repetition
  • Loading branch information
glehmann committed Feb 2, 2024
1 parent 4236a87 commit 0a20e4d
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 42 deletions.
17 changes: 7 additions & 10 deletions src/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<()> {
Expand All @@ -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)?;
Expand All @@ -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)?)?;
Expand Down Expand Up @@ -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..])
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<()> {
Expand Down Expand Up @@ -38,7 +38,7 @@ fn build_env(data: &sy::Value) -> Result<HashMap<String, String>> {
env.insert(key, value);
}
}
_ => Err(AppError::NotAMapError)?,
_ => Err(YageError::NotAMap)?,
}
Ok(env)
}
Expand All @@ -55,6 +55,6 @@ fn plain_value_to_string(data: &sy::Value) -> Result<String> {
n.as_u64().unwrap().to_string()
}
}
_ => Err(AppError::NotAStringOrNumberError)?,
_ => Err(YageError::NotAStringOrNumber)?,
})
}
38 changes: 19 additions & 19 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,54 +5,54 @@ 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<T> = result::Result<T, AppError>;
pub type Result<T> = result::Result<T, YageError>;

pub trait IOResultExt<T> {
fn path_ctx<P: Into<PathBuf>>(self, path: P) -> Result<T>;
}

impl<T> IOResultExt<T> for io::Result<T> {
fn path_ctx<P: Into<PathBuf>>(self, path: P) -> Result<T> {
self.map_err(|source| AppError::PathIoError {
self.map_err(|source| YageError::PathIo {
source,
path: path.into(),
})
Expand Down
18 changes: 8 additions & 10 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Box<dyn Write>> {
Ok(if path == Path::new("-") {
Expand Down Expand Up @@ -65,7 +65,7 @@ pub fn decrypt_value(s: &str, identities: &[x25519::Identity]) -> Result<sy::Val
let encrypted = BASE64_STANDARD.decode(encoded)?;
let decryptor = match age::Decryptor::new(&encrypted[..])? {
age::Decryptor::Recipients(d) => 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))?;
Expand All @@ -82,7 +82,7 @@ pub fn load_identities(keys: &[String], key_files: &[PathBuf]) -> Result<Vec<x25
for key in keys.iter() {
debug!("loading key: {key}");
let key = x25519::Identity::from_str(key)
.map_err(|e| AppError::KeyParseError { message: e.into() })?;
.map_err(|e| YageError::KeyParse { message: e.into() })?;
identities.push(key);
}
for key_file in key_files.iter() {
Expand Down Expand Up @@ -141,8 +141,7 @@ pub fn encrypt_value(value: &sy::Value, recipients: &[x25519::Recipient]) -> Res
.map(|r| Box::new(r.clone()) as Box<dyn age::Recipient + Send + 'static>)
.collect::<Recipients>();
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())?;
Expand All @@ -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(),
})?;
Expand All @@ -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);
}
}
Expand Down

0 comments on commit 0a20e4d

Please sign in to comment.