Add -o option to shasum

This commit is contained in:
2022-11-27 23:43:46 -05:00
parent a1cf93e605
commit f6dbe94bac
4 changed files with 103 additions and 4 deletions

View File

@@ -1,10 +1,12 @@
use std::{
fs::File,
fs::{File, OpenOptions},
io::{BufRead, BufReader, Read},
path::Path,
};
use anyhow::{Context, Error, Result};
use argh::FromArgs;
use filetime::{set_file_mtime, FileTime};
use sha1::{Digest, Sha1};
#[derive(FromArgs, PartialEq, Eq, Debug)]
@@ -17,6 +19,9 @@ pub struct Args {
#[argh(positional)]
/// path to file
file: String,
#[argh(option, short = 'o')]
/// touch output file on successful check
output: Option<String>,
}
const DEFAULT_BUF_SIZE: usize = 8192;
@@ -31,7 +36,7 @@ pub fn run(args: Args) -> Result<()> {
}
}
fn check(_args: Args, file: File) -> Result<()> {
fn check(args: Args, file: File) -> Result<()> {
let reader = BufReader::new(file);
let mut mismatches = 0usize;
for line in reader.lines() {
@@ -63,6 +68,9 @@ fn check(_args: Args, file: File) -> Result<()> {
eprintln!("WARNING: {} computed checksum did NOT match", mismatches);
std::process::exit(1);
}
if let Some(out_path) = args.output {
touch(&out_path).with_context(|| format!("Failed to touch output file '{}'", out_path))?;
}
Ok(())
}
@@ -86,3 +94,14 @@ fn file_sha1(mut file: File) -> Result<sha1::digest::Output<Sha1>> {
hasher.update(&buf[0..read]);
})
}
fn touch<P: AsRef<Path>>(path: P) -> std::io::Result<()> {
if path.as_ref().exists() {
set_file_mtime(path, FileTime::now())
} else {
match OpenOptions::new().create(true).write(true).open(path) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
}