use clap::Parser;
use std::collections::HashMap;
use serde_json::Value;
use crate::response::{Request, Params};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Parser)]
#[command(name = "jsonhash")]
#[command(version, about = "A commande-line tool to compute hash of file content and filepath. Supports SHA256 and MD5. Returns as Json", long_about = None)]
pub struct Cli {
#[arg(value_name = "FILEPATH")]
pub filepath: String,
#[arg(short = 'a', long = "alg", default_value = "sha256", value_name = "ALGORITHM")]
pub alg: String,
#[arg(long = "id")]
pub id: Option<String>,
}
impl Cli {
pub fn validate_algorithm(alg: &str) -> Result<(), String> {
match alg.to_lowercase().as_str() {
"sha256" | "md5" => Ok(()),
_ => Err("HASH-ALGORITHM-INVALID".to_string()),
}
}
pub fn build_request(&self) -> Request {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");
let timestamp_ns = now.as_nanos();
let mut params: Params = HashMap::new();
params.insert("filepath".to_string(), Value::String(self.filepath.clone()));
params.insert("alg".to_string(), Value::String(self.alg.clone()));
if let Some(id) = &self.id {
params.insert("id".to_string(), Value::String(id.clone()));
} else {
params.insert("id".to_string(), Value::Null);
}
Request {
method: "jsonhash".to_string(), params,
ts: timestamp_ns, version: env!("CARGO_PKG_VERSION").to_string(), }
}
}