|
| 1 | +use anyhow::Result; |
1 | 2 | use checksum::digest::compute_digest; |
2 | 3 | use clap::Parser; |
3 | | -use std::path::PathBuf; |
| 4 | +use std::io::{self, IsTerminal, Read}; |
| 5 | +use std::path::{Path, PathBuf}; |
4 | 6 |
|
5 | | -#[derive(Parser)] |
| 7 | +#[derive(Debug, Parser)] |
6 | 8 | #[command(version, about, long_about = None)] |
7 | 9 | struct Cli { |
| 10 | + /// Path to file to compute digest for |
8 | 11 | #[arg(short, long, value_name = "FILE")] |
9 | 12 | path: Option<PathBuf>, |
| 13 | + /// Input string to compute digest for |
| 14 | + #[arg(short, long, value_name = "INPUT")] |
| 15 | + input: Option<String>, |
| 16 | + /// File type of supplied input. Supported file extensions: json, yaml, yml |
| 17 | + #[arg(short, long, value_name = "FILETYPE")] |
| 18 | + r#type: Option<String>, |
10 | 19 | } |
11 | 20 |
|
12 | | -fn main() { |
13 | | - let cli = Cli::parse(); |
| 21 | +fn handle_path(path: &Path) -> Result<(), anyhow::Error> { |
| 22 | + if let Some(path_ext) = path.extension() { |
| 23 | + let file_contents = std::fs::read_to_string(path)?; |
| 24 | + let digest = compute_digest(&file_contents, path_ext.to_str())?; |
| 25 | + println!("{:?}", digest); |
| 26 | + Ok(()) |
| 27 | + } else { |
| 28 | + Err(anyhow::anyhow!( |
| 29 | + "Unable to extract file extension for {:?}", |
| 30 | + path |
| 31 | + ))? |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +fn handle_input(input: &str, filetype: Option<&str>) -> Result<(), anyhow::Error> { |
| 36 | + let digest = compute_digest(input, filetype)?; |
| 37 | + println!("{:?}", digest); |
| 38 | + Ok(()) |
| 39 | +} |
| 40 | + |
| 41 | +fn handle_terminal(filetype: Option<&str>) -> Result<(), anyhow::Error> { |
| 42 | + let mut buffer = String::new(); |
| 43 | + io::stdin().read_to_string(&mut buffer)?; |
| 44 | + let digest = compute_digest(buffer.trim(), filetype)?; |
| 45 | + println!("{:?}", digest); |
| 46 | + Ok(()) |
| 47 | +} |
14 | 48 |
|
| 49 | +fn main() -> Result<()> { |
| 50 | + let cli = Cli::parse(); |
15 | 51 | if let Some(path) = cli.path.as_deref() { |
16 | | - let path_ext = path.extension().unwrap(); |
17 | | - let file_contents = std::fs::read_to_string(path).unwrap(); |
18 | | - let digest = compute_digest(&file_contents, path_ext.to_str()); |
19 | | - println!("{:?}", digest); |
| 52 | + handle_path(path) |
| 53 | + } else if let Some(input) = cli.input.as_deref() { |
| 54 | + handle_input(input, cli.r#type.as_deref()) |
| 55 | + } else if !io::stdin().is_terminal() { |
| 56 | + handle_terminal(cli.r#type.as_deref()) |
| 57 | + } else { |
| 58 | + Err(anyhow::anyhow!( |
| 59 | + "Unable to output digest with supplied command line args" |
| 60 | + ))? |
20 | 61 | } |
21 | 62 | } |
0 commit comments