Skip to main content

codeberg_cli/
run.rs

1use clap::Parser;
2
3use crate::{
4    actions::BergCommand,
5    render::json::JsonToStdout,
6    types::{config::BergConfig, output::OutputMode},
7};
8
9pub async fn berg_main() {
10    tracing_subscriber::fmt::init();
11
12    let cmd = BergCommand::parse();
13    let output_mode = cmd.output_mode;
14    if let Err(err) = cmd.run().await {
15        match output_mode {
16            // output a pretty, human-readable error to stderr
17            OutputMode::Pretty => output_pretty_error(err),
18            // This is useful for automation tooling and for testing ... otherwise we wouldn't be
19            // able to "catch" the error message and work with it easily
20            //
21            // note that this outputs to stdout for simplicity
22            OutputMode::Json => output_json_error(err),
23        }
24        std::process::exit(1);
25    }
26}
27
28fn output_json_error(error: miette::Error) {
29    // helper struct to output JSON which is a bit more structured than just a raw
30    // string
31    #[derive(serde::Serialize)]
32    struct BergErrorMessage {
33        // the error in text form
34        error_message: String,
35    }
36
37    BergErrorMessage {
38        error_message: error.to_string(),
39    }
40    .print_json()
41    .expect("String to JSON always works");
42}
43
44fn output_pretty_error(error: miette::Error) {
45    let config = match BergConfig::new() {
46        Ok(config) => config,
47        Err(e) => {
48            eprintln!("{e:?}");
49            std::process::exit(1);
50        }
51    };
52    let err = format!("{error:?}");
53    let table = config.make_table().add_error(err.trim());
54    eprintln!("\n{table}", table = table.show());
55}