jsonhash 0.2.0

A command-line tool to generate hash values for files. SHA256 and MD5. Output and Error messages in JSON format.
Documentation
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,
    
    /// Optional request ID
    #[arg(long = "id")]
    pub id: Option<String>,
}

impl Cli {
    
    // Validates the provided hash algorithm
    pub fn validate_algorithm(alg: &str) -> Result<(), String> {
        match alg.to_lowercase().as_str() {
            "sha256" | "md5" => Ok(()),
            _ => Err("HASH-ALGORITHM-INVALID".to_string()),
        }
    }

    /// Builds a Request object from CLI information
    pub fn build_request(&self) -> Request {
        // Get current timestamp in nanoseconds since epoch
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards");
        let timestamp_ns = now.as_nanos();
        
        // Build params from CLI arguments
        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(),  // Name of the executable
            params,
            ts: timestamp_ns,  // Timestamp in nanoseconds
            version: env!("CARGO_PKG_VERSION").to_string(),  // Crate version from Cargo.toml
        }
    }
}