use std::path::Path;
use anyhow::{Context, Result};
use duct::cmd;
pub fn local_diff(dir: &Path, args: &[String]) -> Result<String> {
let dir_str = dir.to_string_lossy();
let mut git_args = vec!["-C", dir_str.as_ref(), "diff", "--no-color"];
git_args.extend(args.iter().map(String::as_str));
cmd("git", git_args).read().with_context(|| {
let tail = if args.is_empty() {
String::new()
} else {
format!(" {}", args.join(" "))
};
format!("git diff{tail} failed")
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_trailing_newline_is_tolerated() {
let dir = Path::new(".");
let diff = local_diff(dir, &[]);
assert!(diff.is_ok());
}
#[test]
fn error_message_reproduces_the_git_command() {
let err = local_diff(
Path::new("."),
&["no-such-ref-abcdef".to_string(), "README.md".to_string()],
)
.unwrap_err();
assert!(format!("{err:#}").contains("git diff no-such-ref-abcdef README.md failed"));
}
#[test]
fn positionals_are_forwarded() {
let diff = local_diff(
Path::new("."),
&["HEAD".to_string(), "Cargo.toml".to_string()],
)
.unwrap();
assert!(diff.is_empty() || diff.contains("Cargo.toml"));
let err = local_diff(
Path::new("."),
&["HEAD".to_string(), "no-such-file-abcdef".to_string()],
)
.unwrap_err();
assert!(format!("{err:#}").contains("no-such-file-abcdef"));
}
}