You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.7 KiB
90 lines
2.7 KiB
use serde::Deserialize; |
|
|
|
use crate::commands::{ClapArgs, Configurable, Executable}; |
|
use crate::config::{AppConfig, System}; |
|
use crate::container::Container; |
|
|
|
use anyhow::Result; |
|
use async_trait::async_trait; |
|
use config::ConfigBuilder; |
|
use config::builder::DefaultState; |
|
|
|
#[derive(Debug, Deserialize, Clone)] |
|
pub struct Config { |
|
pub system: System, |
|
pub input: String, |
|
pub dict_name: String, |
|
} |
|
|
|
#[derive(ClapArgs, Debug, Clone)] |
|
pub struct EncodeCmd { |
|
#[arg(short, long, help = defaults::HELP_ENC_SYSTEM)] |
|
pub system: Option<String>, |
|
|
|
#[arg(short, long, help = defaults::HELP_ENC_DICT)] |
|
pub dict_name: Option<String>, |
|
|
|
#[arg(short, long, help = defaults::HELP_ENC_INPUT)] |
|
pub input: String, |
|
} |
|
|
|
impl Configurable for EncodeCmd { |
|
fn apply_defaults( |
|
&self, |
|
builder: ConfigBuilder<DefaultState>, |
|
) -> Result<ConfigBuilder<DefaultState>> { |
|
builder |
|
.set_default("encode.system", defaults::ENC_SYSTEM_NAME)? |
|
.set_default("encode.dict_name", defaults::ENC_DICT_NAME)? |
|
.set_default("encode.input", "") |
|
.map_err(Into::into) |
|
} |
|
|
|
fn apply_overrides( |
|
&self, |
|
builder: ConfigBuilder<DefaultState>, |
|
) -> Result<ConfigBuilder<DefaultState>> { |
|
let mut builder = builder; |
|
|
|
if let Some(system) = &self.system { |
|
builder = builder.set_override("encode.system", system.clone())?; |
|
} |
|
if let Some(dict_name) = &self.dict_name { |
|
builder = builder.set_override("encode.dict_name", dict_name.clone())?; |
|
} |
|
builder = builder.set_override("encode.input", self.input.clone())?; |
|
Ok(builder) |
|
} |
|
} |
|
|
|
#[async_trait] |
|
impl Executable for EncodeCmd { |
|
async fn execute(&self, config: &AppConfig, container: &Container) -> Result<()> { |
|
let config = config |
|
.encode |
|
.as_ref() |
|
.ok_or_else(|| anyhow::anyhow!("Encoder config not set"))?; |
|
|
|
let encoder = container.create_encoder(&config).await?; |
|
let result = encoder.encode(&config.input); |
|
|
|
match result { |
|
Ok(res) => { |
|
let json = serde_json::to_string_pretty(&res).expect("JSON serialization failed"); |
|
println!("{}", json); |
|
} |
|
Err(e) => eprintln!("Error encoding: {:?}", e), |
|
} |
|
|
|
Ok(()) |
|
} |
|
} |
|
|
|
mod defaults { |
|
use const_format::formatcp; |
|
pub const ENC_SYSTEM_NAME: &str = "major_pl"; |
|
pub const ENC_DICT_NAME: &str = "demo_pl"; |
|
pub const HELP_ENC_SYSTEM: &str = formatcp!("System to use [default: {}]", ENC_SYSTEM_NAME); |
|
pub const HELP_ENC_INPUT: &str = formatcp!("Number to encode"); |
|
pub const HELP_ENC_DICT: &str = formatcp!("Dictionary to use [default: {}]", ENC_DICT_NAME); |
|
}
|
|
|