Skip to content

Commit

Permalink
fix(rust): error chain is kept in ockam_command crate
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianbenavides committed Nov 5, 2024
1 parent 8ff87f0 commit f6e24d5
Show file tree
Hide file tree
Showing 34 changed files with 256 additions and 265 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion implementations/rust/ockam/ockam_api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ jaq-parse = "1"
jaq-std = "1"
kafka-protocol = "0.10"
log = "0.4"
miette = "7"
miette = { version = "7.2.0", features = ["fancy-no-backtrace"] }
minicbor = { version = "0.24.1", features = ["alloc", "derive"] }
nix = { version = "0.29", features = ["signal"] }
once_cell = { version = "1", default-features = false }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,15 +104,15 @@ impl CliState {
let message =
"There should be a default space set for the current user. Please re-enroll";
error!("{}", message);
return Err(CliStateError::from(message))?;
return Err(CliStateError::Other(message.into()))?;
}

let default_project_exists = self.projects().get_default_project().await.is_ok();
if !default_project_exists {
let message =
"There should be a default project set for the current user. Please re-enroll";
error!("{}", message);
return Err(CliStateError::from(message))?;
return Err(CliStateError::Other(message.into()))?;
}

Ok(true)
Expand Down
32 changes: 7 additions & 25 deletions implementations/rust/ockam/ockam_api/src/cli_state/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#![allow(clippy::unconditional_recursion)]
use miette::Diagnostic;
use ockam_core::Error;
use thiserror::Error;

pub type Result<T> = std::result::Result<T, CliStateError>;
Expand All @@ -23,14 +22,18 @@ pub enum CliStateError {
#[diagnostic(code("OCK500"))]
Ockam(#[from] ockam_core::Error),

#[error(transparent)]
#[diagnostic(code("OCK500"))]
MultiAddr(#[from] ockam_multiaddr::Error),

#[error("A {resource} named {name} already exists")]
#[diagnostic(
code("OCK409"),
help("Please try using a different name or delete the existing {resource}")
)]
AlreadyExists { resource: String, name: String },

#[error("Unable to find {resource} named {name}")]
#[error("There is no {resource} with name {name}")]
#[diagnostic(code("OCK404"))]
ResourceNotFound { resource: String, name: String },

Expand Down Expand Up @@ -62,38 +65,17 @@ pub enum CliStateError {
Other(#[from] Box<dyn std::error::Error + Send + Sync>),
}

// TODO: remove this and use ApiError instead of ockam_core::Error within the crate
impl From<CliStateError> for ockam_core::Error {
#[track_caller]
fn from(e: CliStateError) -> Self {
match e {
CliStateError::Ockam(e) => e,
_ => Error::new(
_ => ockam_core::Error::new(
ockam_core::errcode::Origin::Application,
ockam_core::errcode::Kind::Internal,
e,
),
}
}
}

impl From<ockam_multiaddr::Error> for CliStateError {
#[track_caller]
fn from(e: ockam_multiaddr::Error) -> Self {
e.into()
}
}

macro_rules! gen_from_impl {
($t:ty) => {
impl From<$t> for CliStateError {
#[track_caller]
fn from(e: $t) -> Self {
CliStateError::Other(e.into())
}
}
};
}

gen_from_impl!(miette::Error);
gen_from_impl!(&str);
gen_from_impl!(dialoguer::Error);
9 changes: 4 additions & 5 deletions implementations/rust/ockam/ockam_api/src/cli_state/nodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,11 +333,10 @@ impl CliState {
if let Some(node) = self.nodes_repository().get_node(node_name).await? {
Ok(node)
} else {
Err(Error::new(
Origin::Api,
Kind::NotFound,
format!("There is no node with name {node_name}"),
))?
Err(CliStateError::ResourceNotFound {
resource: "node".to_string(),
name: node_name.to_string(),
})?
}
}

Expand Down
2 changes: 2 additions & 0 deletions implementations/rust/ockam/ockam_api/src/ui/terminal/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
pub const PADDING: &str = " ";
/// Left padding for all terminal output that starts with an icon
pub const ICON_PADDING: &str = " ";
/// Left padding for miette errors
pub const MIETTE_PADDING: &str = " ";
/// A two-space indentation for nested terminal output
pub const INDENTATION: &str = " ";

Expand Down
2 changes: 0 additions & 2 deletions implementations/rust/ockam/ockam_command/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,11 @@ rustls-native-certs = "0.8.0"
rustls-pki-types = "1.7.0"
semver = "1.0.23"
serde = { version = "1", features = ["derive"] }
serde_bare = { version = "0.5.0", default-features = false, features = ["alloc"] }
serde_json = "1"
serde_yaml = "0.9"
shellexpand = { version = "3.1.0", default-features = false, features = ["base-0"] }
syntect = { version = "5.2.0", default-features = false, features = ["default-syntaxes", "regex-onig"] }
thiserror = "1"
time = { version = "0.3", default-features = false, features = ["std", "local-offset"] }
tokio = { version = "1.41.0", features = ["full"] }
tokio-retry = "0.3"
tracing = { version = "0.1", default-features = false }
Expand Down
13 changes: 5 additions & 8 deletions implementations/rust/ockam/ockam_command/src/authority/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::str::FromStr;

use clap::Args;
use colorful::Colorful;
use miette::{miette, IntoDiagnostic};
use miette::{miette, IntoDiagnostic, WrapErr};
use serde::{Deserialize, Serialize};
use tokio::fs::read_to_string;
use tokio_retry::strategy::FixedInterval;
Expand All @@ -26,10 +26,10 @@ use ockam_core::compat::collections::BTreeMap;
use ockam_core::compat::fmt;

use crate::node::util::run_ockam;
use crate::util::embedded_node_that_is_not_stopped;
use crate::util::foreground_args::{wait_for_exit_signal, ForegroundArgs};
use crate::util::parsers::internet_address_parser;
use crate::util::{async_cmd, local_cmd};
use crate::util::{embedded_node_that_is_not_stopped, exitcode};
use crate::{docs, CommandGlobalOpts, Result};

const LONG_ABOUT: &str = include_str!("./static/create/long_about.txt");
Expand Down Expand Up @@ -530,12 +530,9 @@ impl CreateCommand {

/// Return a list of trusted identities passed as a JSON string on the command line
fn parse_trusted_identities(values: &str) -> Result<TrustedIdentities> {
serde_json::from_str::<TrustedIdentities>(values).map_err(|e| {
crate::Error::new(
exitcode::CONFIG,
miette!("Cannot parse the trusted identities: {}", e),
)
})
serde_json::from_str::<TrustedIdentities>(values)
.into_diagnostic()
.wrap_err("Cannot parse the trusted identities")
}

#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
Expand Down
20 changes: 6 additions & 14 deletions implementations/rust/ockam/ockam_command/src/command.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use clap::Parser;
use colorful::Colorful;
use miette::GraphicalReportHandler;
use ockam_api::fmt_warn;
use opentelemetry::trace::{Link, SpanBuilder, TraceContextExt, Tracer};
use opentelemetry::{global, Context};
Expand All @@ -10,11 +9,11 @@ use ockam_core::OCKAM_TRACER_NAME;

use crate::command_events::{add_command_error_event, add_command_event};
use crate::command_global_opts::CommandGlobalOpts;
use crate::docs;
use crate::global_args::GlobalArgs;
use crate::subcommand::OckamSubcommand;
use crate::upgrade::check_if_an_upgrade_is_available;
use crate::version::Version;
use crate::{docs, ErrorReportHandler};

const ABOUT: &str = include_str!("./static/about.txt");
const LONG_ABOUT: &str = include_str!("./static/long_about.txt");
Expand All @@ -33,7 +32,7 @@ about = docs::about(ABOUT),
long_about = docs::about(LONG_ABOUT),
after_long_help = docs::after_help(AFTER_LONG_HELP),
version,
long_version = Version::long(),
long_version = Version::clappy(),
next_help_heading = "Global Options",
disable_help_flag = true,
)]
Expand Down Expand Up @@ -67,17 +66,10 @@ impl OckamCommand {
.install_default()
.expect("Failed to install ring crypto provider");

// Sets a hook using our own Error Report Handler
// This allows us to customize how we
// format the error messages and their content.
let _hook_result = miette::set_hook(Box::new(|_| {
Box::new(
GraphicalReportHandler::new()
.with_cause_chain()
.with_footer(Version::short().light_gray().to_string())
.with_urls(false),
)
}));
// Sets a hook using our own Error Report Handler.
// This allows us to customize how we format the error messages and their content.
let _hook_result = miette::set_hook(Box::new(|_| Box::new(ErrorReportHandler::new())));

let options = CommandGlobalOpts::new(&arguments, &self.global_args, &self.subcommand)?;

if let Err(err) = check_if_an_upgrade_is_available(&options) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl CommandGlobalOpts {
debug!("Arguments: {}", arguments.join(" "));
debug!("Global arguments: {:#?}", &global_args);
debug!("Command: {:#?}", &cmd);
debug!("Version: {}", Version::short());
debug!("Version: {}", Version::new());

info!("Tracing initialized");
debug!("{:#?}", logging_configuration);
Expand Down
10 changes: 4 additions & 6 deletions implementations/rust/ockam/ockam_command/src/credential/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use clap::{Args, Subcommand};
use colorful::core::StrMarker;
use colorful::Colorful;
use miette::miette;
use serde::Serialize;
use serde_json::json;

Expand All @@ -14,7 +14,6 @@ pub(crate) use store::StoreCommand;
pub(crate) use verify::VerifyCommand;

use crate::credential::list::ListCommand;
use crate::error::Error;
use crate::{CommandGlobalOpts, Result};

pub(crate) mod issue;
Expand Down Expand Up @@ -81,10 +80,9 @@ impl CredentialOutput {
let credential_data = credential.credential.get_credential_data()?;
let purpose_key_data = credential.purpose_key_attestation.get_attestation_data()?;

let subject = credential_data.subject.ok_or(Error::InternalError {
error_message: "credential subject is missing".to_str(),
exit_code: 1,
})?;
let subject = credential_data
.subject
.ok_or(miette!("credential subject is missing"))?;

let mut attributes = HashMap::<String, String>::default();
for (k, v) in credential_data.subject_attributes.map {
Expand Down
26 changes: 12 additions & 14 deletions implementations/rust/ockam/ockam_command/src/entry_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@ use std::process::exit;
use clap::Parser;
use miette::IntoDiagnostic;

use crate::{
add_command_error_event, has_help_flag, has_version_flag, pager, replace_hyphen_with_stdin,
util::exitcode, version::Version, OckamCommand,
};
use ockam_api::cli_state::CliState;
use ockam_api::fmt_log;
use ockam_api::logs::{
logging_configuration, Colored, ExportingConfiguration, LogLevelWithCratesFilter,
LoggingTracing,
};

use crate::{
add_command_error_event, has_help_flag, has_version_flag, pager, replace_hyphen_with_stdin,
util::exitcode, version::Version, ErrorReportHandler, OckamCommand,
};
use ockam_api::output::Output;

/// Main method for running the `ockam` executable:
///
Expand All @@ -25,8 +24,6 @@ pub fn run() -> miette::Result<()> {
.map(replace_hyphen_with_stdin)
.collect::<Vec<_>>();

let _ = miette::set_hook(Box::new(|_e| Box::new(ErrorReportHandler::new())));

if has_version_flag(&input) {
print_version_and_exit();
}
Expand Down Expand Up @@ -66,11 +63,12 @@ pub fn run() -> miette::Result<()> {
}

fn print_version_and_exit() {
let version_msg = Version::long();
let version_msg_vec = version_msg.split('\n').collect::<Vec<_>>();
println!("{}", fmt_log!("ockam {}", version_msg_vec[0]));
for item in version_msg_vec.iter().skip(1) {
println!("{}", fmt_log!("{}", item));
}
println!(
"{}",
Version::new()
.multiline()
.item()
.expect("Failed to process version")
);
exit(exitcode::OK);
}
Loading

0 comments on commit f6e24d5

Please sign in to comment.