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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use std::path::PathBuf;

use clap::{IntoApp, Parser};
use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;
use tracing::metadata::LevelFilter;
use tracing_log::{LogTracer, log_tracer::SetLoggerError};
use tracing_subscriber::EnvFilter;

use crate::config::{self, ConfigFileFormat};

// Exit codes as defined in sysexits.h.
pub const INTERNAL_ERROR_EXIT_CODE: i32 = 70;
pub const CONFIGURATION_ERROR_EXIT_CODE: i32 = 78;

#[derive(Error, Debug)]
pub enum CliError {
    #[error(transparent)]
    ArgParse(#[from] clap::Error),
    #[error(transparent)]
    Config(#[from] config::ConfigError),
    #[error(transparent)]
    SetLogger(#[from] SetLoggerError),
    #[error(transparent)]
    InitLogger(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
}

pub trait AppOpts: Parser {
    fn try_init() -> Result<Self, CliError> {
        let result = Self::try_parse().map_err(CliError::ArgParse);

        match &result {
            Ok(result) => {
                //LogTracer::init()?;

                try_init_pretty_logger(
                    result.get_log_environment_variable_name(),
                    result.get_log_level_filter(),
                )?;
            }
            Err(_) => {
                // Initialize the logger with defaults.
                //LogTracer::init()?;
    
                tracing_subscriber::fmt::init();
            }
        }

        result
    }

    fn init() -> Self {
        match Self::try_init() {
            Ok(args) => args,
            Err(CliError::ArgParse(err)) => err.exit(),
            Err(CliError::Config(err)) => {
                tracing::error!("{}", err);

                safe_exit(CONFIGURATION_ERROR_EXIT_CODE);
            },
            Err(CliError::SetLogger(err)) => {
                eprintln!("{}", err);

                safe_exit(INTERNAL_ERROR_EXIT_CODE);
            },
            Err(CliError::InitLogger(err)) => {
                eprintln!("{}", err);

                safe_exit(INTERNAL_ERROR_EXIT_CODE);
            },
        }
    }

    fn get_log_level_filter(&self) -> Option<LevelFilter> {
        None
    }

    fn get_log_environment_variable_name(&self) -> Option<&str> {
        None
    }
}

pub trait ConfigurableAppOpts<C: DeserializeOwned + Default + Serialize>: AppOpts {
    fn try_init_with_config() -> Result<(Self, C), CliError> {
        let opts = Self::try_init()?;

        let app = <Self as IntoApp>::command();

        let conf = config::from_defaults(
            app.get_name(),
            &opts.get_additional_config_paths(),
            opts.get_config_file_format(),
        )
        .map_err(CliError::Config)?;

        Ok((opts, conf))
    }

    fn init_with_config() -> (Self, C) {
        match Self::try_init_with_config() {
            Ok(args_and_config) => args_and_config,
            Err(CliError::ArgParse(err)) => err.exit(),
            Err(CliError::Config(err)) => {
                tracing::error!("{}", err);

                safe_exit(CONFIGURATION_ERROR_EXIT_CODE);
            },
            Err(CliError::SetLogger(err)) => {
                eprintln!("{}", err);

                safe_exit(INTERNAL_ERROR_EXIT_CODE);
            },
            Err(CliError::InitLogger(err)) => {
                eprintln!("{}", err);

                safe_exit(INTERNAL_ERROR_EXIT_CODE);
            },
        }
    }

    fn get_config_file_format(&self) -> ConfigFileFormat {
        ConfigFileFormat::Toml
    }

    fn get_additional_config_paths(&self) -> Vec<(PathBuf, Option<ConfigFileFormat>)>;
}

fn try_init_pretty_logger(
    environment_variable_name: Option<&str>,
    level_filter_override: Option<LevelFilter>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
    let mut builder = tracing_subscriber::fmt();

    if let Some(level_filter_override) = level_filter_override {
        builder = builder.with_max_level(level_filter_override);
    }

    let filter = if let Some(environment_variable_name) = environment_variable_name {
        EnvFilter::from_env(environment_variable_name)
    } else {
        EnvFilter::from_default_env()
    };

    builder.with_env_filter(filter).try_init()
}

/// Converts a integer verbosity value into a `LevelFilter`.
///
/// Examples:
///
/// ```
/// use collective::cli::get_log_level_filter_from_verbosity;
///
/// assert_eq!(
///     get_log_level_filter_from_verbosity(1),
///     Some(log::LevelFilter::Info)
/// );
///
/// assert_eq!(get_log_level_filter_from_verbosity(15), None);
/// ```
pub fn get_log_level_filter_from_verbosity(verbosity: u8) -> Option<LevelFilter> {
    match verbosity {
        3 => Some(LevelFilter::TRACE),
        2 => Some(LevelFilter::DEBUG),
        1 => Some(LevelFilter::INFO),
        _ => None,
    }
}

/// Flushes stdout/stderr and terminates the current process.
///
/// This is used internally in the library to handle non-critical CLI errors.
pub fn safe_exit(code: i32) -> ! {
    use std::io::Write;

    let _ = std::io::stdout().lock().flush();
    let _ = std::io::stderr().lock().flush();

    std::process::exit(code)
}