use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Outcome {
Clean,
Findings,
Incomplete,
}
impl Outcome {
pub(crate) fn code(self) -> u8 {
match self {
Self::Clean => 0,
Self::Findings => 1,
Self::Incomplete => 2,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum CliError {
Usage(String),
Io {
path: String,
detail: String,
},
Parse {
path: String,
detail: String,
},
UnsupportedSchema(String),
Unsupported(String),
MissingEntity(String),
WrongEntityType(String),
MissingReference(String),
InvalidModel(String),
BudgetExceeded(String),
Write(String),
}
impl CliError {
pub(crate) fn exit_code(&self) -> u8 {
2
}
pub(crate) fn kind(&self) -> &'static str {
match self {
Self::Usage(_) => "usage",
Self::Io { .. } => "io",
Self::Parse { .. } => "parse",
Self::UnsupportedSchema(_) => "unsupported-schema",
Self::Unsupported(_) => "unsupported",
Self::MissingEntity(_) => "missing-entity",
Self::WrongEntityType(_) => "wrong-entity-type",
Self::MissingReference(_) => "missing-reference",
Self::InvalidModel(_) => "invalid-model",
Self::BudgetExceeded(_) => "budget-exceeded",
Self::Write(_) => "write",
}
}
pub(crate) fn stdout(error: &std::io::Error) -> Self {
Self::Io {
path: "-".to_owned(),
detail: error.to_string(),
}
}
}
impl fmt::Display for CliError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: ", self.kind())?;
match self {
Self::Io { path, detail } | Self::Parse { path, detail } => {
write!(f, "{path}: {detail}")
}
Self::Usage(detail)
| Self::UnsupportedSchema(detail)
| Self::Unsupported(detail)
| Self::MissingEntity(detail)
| Self::WrongEntityType(detail)
| Self::MissingReference(detail)
| Self::InvalidModel(detail)
| Self::BudgetExceeded(detail)
| Self::Write(detail) => f.write_str(detail),
}
}
}
pub(crate) type CliResult<T> = Result<T, CliError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn findings_and_refusals_exit_differently() {
assert_eq!(Outcome::Clean.code(), 0);
assert_eq!(Outcome::Findings.code(), 1);
assert_eq!(Outcome::Incomplete.code(), 2);
let refusal = CliError::UnsupportedSchema("IFC9".into());
assert_eq!(refusal.exit_code(), 2);
assert_eq!(refusal.to_string(), "unsupported-schema: IFC9");
}
}