use super::*;
pub fn diff_staged(root: &Path) -> Result<String, String> {
diff_text(root, &["diff", "--staged"])
}
pub fn merge_base(root: &Path, branch: &str) -> Option<String> {
diff_text(root, &["merge-base", "HEAD", branch])
.ok()
.map(|out| out.trim().to_string())
.filter(|sha| !sha.is_empty())
}
pub fn diff_against_branch(root: &Path, branch: &str) -> Result<String, String> {
match merge_base(root, branch) {
Some(base) => diff_text(root, &["diff", &base]),
None => diff_text(root, &["diff", branch]),
}
}
pub fn diff_previous_commit(root: &Path) -> Result<String, String> {
diff_text(root, &["diff", "HEAD~1"])
}
pub(super) fn diff_text(root: &Path, args: &[&str]) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str]);
match args.split_first() {
Some((sub, rest)) if matches!(*sub, "diff" | "show") => {
cmd.arg(sub)
.args(["--no-color", "--no-ext-diff"])
.args(rest);
}
_ => {
cmd.args(args);
}
}
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git {args:?} failed with code {:?}", output.status.code())
} else {
msg
})
}
}
pub fn is_submodule(root: &Path, rel_path: &str) -> bool {
let gitlink = |args: &[&str]| {
run_git(root, args).is_ok_and(|out| out.lines().any(|l| l.starts_with("160000 ")))
};
gitlink(&["--literal-pathspecs", "ls-files", "--stage", "--", rel_path])
|| gitlink(&["--literal-pathspecs", "ls-tree", "HEAD", "--", rel_path])
}
pub fn submodule_diff(root: &Path, rel_path: &str) -> Result<String, String> {
let diff = |mode: &str| {
run_git(
root,
&[
"-c",
"color.ui=never",
"--literal-pathspecs",
"diff",
mode,
"HEAD",
"--",
rel_path,
],
)
.map_err(|e| e.to_string())
};
let log = diff("--submodule=log")?;
let content: String = diff("--submodule=diff")?
.lines()
.filter(|l| !l.starts_with("Submodule "))
.map(|l| format!("{l}\n"))
.collect();
Ok(if content.is_empty() {
log
} else {
format!("{log}\n{content}")
})
}