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);
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() {
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");
let cli = Cli {
filepath: filepath.to_string(),
alg: "sha256".to_string(),
id: None,
};
let output_message = process_file(&cli);
assert!(output_message.response.is_some());
assert!(output_message.error.is_none());
let response = output_message.response.unwrap();
assert!(!response.filename.is_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());
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());
}
}
}