Skip to main content

cargo_edit/
errors.rs

1use std::fmt::Display;
2
3/// Common result type
4pub type CargoResult<T> = anyhow::Result<T>;
5
6/// Common error type
7pub type Error = anyhow::Error;
8
9pub use anyhow::Context;
10
11/// CLI-specific result
12pub type CliResult = Result<(), CliError>;
13
14#[derive(Debug)]
15/// The CLI error is the error type used at Cargo's CLI-layer.
16///
17/// All errors from the lib side of Cargo will get wrapped with this error.
18/// Other errors (such as command-line argument validation) will create this
19/// directly.
20pub struct CliError {
21    /// The error to display. This can be `None` in rare cases to exit with a
22    /// code without displaying a message. For example `cargo run -q` where
23    /// the resulting process exits with a nonzero code (on Windows), or an
24    /// external subcommand that exits nonzero (we assume it printed its own
25    /// message).
26    pub error: Option<anyhow::Error>,
27    /// The process exit code.
28    pub exit_code: i32,
29}
30
31impl CliError {
32    /// Attach an error code to an error
33    pub fn new(error: anyhow::Error, code: i32) -> CliError {
34        CliError {
35            error: Some(error),
36            exit_code: code,
37        }
38    }
39
40    /// Silent error
41    pub fn code(code: i32) -> CliError {
42        CliError {
43            error: None,
44            exit_code: code,
45        }
46    }
47}
48
49impl From<anyhow::Error> for CliError {
50    fn from(err: anyhow::Error) -> CliError {
51        CliError::new(err, 101)
52    }
53}
54
55#[cfg(feature = "clap")]
56impl From<clap::Error> for CliError {
57    fn from(err: clap::Error) -> CliError {
58        #[allow(clippy::bool_to_int_with_if)]
59        let code = if err.use_stderr() { 1 } else { 0 };
60        CliError::new(err.into(), code)
61    }
62}
63
64impl From<std::io::Error> for CliError {
65    fn from(err: std::io::Error) -> CliError {
66        CliError::new(err.into(), 1)
67    }
68}
69
70pub(crate) fn non_existent_table_err(table: impl Display) -> Error {
71    anyhow::format_err!("The table `{table}` could not be found.")
72}
73
74pub(crate) fn non_existent_dependency_err(name: impl Display, table: impl Display) -> Error {
75    anyhow::format_err!("The dependency `{name}` could not be found in `{table}`.",)
76}
77
78pub(crate) fn unsupported_version_req(req: impl Display) -> Error {
79    anyhow::format_err!("Support for modifying {req} is currently unsupported")
80}
81
82pub(crate) fn invalid_release_level(actual: impl Display, version: impl Display) -> Error {
83    anyhow::format_err!("Cannot increment the {actual} field for {version}")
84}