Skip to content

Commit

Permalink
Add error conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
c-git committed Nov 4, 2023
1 parent e71d2db commit dfa6c62
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 34 deletions.
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.75"
cargo-util = "0.2.6"
git2 = "0.18.1"
thiserror = "1.0.50"
60 changes: 26 additions & 34 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,51 +1,43 @@
use std::{error::Error, fmt::Display};
use thiserror::Error;

/// Enumerates the possible error values that can be generated by this crate
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum VSCError {
/// Unable to detect a version control system
#[error("no vcs")]
NoVCS,
/// Found a type of file that was not allowed. Includes listing of disallowed files found
#[error("{}", format_disallowed_files(dirty_files, staged_files))]
NotAllowedFilesFound {
/// Dirty files found (note this will be empty if dirty files are allowed)
dirty_files: Vec<String>,
/// Staged files found (note this will be empty if staged files are allowed)
staged_files: Vec<String>,
},
/// Errors produced outside of the ones from this library
#[error(transparent)]
Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error
}

impl Display for VSCError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
VSCError::NoVCS => write!(f, "no VCS found but this not allowed"),
VSCError::NotAllowedFilesFound {
dirty_files,
staged_files,
} => {
let mut files_list = String::new();
for file in dirty_files {
files_list.push_str(" * ");
files_list.push_str(file);
files_list.push_str(" (dirty)\n");
}
for file in staged_files {
files_list.push_str(" * ");
files_list.push_str(file);
files_list.push_str(" (staged)\n");
}

write!(
f,
"disallowed files found:\n\
\n\
{}\n\
",
files_list
)
}
}
fn format_disallowed_files(dirty_files: &[String], staged_files: &[String]) -> String {
let mut files_list = String::new();
for file in dirty_files {
files_list.push_str(" * ");
files_list.push_str(file);
files_list.push_str(" (dirty)\n");
}
for file in staged_files {
files_list.push_str(" * ");
files_list.push_str(file);
files_list.push_str(" (staged)\n");
}
}

impl Error for VSCError {}
format!(
"disallowed files found:\n\
\n\
{}\n\
",
files_list
)
}

0 comments on commit dfa6c62

Please sign in to comment.