Skip to content

Commit

Permalink
Merge pull request #27 from coolreader18/manual-error
Browse files Browse the repository at this point in the history
Manually implement Display/Error for Error
  • Loading branch information
bkchr authored Dec 15, 2022
2 parents 6ccf98f + 52ca9d9 commit fb8a49a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 8 deletions.
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ readme = "./README.md"

[dependencies]
toml = "0.5.2"
thiserror = "1.0.24"
once_cell = "1.13.0"

[dev-dependencies]
Expand Down
42 changes: 35 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ at your option.

use std::{
collections::btree_map::{self, BTreeMap},
env,
env, fmt,
fs::{self, File},
io::{self, Read},
path::{Path, PathBuf},
Expand All @@ -70,20 +70,48 @@ use once_cell::sync::Lazy;
use toml::{self, value::Table};

/// Error type used by this crate.
#[derive(Debug, thiserror::Error)]
#[derive(Debug)]
pub enum Error {
#[error("Could not find `Cargo.toml` in manifest dir: `{0}`.")]
NotFound(PathBuf),
#[error("`CARGO_MANIFEST_DIR` env variable not set.")]
CargoManifestDirNotSet,
#[error("Could not read `{path}`.")]
CouldNotRead { path: PathBuf, source: io::Error },
#[error("Invalid toml file.")]
InvalidToml { source: toml::de::Error },
#[error("Could not find `{crate_name}` in `dependencies` or `dev-dependencies` in `{path}`!")]
CrateNotFound { crate_name: String, path: PathBuf },
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::CouldNotRead { source, .. } => Some(source),
Error::InvalidToml { source } => Some(source),
_ => None,
}
}
}

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::NotFound(path) => write!(
f,
"Could not find `Cargo.toml` in manifest dir: `{}`.",
path.display()
),
Error::CargoManifestDirNotSet => {
f.write_str("`CARGO_MANIFEST_DIR` env variable not set.")
}
Error::CouldNotRead { path, .. } => write!(f, "Could not read `{}`.", path.display()),
Error::InvalidToml { .. } => f.write_str("Invalid toml file."),
Error::CrateNotFound { crate_name, path } => write!(
f,
"Could not find `{}` in `dependencies` or `dev-dependencies` in `{}`!",
crate_name,
path.display(),
),
}
}
}

/// The crate as found by [`crate_name`].
#[derive(Debug, PartialEq, Clone, Eq)]
pub enum FoundCrate {
Expand Down

0 comments on commit fb8a49a

Please sign in to comment.