aboutsummaryrefslogtreecommitdiff
path: root/examples/example-exitcode/src/main.rs
blob: 6b22eae8cf0c65576c467c963e490988dfcb8a02 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! Example Error Handling
//!
//! > This example demonstrates how to handle errors in Mingling, including custom error types and error rendering.
//!
//! Run:
//! ```bash
//! cargo run --manifest-path examples/example-exitcode/Cargo.toml --quiet -- hello Alice
//! cargo run --manifest-path examples/example-exitcode/Cargo.toml --quiet -- hello
//! ```
//!
//! Output:
//! ```plaintext
//! Hello, Alice
//! No name provided (with exit code 1)
//! ```

use mingling::{
    macros::help,
    prelude::*,
    res::ResExitCode,
    setup::{BasicProgramSetup, ExitCodeSetup},
};
use std::io::Write;

fn main() {
    let mut program = ThisProgram::new();
    program.with_setup(BasicProgramSetup);

    // --------- IMPORTANT ---------
    // Register `ExitCodeSetup` for the program to enable exit codes
    program.with_setup(ExitCodeSetup::default());
    // --------- IMPORTANT ---------

    program.with_dispatcher(CMDHello);
    program.exec_and_exit();
}

dispatcher!("hello", CMDHello => EntryHello);

pack!(ErrorNoNameProvided = ());
pack!(ResultName = String);

#[chain]
fn handle_hello(args: EntryHello) -> Next {
    let Some(name) = args.inner.first().cloned() else {
        // If no name is provided, pass ErrorNoNameProvided
        return ErrorNoNameProvided::default().to_render();
    };

    // If the name is valid, pass ResultName
    ResultName::new(name).to_render()
}

/// Renders a successful greeting with the given name.
#[renderer]
fn render_result_name(name: ResultName) -> RenderResult {
    let mut result = RenderResult::new();
    writeln!(result, "Hello, {}", *name).ok();
    result
}

#[help]
fn help_hello(_p: EntryHello, ec: &mut ResExitCode) -> RenderResult {
    let mut result = RenderResult::new();
    writeln!(result, "Usage: hello <NAME>").ok();
    ec.exit_code = 2;
    result
}

// Define renderer, render error message                      _______________ Inject exit code resource
//                                                           /
/// Renders the error when no name is provided               |
#[renderer] //                                               vvvvvvvvvvvvvvvv
fn render_error_no_name_provided(_: ErrorNoNameProvided, ec: &mut ResExitCode) -> RenderResult {
    ec.exit_code = 1;

    let mut result = RenderResult::new();

    // Prompt when no name is provided
    writeln!(result, "No name provided (with exit code 1)").ok();
    result
}

gen_program!();