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 serde_json;
use jsonhash::{Cli, Outputer, JsonOutputer, process_file};

fn main() {
    let cli = Cli::parse();
    
    let output_message = process_file(&cli);
    
    let json_outputer = JsonOutputer;
    let json_string = serde_json::to_string_pretty(&output_message).unwrap_or_else(|_| {
        serde_json::to_string(&output_message).unwrap_or_default()
    });
    let output = json_outputer.output(&json_string);
    println!("{}", output);
    
    // Exit with error code if there was an error
    if output_message.error.is_some() {
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::NamedTempFile;
    use std::io::Write;
    use std::process::Command;

    #[test]
    fn test_jsonhash_output() {
        // Create a temporary file
        let mut file = NamedTempFile::new().expect("Failed to create temp file");
        writeln!(file, "test content").expect("Failed to write to temp file");
        
        let filepath = file.path().to_str().expect("Failed to convert path to string");
        
        // Create CLI struct directly
        let cli = Cli {
            filepath: filepath.to_string(),
            alg: "sha256".to_string(),
            id: None,
        };
        
        // Process the file
        let output_message = process_file(&cli);
        
        // Verify we got a successful response
        assert!(output_message.response.is_some());
        assert!(output_message.error.is_none());
        
        let response = output_message.response.unwrap();
        
        // Verify filename is not empty
        assert!(!response.filename.is_empty());
        
        // These fields should not be empty
        assert!(!response.absfilepath.is_empty());
        assert!(!response.hash.is_empty());
        assert!(!response.shortpath.is_empty());
        assert!(!response.pathid.is_empty());
        assert!(!response.shortpathid.is_empty());
        
        // Verify content hash matches command line sha256sum
        let sha256sum_output = Command::new("sha256sum")
            .arg(filepath)
            .output()
            .expect("Failed to execute sha256sum");
            
        if sha256sum_output.status.success() {
            let sha256sum_stdout = String::from_utf8_lossy(&sha256sum_output.stdout);
            let expected_hash = sha256sum_stdout.split_whitespace().next().expect("No hash in sha256sum output");
            assert_eq!(response.hash, expected_hash.to_lowercase());
        }
    }
}