Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manually implement Display/Error for Error #27

Merged
merged 1 commit into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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