use super::*;
#[derive(Clone, Copy)]
pub(super) enum HunkSide {
Old,
New,
}
pub(super) fn retarget_hunk_starts(patch: &str, side: HunkSide) -> String {
let fix = |line: &str| -> Option<String> {
let rest = line.strip_prefix("@@ -")?;
let (old, rest) = rest.split_once(" +")?;
let (new, tail) = rest.split_once(" @@")?;
let start = |range: &str| range.split(',').next().map(str::to_string);
let count = |range: &str| range.split_once(',').map(|(_, c)| format!(",{c}"));
let pick = match side {
HunkSide::Old => start(old)?,
HunkSide::New => start(new)?,
};
Some(format!(
"@@ -{pick}{} +{pick}{} @@{tail}",
count(old).unwrap_or_default(),
count(new).unwrap_or_default()
))
};
patch
.split('\n')
.map(|l| fix(l).unwrap_or_else(|| l.to_string()))
.collect::<Vec<_>>()
.join("\n")
}
pub(super) fn patch_path(patch: &str) -> Option<&str> {
patch
.split('\n')
.find_map(|l| l.strip_prefix("+++ b/"))
.map(|p| p.trim_end_matches('\r'))
}
pub(super) fn strips_cr_on_add(root: &Path, rel: &str) -> bool {
let hash = |input: &[u8], args: &[&str]| -> Option<String> {
use std::io::Write as _;
let mut child = Git::new()
.at(root)
.args(["hash-object", "--stdin"])
.args(args)
.into_command()
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
child.stdin.take()?.write_all(input).ok()?;
let out = child.wait_with_output().ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
};
let path_arg = format!("--path={rel}");
match (
hash(b"croft\r\n", &[&path_arg]),
hash(b"croft\n", &["--no-filters"]),
) {
(Some(cleaned), Some(lf)) => cleaned == lf,
_ => false,
}
}
pub(super) fn strip_added_crs(patch: &str) -> String {
patch
.split('\n')
.map(|l| {
if l.starts_with('+') && !l.starts_with("+++ ") {
l.strip_suffix('\r').unwrap_or(l)
} else {
l
}
})
.collect::<Vec<_>>()
.join("\n")
}
pub(super) fn add_crs_to_head_lines(patch: &str) -> String {
patch
.split('\n')
.map(|l| {
let from_head = (l.starts_with(' ') || l.starts_with('-')) && !l.starts_with("--- ");
if from_head && !l.ends_with('\r') {
format!("{l}\r")
} else {
l.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
}
pub fn apply_patch(
root: &Path,
patch: &str,
cached: bool,
reverse: bool,
) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut args: Vec<&str> = vec!["apply", "--whitespace=nowarn"];
if cached {
args.push("--cached");
}
if reverse {
args.push("-R");
}
args.push("-");
let paths = patch.lines().filter_map(|l| {
l.strip_prefix("+++ b/")
.or_else(|| l.strip_prefix("--- a/"))
});
for rel in paths {
if let Some(filter) = path_filter(root, rel) {
let whole = match (cached, reverse) {
(true, false) => "stage",
(true, true) => "unstage",
_ => "discard",
};
return Err(format!(
"{rel} uses the {filter} filter: {whole} the whole file, not a part"
));
}
}
let retargeted = match (cached, reverse) {
(true, false) => retarget_hunk_starts(patch, HunkSide::Old),
(false, true) => retarget_hunk_starts(patch, HunkSide::New),
_ => patch.to_string(),
};
let retargeted = match patch_path(&retargeted) {
Some(rel) if strips_cr_on_add(root, rel) => {
if cached {
strip_added_crs(&retargeted)
} else if std::fs::read(root.join(rel))
.is_ok_and(|b| b.windows(2).any(|w| w == b"\r\n"))
{
add_crs_to_head_lines(&retargeted)
} else {
retargeted
}
}
_ => retargeted,
};
let patch = retargeted.as_str();
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&format!("> git {} <<patch", args.join(" ")),
);
let mut child = Git::new()
.at(path_str)
.args(&args)
.into_command()
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
if let Err(e) = stdin.write_all(patch.as_bytes()) {
drop(stdin);
let _ = child.wait();
return Err(format!("failed to feed patch to git apply: {e}"));
}
}
let output = child
.wait_with_output()
.map_err(|e| format!("git apply did not exit cleanly: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
Ok(if !stdout.is_empty() { stdout } else { stderr })
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
let err = if msg.is_empty() {
format!("git apply failed with code {:?}", output.status.code())
} else {
msg
};
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Error,
&err,
);
Err(err)
}
}