Skip to content

Commit 7f3f4e5

Browse files
authored
Merge pull request #2012 from input-output-hk/djo/refactor_client_cli_command_params
Refactor client cli command parameters
2 parents 3908e8a + 13e97a9 commit 7f3f4e5

File tree

21 files changed

+326
-198
lines changed

21 files changed

+326
-198
lines changed

Cargo.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mithril-client-cli/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "mithril-client-cli"
3-
version = "0.9.15"
3+
version = "0.9.16"
44
description = "A Mithril Client"
55
authors = { workspace = true }
66
edition = { workspace = true }
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
use config::builder::DefaultState;
2+
use config::ConfigBuilder;
3+
use slog::Logger;
4+
use std::collections::HashMap;
5+
6+
use mithril_client::MithrilResult;
7+
8+
use crate::configuration::ConfigParameters;
9+
10+
/// Context for the command execution
11+
pub struct CommandContext {
12+
config_builder: ConfigBuilder<DefaultState>,
13+
unstable_enabled: bool,
14+
logger: Logger,
15+
}
16+
17+
impl CommandContext {
18+
/// Create a new command context
19+
pub fn new(
20+
config_builder: ConfigBuilder<DefaultState>,
21+
unstable_enabled: bool,
22+
logger: Logger,
23+
) -> Self {
24+
Self {
25+
config_builder,
26+
unstable_enabled,
27+
logger,
28+
}
29+
}
30+
31+
/// Check if unstable commands are enabled
32+
pub fn is_unstable_enabled(&self) -> bool {
33+
self.unstable_enabled
34+
}
35+
36+
/// Get the configured parameters
37+
pub fn config_parameters(&self) -> MithrilResult<ConfigParameters> {
38+
let config = self.config_builder.clone().build()?;
39+
let config_hash_map = config.try_deserialize::<HashMap<String, String>>()?;
40+
Ok(ConfigParameters::new(config_hash_map))
41+
}
42+
43+
/// Get the shared logger
44+
pub fn logger(&self) -> &Logger {
45+
&self.logger
46+
}
47+
}

mithril-client-cli/src/commands/cardano_db/download.rs

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use anyhow::{anyhow, Context};
22
use chrono::Utc;
33
use clap::Parser;
4-
use config::{builder::DefaultState, ConfigBuilder, Map, Source, Value, ValueKind};
54
use slog_scope::{debug, warn};
65
use std::{
76
collections::HashMap,
@@ -11,12 +10,13 @@ use std::{
1110
};
1211

1312
use crate::{
14-
commands::client_builder,
15-
configuration::ConfigParameters,
13+
commands::{client_builder, SharedArgs},
14+
configuration::{ConfigError, ConfigSource},
1615
utils::{
1716
CardanoDbDownloadChecker, CardanoDbUtils, ExpanderUtils, IndicatifFeedbackReceiver,
1817
ProgressOutputType, ProgressPrinter,
1918
},
19+
CommandContext,
2020
};
2121
use mithril_client::{
2222
common::ProtocolMessage, Client, MessageBuilder, MithrilCertificate, MithrilResult, Snapshot,
@@ -25,9 +25,8 @@ use mithril_client::{
2525
/// Clap command to download a Cardano db and verify its associated certificate.
2626
#[derive(Parser, Debug, Clone)]
2727
pub struct CardanoDbDownloadCommand {
28-
/// Enable JSON output.
29-
#[clap(long)]
30-
json: bool,
28+
#[clap(flatten)]
29+
shared_args: SharedArgs,
3130

3231
/// Digest of the cardano db to download. Use the `list` command to get that information.
3332
///
@@ -48,17 +47,16 @@ pub struct CardanoDbDownloadCommand {
4847
impl CardanoDbDownloadCommand {
4948
/// Is JSON output enabled
5049
pub fn is_json_output_enabled(&self) -> bool {
51-
self.json
50+
self.shared_args.json
5251
}
5352

5453
/// Command execution
55-
pub async fn execute(&self, config_builder: ConfigBuilder<DefaultState>) -> MithrilResult<()> {
56-
let config = config_builder.add_source(self.clone()).build()?;
57-
let params = ConfigParameters::new(config.try_deserialize::<HashMap<String, String>>()?);
54+
pub async fn execute(&self, context: CommandContext) -> MithrilResult<()> {
55+
let params = context.config_parameters()?.add_source(self)?;
5856
let download_dir: &String = &params.require("download_dir")?;
5957
let db_dir = Path::new(download_dir).join("db");
6058

61-
let progress_output_type = if self.json {
59+
let progress_output_type = if self.is_json_output_enabled() {
6260
ProgressOutputType::JsonReporter
6361
} else {
6462
ProgressOutputType::Tty
@@ -128,7 +126,11 @@ impl CardanoDbDownloadCommand {
128126
)
129127
.await?;
130128

131-
Self::log_download_information(&db_dir, &cardano_db_message, self.json)?;
129+
Self::log_download_information(
130+
&db_dir,
131+
&cardano_db_message,
132+
self.is_json_output_enabled(),
133+
)?;
132134

133135
Ok(())
134136
}
@@ -301,34 +303,29 @@ impl CardanoDbDownloadCommand {
301303
}
302304
}
303305

304-
impl Source for CardanoDbDownloadCommand {
305-
fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
306-
Box::new(self.clone())
307-
}
308-
309-
fn collect(&self) -> Result<Map<String, Value>, config::ConfigError> {
310-
let mut map = Map::new();
311-
let namespace = "clap arguments".to_string();
306+
impl ConfigSource for CardanoDbDownloadCommand {
307+
fn collect(&self) -> Result<HashMap<String, String>, ConfigError> {
308+
let mut map = HashMap::new();
312309

313310
if let Some(download_dir) = self.download_dir.clone() {
314311
map.insert(
315312
"download_dir".to_string(),
316-
Value::new(
317-
Some(&namespace),
318-
ValueKind::from(download_dir.to_str().ok_or_else(|| {
319-
config::ConfigError::Message(format!(
313+
download_dir
314+
.to_str()
315+
.ok_or_else(|| {
316+
ConfigError::Conversion(format!(
320317
"Could not read download directory: '{}'.",
321318
download_dir.display()
322319
))
323-
})?),
324-
),
320+
})?
321+
.to_string(),
325322
);
326323
}
327324

328325
if let Some(genesis_verification_key) = self.genesis_verification_key.clone() {
329326
map.insert(
330327
"genesis_verification_key".to_string(),
331-
Value::new(Some(&namespace), ValueKind::from(genesis_verification_key)),
328+
genesis_verification_key,
332329
);
333330
}
334331

mithril-client-cli/src/commands/cardano_db/list.rs

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,32 @@
11
use clap::Parser;
22
use cli_table::{format::Justify, print_stdout, Cell, Table};
3-
use config::{builder::DefaultState, ConfigBuilder};
4-
use std::collections::HashMap;
53

6-
use crate::{commands::client_builder_with_fallback_genesis_key, configuration::ConfigParameters};
4+
use crate::{
5+
commands::{client_builder_with_fallback_genesis_key, SharedArgs},
6+
CommandContext,
7+
};
78
use mithril_client::MithrilResult;
89

910
/// Clap command to list existing cardano dbs
1011
#[derive(Parser, Debug, Clone)]
1112
pub struct CardanoDbListCommand {
12-
/// Enable JSON output.
13-
#[clap(long)]
14-
json: bool,
13+
#[clap(flatten)]
14+
shared_args: SharedArgs,
1515
}
1616

1717
impl CardanoDbListCommand {
1818
/// Is JSON output enabled
1919
pub fn is_json_output_enabled(&self) -> bool {
20-
self.json
20+
self.shared_args.json
2121
}
2222

2323
/// Main command execution
24-
pub async fn execute(&self, config_builder: ConfigBuilder<DefaultState>) -> MithrilResult<()> {
25-
let config = config_builder.build()?;
26-
let params = ConfigParameters::new(config.try_deserialize::<HashMap<String, String>>()?);
24+
pub async fn execute(&self, context: CommandContext) -> MithrilResult<()> {
25+
let params = context.config_parameters()?;
2726
let client = client_builder_with_fallback_genesis_key(&params)?.build()?;
2827
let items = client.snapshot().list().await?;
2928

30-
if self.json {
29+
if self.is_json_output_enabled() {
3130
println!("{}", serde_json::to_string(&items)?);
3231
} else {
3332
let items = items

mithril-client-cli/src/commands/cardano_db/mod.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ pub use download::*;
77
pub use list::*;
88
pub use show::*;
99

10+
use crate::CommandContext;
1011
use clap::Subcommand;
11-
use config::{builder::DefaultState, ConfigBuilder};
1212
use mithril_client::MithrilResult;
1313

1414
/// Cardano db management (alias: cdb)
@@ -37,7 +37,7 @@ pub enum CardanoDbSnapshotCommands {
3737

3838
impl CardanoDbCommands {
3939
/// Execute cardano db command
40-
pub async fn execute(&self, config_builder: ConfigBuilder<DefaultState>) -> MithrilResult<()> {
40+
pub async fn execute(&self, config_builder: CommandContext) -> MithrilResult<()> {
4141
match self {
4242
Self::Download(cmd) => cmd.execute(config_builder).await,
4343
Self::Snapshot(cmd) => cmd.execute(config_builder).await,
@@ -47,7 +47,7 @@ impl CardanoDbCommands {
4747

4848
impl CardanoDbSnapshotCommands {
4949
/// Execute Cardano db snapshot command
50-
pub async fn execute(&self, config_builder: ConfigBuilder<DefaultState>) -> MithrilResult<()> {
50+
pub async fn execute(&self, config_builder: CommandContext) -> MithrilResult<()> {
5151
match self {
5252
Self::List(cmd) => cmd.execute(config_builder).await,
5353
Self::Show(cmd) => cmd.execute(config_builder).await,

mithril-client-cli/src/commands/cardano_db/show.rs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,19 @@
11
use anyhow::{anyhow, Context};
22
use clap::Parser;
33
use cli_table::{print_stdout, Cell, Table};
4-
use config::{builder::DefaultState, ConfigBuilder};
5-
use std::collections::HashMap;
64

75
use crate::{
8-
commands::client_builder_with_fallback_genesis_key, configuration::ConfigParameters,
6+
commands::{client_builder_with_fallback_genesis_key, SharedArgs},
97
utils::ExpanderUtils,
8+
CommandContext,
109
};
1110
use mithril_client::MithrilResult;
1211

1312
/// Clap command to show a given cardano db
1413
#[derive(Parser, Debug, Clone)]
1514
pub struct CardanoDbShowCommand {
16-
/// Enable JSON output.
17-
#[clap(long)]
18-
json: bool,
15+
#[clap(flatten)]
16+
shared_args: SharedArgs,
1917

2018
/// Cardano DB digest.
2119
///
@@ -26,13 +24,12 @@ pub struct CardanoDbShowCommand {
2624
impl CardanoDbShowCommand {
2725
/// Is JSON output enabled
2826
pub fn is_json_output_enabled(&self) -> bool {
29-
self.json
27+
self.shared_args.json
3028
}
3129

3230
/// Cardano DB Show command
33-
pub async fn execute(&self, config_builder: ConfigBuilder<DefaultState>) -> MithrilResult<()> {
34-
let config = config_builder.build()?;
35-
let params = ConfigParameters::new(config.try_deserialize::<HashMap<String, String>>()?);
31+
pub async fn execute(&self, context: CommandContext) -> MithrilResult<()> {
32+
let params = context.config_parameters()?;
3633
let client = client_builder_with_fallback_genesis_key(&params)?.build()?;
3734

3835
let get_list_of_artifact_ids = || async {
@@ -55,7 +52,7 @@ impl CardanoDbShowCommand {
5552
.await?
5653
.ok_or_else(|| anyhow!("Cardano DB not found for digest: '{}'", &self.digest))?;
5754

58-
if self.json {
55+
if self.is_json_output_enabled() {
5956
println!("{}", serde_json::to_string(&cardano_db_message)?);
6057
} else {
6158
let cardano_db_table = vec![

0 commit comments

Comments
 (0)