use std::path::Path;
use anyhow::{Context, Result};
use duct::cmd;
pub fn local_diff(dir: &Path, reference: Option<&str>) -> Result<String> {
let dir_str = dir.to_string_lossy();
let mut args = vec!["-C", dir_str.as_ref(), "diff", "--no-color"];
if let Some(reference) = reference {
args.push(reference);
}
cmd("git", args).read().with_context(|| match reference {
Some(reference) => format!("git diff {reference} failed"),
None => "git diff failed".to_string(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_trailing_newline_is_tolerated() {
let dir = Path::new(".");
let diff = local_diff(dir, None);
assert!(diff.is_ok());
}
#[test]
fn nonexistent_reference_is_an_error() {
let err = local_diff(Path::new("."), Some("no-such-ref-abcdef")).unwrap_err();
assert!(format!("{err:#}").contains("git diff no-such-ref-abcdef failed"));
}
}