mithril_client_cli/
command_context.rs

1use anyhow::anyhow;
2use config::builder::DefaultState;
3use config::ConfigBuilder;
4use slog::Logger;
5use std::collections::HashMap;
6
7use mithril_client::MithrilResult;
8
9use crate::configuration::ConfigParameters;
10
11/// Context for the command execution
12pub struct CommandContext {
13    config_builder: ConfigBuilder<DefaultState>,
14    unstable_enabled: bool,
15    logger: Logger,
16}
17
18impl CommandContext {
19    /// Create a new command context
20    pub fn new(
21        config_builder: ConfigBuilder<DefaultState>,
22        unstable_enabled: bool,
23        logger: Logger,
24    ) -> Self {
25        Self {
26            config_builder,
27            unstable_enabled,
28            logger,
29        }
30    }
31
32    /// Check if unstable commands are enabled
33    pub fn is_unstable_enabled(&self) -> bool {
34        self.unstable_enabled
35    }
36
37    /// Ensure that unstable commands are enabled
38    pub fn require_unstable(
39        &self,
40        sub_command: &str,
41        command_example: Option<&str>,
42    ) -> MithrilResult<()> {
43        if self.is_unstable_enabled() {
44            Ok(())
45        } else {
46            let example = command_example.map(|e| format!(" {e}")).unwrap_or_default();
47            Err(anyhow!(
48                "The \"{sub_command}\" subcommand is only accepted using the --unstable flag.\n\n\
49                ie: \"mithril-client --unstable {sub_command}{example}\""
50            ))
51        }
52    }
53
54    /// Get the configured parameters
55    pub fn config_parameters(&self) -> MithrilResult<ConfigParameters> {
56        let config = self.config_builder.clone().build()?;
57        let config_hash_map = config.try_deserialize::<HashMap<String, String>>()?;
58        Ok(ConfigParameters::new(config_hash_map))
59    }
60
61    /// Get the shared logger
62    pub fn logger(&self) -> &Logger {
63        &self.logger
64    }
65}
66
67#[cfg(test)]
68mod tests {
69    use slog::o;
70
71    use super::*;
72
73    #[test]
74    fn require_unstable_return_ok_if_unstable_enabled() {
75        let unstable_enabled = true;
76        let context = CommandContext::new(
77            ConfigBuilder::default(),
78            unstable_enabled,
79            Logger::root(slog::Discard, o!()),
80        );
81
82        let result = context.require_unstable("test", None);
83        assert!(result.is_ok(), "Expected Ok, got {result:?}");
84    }
85
86    #[test]
87    fn require_unstable_return_err_if_unstable_disabled() {
88        let unstable_enabled = false;
89        let context = CommandContext::new(
90            ConfigBuilder::default(),
91            unstable_enabled,
92            Logger::root(slog::Discard, o!()),
93        );
94
95        let result = context.require_unstable("test", None);
96        assert!(result.is_err(), "Expected Err, got {result:?}");
97    }
98}