Skip to main content

find_crate/
error.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3use alloc::string::String;
4use core::fmt;
5use std::io;
6
7use crate::MANIFEST_DIR;
8
9/// An error which occurred while parsing the TOML manifest
10#[derive(Debug)]
11pub struct TomlError {
12    pub(super) error: toml::de::Error,
13}
14
15impl fmt::Display for TomlError {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        self.error.fmt(f)
18    }
19}
20
21impl std::error::Error for TomlError {
22    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
23        Some(&self.error)
24    }
25}
26
27/// An error that occurred when getting manifest.
28#[derive(Debug)]
29#[non_exhaustive]
30pub enum Error {
31    /// The [`CARGO_MANIFEST_DIR`] environment variable not found.
32    ///
33    /// [`CARGO_MANIFEST_DIR`]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates
34    NotFoundManifestDir,
35
36    /// The manifest is invalid for the following reason.
37    InvalidManifest(String),
38
39    /// The crate with the specified name not found. This error occurs only from [`find_crate`].
40    ///
41    /// [`find_crate`]: super::find_crate
42    NotFound,
43
44    /// An error occurred while trying to open or to read the manifest file.
45    Io(io::Error),
46
47    /// An error occurred while trying to parse the manifest file.
48    Toml(TomlError),
49}
50
51impl fmt::Display for Error {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match self {
54            Error::NotFoundManifestDir => {
55                write!(f, "`{MANIFEST_DIR}` environment variable not found")
56            }
57            Error::InvalidManifest(reason) => {
58                write!(f, "The manifest is invalid because: {reason}")
59            }
60            Error::NotFound => {
61                f.write_str("the crate with the specified name not found in dependencies")
62            }
63            Error::Io(e) => write!(f, "an error occurred while to open or to read: {e}"),
64            Error::Toml(e) => write!(f, "an error occurred while parsing the manifest file: {e}"),
65        }
66    }
67}
68
69impl std::error::Error for Error {
70    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
71        match self {
72            Error::Io(e) => Some(e),
73            Error::Toml(e) => Some(e),
74            _ => None,
75        }
76    }
77}
78
79impl From<io::Error> for Error {
80    fn from(e: io::Error) -> Self {
81        Error::Io(e)
82    }
83}