use super::*;
pub fn path_filter(root: &Path, rel_path: &str) -> Option<String> {
let out = Git::new()
.at(root)
.args(["check-attr", "filter", "--", rel_path])
.into_command()
.output()
.ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let value = text.trim_end().rsplit(": ").next()?;
match value {
"" => None,
"unspecified" | "unset" | "set" if !filter_driver_configured(root, value) => None,
name => Some(name.to_string()),
}
}
pub(super) fn filter_driver_configured(root: &Path, name: &str) -> bool {
Git::new()
.at(root)
.args(["config", "--get-regexp"])
.arg(format!(
r"^filter\.{}\.(clean|smudge|process)$",
regex::escape(name)
))
.into_command()
.output()
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty())
}
pub fn read_file_at_head(root: &Path, rel_path: &str) -> Result<String, String> {
let bytes = read_bytes_at_head(root, rel_path)?;
String::from_utf8(bytes).map_err(|_| format!("{rel_path} at HEAD is not UTF-8"))
}
pub fn read_bytes_at_head(root: &Path, rel_path: &str) -> Result<Vec<u8>, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let spec = format!("HEAD:{rel_path}");
let output = show_blob(Path::new(path_str), &spec, rel_path)
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if stderr.is_empty() {
format!(
"git show {spec} failed with code {:?}",
output.status.code()
)
} else {
stderr
});
}
Ok(output.stdout)
}
pub(super) fn show_blob(root: &Path, spec: &str, rel_path: &str) -> Command {
let git = Git::new().at(root);
let git = match path_filter(root, rel_path) {
Some(_) => git.args(["cat-file", "--filters"]),
None => git.arg("show"),
};
git.arg(spec).into_command()
}
pub fn read_file_at_rev(root: &Path, rev: &str, rel_path: &str) -> Result<String, String> {
let spec = format!("{rev}:./{rel_path}");
let output = show_blob(root, &spec, rel_path)
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
}
String::from_utf8(output.stdout).map_err(|_| format!("{rel_path} at {rev} is not UTF-8"))
}
pub fn read_file_at_stage(root: &Path, rel_path: &str, stage: u8) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let spec = format!(":{stage}:{rel_path}");
let output = show_blob(Path::new(path_str), &spec, rel_path)
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if stderr.is_empty() {
format!(
"git show {spec} failed with code {:?}",
output.status.code()
)
} else {
stderr
});
}
String::from_utf8(output.stdout)
.map_err(|_| format!("{rel_path} at stage {stage} is not UTF-8"))
}
pub fn remerge_diff3(root: &Path, rel_path: &str) -> Result<String, String> {
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let sides = [
("ours", read_file_at_stage(root, rel_path, 2)?),
("base", read_file_at_stage(root, rel_path, 1)?),
("theirs", read_file_at_stage(root, rel_path, 3)?),
];
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos());
let dir = std::env::temp_dir().join(format!(
"croft-remerge-{}-{}-{nanos}",
std::process::id(),
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder.create(&dir).map_err(|e| e.to_string())?;
let merged = (|| {
for (name, text) in &sides {
std::fs::write(dir.join(name), text).map_err(|e| e.to_string())?;
}
let output = Git::new()
.at(root)
.args(["merge-file", "-p", "-q", "--diff3"])
.args(sides.iter().map(|(name, _)| dir.join(name)))
.into_command()
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
match output.status.code() {
Some(0..=127) => String::from_utf8(output.stdout)
.map_err(|_| format!("{rel_path} merged is not UTF-8")),
_ => Err(String::from_utf8_lossy(&output.stderr).trim().to_string()),
}
})();
let _ = std::fs::remove_dir_all(&dir);
merged
}