Skip to content

Commit

Permalink
Control exit codes with ErrorWithExitCode
Browse files Browse the repository at this point in the history
  • Loading branch information
maciektr committed Mar 3, 2023
1 parent 94cf56d commit 395067a
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
10 changes: 6 additions & 4 deletions scarb/src/bin/scarb/commands/fmt.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
use anyhow::Result;

use crate::args::FmtArgs;
use crate::errors::ErrorWithExitCode;
use scarb::core::Config;
use scarb::ops;

#[tracing::instrument(skip_all, level = "info")]
pub fn run(args: FmtArgs, config: &Config) -> Result<()> {
let ws = ops::read_workspace(config.manifest_path(), config)?;
match ops::format(
if ops::format(
ops::FmtOptions {
check: args.check,
pkg_name: args.package,
color: !args.no_color,
},
&ws,
) {
Ok(true) => Ok(()),
_ => std::process::exit(1),
)? {
Ok(())
} else {
Err(ErrorWithExitCode::code(1).into())
}
}
3 changes: 0 additions & 3 deletions scarb/src/bin/scarb/errors.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use anyhow::Result;
use thiserror::Error;

pub type ScarbResult<T> = Result<T, ErrorWithExitCode>;

/// The ErrorWithExitCode is the error type used at Scarb's CLI-layer.
#[derive(Error, Debug)]
#[error("ErrorWithExitCode exit_code: {exit_code}")]
Expand Down
19 changes: 18 additions & 1 deletion scarb/src/bin/scarb/main.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
use std::env;

use anyhow::Result;
use anyhow::{Error, Result};
use clap::Parser;
use tracing::debug;
use tracing_log::AsTrace;
use tracing_subscriber::EnvFilter;

use crate::errors::ErrorWithExitCode;
use args::ScarbArgs;
use scarb::core::Config;
use scarb::ops;
use scarb::ui::Ui;

mod args;
mod commands;
mod errors;

fn main() {
let args = ScarbArgs::parse();
Expand All @@ -30,6 +33,20 @@ fn main() {
let ui = Ui::new(args.ui_verbosity(), args.output_format());

if let Err(err) = cli_main(args) {
exit_with_error(err, &ui);
}
}

fn exit_with_error(err: Error, ui: &Ui) {
debug!("exit_with_error; err={:?}", err);

if let Some(error_with_exit_code) = err.downcast_ref::<ErrorWithExitCode>() {
let ErrorWithExitCode { source, exit_code } = error_with_exit_code;
if let Some(source_err) = source {
ui.anyhow(source_err);
}
std::process::exit(*exit_code);
} else {
ui.anyhow(&err);
std::process::exit(1);
}
Expand Down

0 comments on commit 395067a

Please sign in to comment.