use std::{path::Path, process::ExitCode};
use basis::Snapshot;
use crate::{cli::FingerprintArgs, exit::EXIT_OK};
pub(crate) fn execute_fingerprint(args: FingerprintArgs) -> Result<ExitCode, String> {
let workspace = match args.workspace {
Some(path) => path,
None => {
std::env::current_dir().map_err(|error| format!("no working directory: {error}"))?
}
};
println!("{}", fingerprint_line(&workspace)?);
Ok(ExitCode::from(EXIT_OK))
}
fn fingerprint_line(workspace: &Path) -> Result<String, String> {
match basis::fingerprint::snapshot(workspace) {
Snapshot::Known(fingerprint) => Ok(fingerprint.hex()),
Snapshot::Unknown { reason } => Err(reason),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_workspace_that_cannot_be_fingerprinted_prints_nothing() {
let reason = fingerprint_line(Path::new("/definitely/not/a/real/path"))
.expect_err("an absent workspace has no fingerprint");
assert!(
reason.contains("/definitely/not/a/real/path"),
"the reason must name the workspace: {reason}"
);
}
#[test]
fn a_fingerprintable_workspace_prints_one_stable_hash() {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join("a.txt"), "one").expect("write");
let printed = fingerprint_line(dir.path()).expect("a workspace with a file in it");
assert_eq!(printed.len(), 16);
assert_eq!(
printed,
fingerprint_line(dir.path()).expect("still fingerprints"),
"a workspace nobody touched must print the same line twice"
);
}
}