Skip to content

Commit

Permalink
Merge pull request #2012 from input-output-hk/djo/refactor_client_cli…
Browse files Browse the repository at this point in the history
…_command_params

Refactor client cli command parameters
  • Loading branch information
Alenar authored Oct 17, 2024
2 parents 3908e8a + 13e97a9 commit 7f3f4e5
Show file tree
Hide file tree
Showing 21 changed files with 326 additions and 198 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion mithril-client-cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mithril-client-cli"
version = "0.9.15"
version = "0.9.16"
description = "A Mithril Client"
authors = { workspace = true }
edition = { workspace = true }
Expand Down
47 changes: 47 additions & 0 deletions mithril-client-cli/src/command_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use config::builder::DefaultState;
use config::ConfigBuilder;
use slog::Logger;
use std::collections::HashMap;

use mithril_client::MithrilResult;

use crate::configuration::ConfigParameters;

/// Context for the command execution
pub struct CommandContext {
config_builder: ConfigBuilder<DefaultState>,
unstable_enabled: bool,
logger: Logger,
}

impl CommandContext {
/// Create a new command context
pub fn new(
config_builder: ConfigBuilder<DefaultState>,
unstable_enabled: bool,
logger: Logger,
) -> Self {
Self {
config_builder,
unstable_enabled,
logger,
}
}

/// Check if unstable commands are enabled
pub fn is_unstable_enabled(&self) -> bool {
self.unstable_enabled
}

/// Get the configured parameters
pub fn config_parameters(&self) -> MithrilResult<ConfigParameters> {
let config = self.config_builder.clone().build()?;
let config_hash_map = config.try_deserialize::<HashMap<String, String>>()?;
Ok(ConfigParameters::new(config_hash_map))
}

/// Get the shared logger
pub fn logger(&self) -> &Logger {
&self.logger
}
}
51 changes: 24 additions & 27 deletions mithril-client-cli/src/commands/cardano_db/download.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use anyhow::{anyhow, Context};
use chrono::Utc;
use clap::Parser;
use config::{builder::DefaultState, ConfigBuilder, Map, Source, Value, ValueKind};
use slog_scope::{debug, warn};
use std::{
collections::HashMap,
Expand All @@ -11,12 +10,13 @@ use std::{
};

use crate::{
commands::client_builder,
configuration::ConfigParameters,
commands::{client_builder, SharedArgs},
configuration::{ConfigError, ConfigSource},
utils::{
CardanoDbDownloadChecker, CardanoDbUtils, ExpanderUtils, IndicatifFeedbackReceiver,
ProgressOutputType, ProgressPrinter,
},
CommandContext,
};
use mithril_client::{
common::ProtocolMessage, Client, MessageBuilder, MithrilCertificate, MithrilResult, Snapshot,
Expand All @@ -25,9 +25,8 @@ use mithril_client::{
/// Clap command to download a Cardano db and verify its associated certificate.
#[derive(Parser, Debug, Clone)]
pub struct CardanoDbDownloadCommand {
/// Enable JSON output.
#[clap(long)]
json: bool,
#[clap(flatten)]
shared_args: SharedArgs,

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

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

let progress_output_type = if self.json {
let progress_output_type = if self.is_json_output_enabled() {
ProgressOutputType::JsonReporter
} else {
ProgressOutputType::Tty
Expand Down Expand Up @@ -128,7 +126,11 @@ impl CardanoDbDownloadCommand {
)
.await?;

Self::log_download_information(&db_dir, &cardano_db_message, self.json)?;
Self::log_download_information(
&db_dir,
&cardano_db_message,
self.is_json_output_enabled(),
)?;

Ok(())
}
Expand Down Expand Up @@ -301,34 +303,29 @@ impl CardanoDbDownloadCommand {
}
}

impl Source for CardanoDbDownloadCommand {
fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
Box::new(self.clone())
}

fn collect(&self) -> Result<Map<String, Value>, config::ConfigError> {
let mut map = Map::new();
let namespace = "clap arguments".to_string();
impl ConfigSource for CardanoDbDownloadCommand {
fn collect(&self) -> Result<HashMap<String, String>, ConfigError> {
let mut map = HashMap::new();

if let Some(download_dir) = self.download_dir.clone() {
map.insert(
"download_dir".to_string(),
Value::new(
Some(&namespace),
ValueKind::from(download_dir.to_str().ok_or_else(|| {
config::ConfigError::Message(format!(
download_dir
.to_str()
.ok_or_else(|| {
ConfigError::Conversion(format!(
"Could not read download directory: '{}'.",
download_dir.display()
))
})?),
),
})?
.to_string(),
);
}

if let Some(genesis_verification_key) = self.genesis_verification_key.clone() {
map.insert(
"genesis_verification_key".to_string(),
Value::new(Some(&namespace), ValueKind::from(genesis_verification_key)),
genesis_verification_key,
);
}

Expand Down
21 changes: 10 additions & 11 deletions mithril-client-cli/src/commands/cardano_db/list.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,32 @@
use clap::Parser;
use cli_table::{format::Justify, print_stdout, Cell, Table};
use config::{builder::DefaultState, ConfigBuilder};
use std::collections::HashMap;

use crate::{commands::client_builder_with_fallback_genesis_key, configuration::ConfigParameters};
use crate::{
commands::{client_builder_with_fallback_genesis_key, SharedArgs},
CommandContext,
};
use mithril_client::MithrilResult;

/// Clap command to list existing cardano dbs
#[derive(Parser, Debug, Clone)]
pub struct CardanoDbListCommand {
/// Enable JSON output.
#[clap(long)]
json: bool,
#[clap(flatten)]
shared_args: SharedArgs,
}

impl CardanoDbListCommand {
/// Is JSON output enabled
pub fn is_json_output_enabled(&self) -> bool {
self.json
self.shared_args.json
}

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

if self.json {
if self.is_json_output_enabled() {
println!("{}", serde_json::to_string(&items)?);
} else {
let items = items
Expand Down
6 changes: 3 additions & 3 deletions mithril-client-cli/src/commands/cardano_db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ pub use download::*;
pub use list::*;
pub use show::*;

use crate::CommandContext;
use clap::Subcommand;
use config::{builder::DefaultState, ConfigBuilder};
use mithril_client::MithrilResult;

/// Cardano db management (alias: cdb)
Expand Down Expand Up @@ -37,7 +37,7 @@ pub enum CardanoDbSnapshotCommands {

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

impl CardanoDbSnapshotCommands {
/// Execute Cardano db snapshot command
pub async fn execute(&self, config_builder: ConfigBuilder<DefaultState>) -> MithrilResult<()> {
pub async fn execute(&self, config_builder: CommandContext) -> MithrilResult<()> {
match self {
Self::List(cmd) => cmd.execute(config_builder).await,
Self::Show(cmd) => cmd.execute(config_builder).await,
Expand Down
19 changes: 8 additions & 11 deletions mithril-client-cli/src/commands/cardano_db/show.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
use anyhow::{anyhow, Context};
use clap::Parser;
use cli_table::{print_stdout, Cell, Table};
use config::{builder::DefaultState, ConfigBuilder};
use std::collections::HashMap;

use crate::{
commands::client_builder_with_fallback_genesis_key, configuration::ConfigParameters,
commands::{client_builder_with_fallback_genesis_key, SharedArgs},
utils::ExpanderUtils,
CommandContext,
};
use mithril_client::MithrilResult;

/// Clap command to show a given cardano db
#[derive(Parser, Debug, Clone)]
pub struct CardanoDbShowCommand {
/// Enable JSON output.
#[clap(long)]
json: bool,
#[clap(flatten)]
shared_args: SharedArgs,

/// Cardano DB digest.
///
Expand All @@ -26,13 +24,12 @@ pub struct CardanoDbShowCommand {
impl CardanoDbShowCommand {
/// Is JSON output enabled
pub fn is_json_output_enabled(&self) -> bool {
self.json
self.shared_args.json
}

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

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

if self.json {
if self.is_json_output_enabled() {
println!("{}", serde_json::to_string(&cardano_db_message)?);
} else {
let cardano_db_table = vec![
Expand Down
Loading

0 comments on commit 7f3f4e5

Please sign in to comment.