Summer/src/main.rs

46 lines
1.2 KiB
Rust

use std::{fs, io};
use std::collections::HashMap;
use std::fs::{DirEntry, File};
use std::io::Read;
use std::path::Path;
use path_slash::PathExt;
use sha3::Digest;
fn main() {
let r = visit_dirs(Path::new("."), &create_hash).unwrap();
let f = File::create("sums.json").unwrap();
serde_json::to_writer_pretty(f, &r).unwrap();
}
fn create_hash(dir: &DirEntry) -> String {
let mut sha = sha3::Sha3_256::default();
let mut f = File::open(dir.path()).unwrap();
let mut b = Vec::new();
f.read_to_end(&mut b).unwrap();
sha.input(&b);
format!("{:x}", sha.result())
}
fn visit_dirs(dir: &Path, cb: &dyn Fn(&DirEntry) -> String) -> io::Result<HashMap<String, String>> {
let mut hm = HashMap::new();
if dir.is_dir() {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let v = visit_dirs(&path, cb)?;
for (k, v) in v {
hm.insert(k, v);
}
} else {
let k = entry.path().to_slash_lossy();
let v = cb(&entry);
hm.insert(k, v);
}
}
}
Ok(hm)
}