use std::{path::Path, time::Duration};
use similar::TextDiff;
#[derive(Clone, Copy, Debug)]
pub(super) enum FileContents<'a> {
Created(&'a str),
Modified {
old: &'a str,
new: &'a str,
},
Deleted(&'a str),
Moved {
from: &'a Path,
old: &'a str,
new: &'a str,
},
}
const PATCH_DIFF_DEADLINE: Duration = Duration::from_millis(250);
pub(super) fn file_patch(path: &Path, contents: FileContents<'_>) -> Option<String> {
let path = plain_absolute(path)?;
let (source, extended, from, to, old, new) = match contents {
FileContents::Created(new) => (
path,
"new file mode 100644\n".to_owned(),
"/dev/null",
path,
"",
new,
),
FileContents::Modified { old, new } => (path, String::new(), path, path, old, new),
FileContents::Deleted(old) => (
path,
"deleted file mode 100644\n".to_owned(),
path,
"/dev/null",
old,
"",
),
FileContents::Moved { from, old, new } => {
let from = plain_absolute(from)?;
let rename = format!("rename from {from}\nrename to {path}\n");
(from, rename, from, path, old, new)
}
};
let hunks = TextDiff::configure()
.timeout(PATCH_DIFF_DEADLINE)
.diff_lines(old, new)
.unified_diff()
.header(from, to)
.to_string();
if hunks.is_empty() && extended.is_empty() {
return None;
}
Some(format!("diff --git {source} {path}\n{extended}{hunks}"))
}
fn plain_absolute(path: &Path) -> Option<&str> {
let text = path.to_str()?;
let needs_quoting = text
.chars()
.any(|c| c == '"' || c == '\\' || c.is_control() || !c.is_ascii());
(path.is_absolute() && !needs_quoting).then_some(text)
}
#[cfg(test)]
#[path = "git_patch_tests.rs"]
mod tests;