use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use super::{byte_line, path_of, read_worktree, FileMap, Side};
use crate::parse::Scan;
use crate::span;
type Range = (usize, usize);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Hunk {
pub(super) old: Range,
pub(super) new: Range,
pub(super) lines: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct FileHunks {
pub(super) path: String,
pub(super) old_path: Option<String>,
pub(super) new_path: Option<String>,
pub(super) binary: bool,
pub(super) hunks: Vec<Hunk>,
}
impl FileHunks {
pub(super) fn added(&self) -> usize {
self.hunks.iter().map(|h| h.new.1).sum()
}
pub(super) fn removed(&self) -> usize {
self.hunks.iter().map(|h| h.old.1).sum()
}
pub(super) fn counts(&self) -> String {
match self.binary {
true => "binary".to_string(),
false => format!("+{} -{}", self.added(), self.removed()),
}
}
pub(super) fn patch(&self) -> String {
if self.hunks.is_empty() {
return String::new();
}
let side = |path: &Option<String>, prefix: &str| {
path.as_ref()
.map_or("/dev/null".to_string(), |p| format!("{prefix}{p}"))
};
let old = self.old_path.as_deref().unwrap_or(&self.path);
let new = self.new_path.as_deref().unwrap_or(&self.path);
let mut out = format!(
"diff --git a/{old} b/{new}\n--- {}\n+++ {}\n",
side(&self.old_path, "a/"),
side(&self.new_path, "b/")
);
for hunk in &self.hunks {
out.push_str(&format!(
"@@ -{},{} +{},{} @@\n",
hunk.old.0, hunk.old.1, hunk.new.0, hunk.new.1
));
for line in &hunk.lines {
out.push_str(line);
out.push('\n');
}
}
out
}
}
pub(super) type Lines = BTreeMap<String, BTreeSet<usize>>;
pub(super) fn ungoverned(
root: &Path,
base: &str,
worktree: bool,
keep: impl Fn(&FileHunks) -> bool,
governed: &[Lines; 2],
) -> Result<Vec<FileHunks>> {
let mut files = git_hunks(root, base)?;
if worktree {
for rel in super::git_lines(root, &["ls-files", "--others", "--exclude-standard"])? {
if root.join(&rel).join(".git").exists() {
continue;
}
files.push(untracked(root, &rel));
}
}
let mut out = Vec::new();
for mut file in files.into_iter().filter(|file| keep(file)) {
let empty = file.hunks.is_empty();
drop_governed(&mut file, governed);
let created_or_gone = file.old_path.is_none() || file.new_path.is_none();
if !file.hunks.is_empty() || file.binary || (empty && created_or_gone) {
out.push(file);
}
}
out.sort_by(|a, b| a.path.cmp(&b.path));
Ok(out)
}
fn drop_governed(file: &mut FileHunks, governed: &[Lines; 2]) {
let empty = BTreeSet::new();
let old_lines = governed[0].get(&file.path).unwrap_or(&empty);
let new_lines = governed[1].get(&file.path).unwrap_or(&empty);
let mut kept = Vec::new();
for hunk in &file.hunks {
let (mut old, mut new) = (hunk.old.0, hunk.new.0);
if hunk.old.1 == 0 {
old += 1;
}
if hunk.new.1 == 0 {
new += 1;
}
let mut run: Option<Hunk> = None;
for line in &hunk.lines {
let removed = line.starts_with('-');
let governs = line[1..].trim().is_empty()
|| match removed {
true => old_lines.contains(&old),
false => new_lines.contains(&new),
};
if governs {
kept.extend(run.take());
} else {
let at = run.get_or_insert_with(|| Hunk {
old: (old - 1, 0),
new: (new - 1, 0),
lines: Vec::new(),
});
let side = if removed { &mut at.old } else { &mut at.new };
if side.1 == 0 {
side.0 = if removed { old } else { new };
}
side.1 += 1;
at.lines.push(line.clone());
}
if removed {
old += 1;
} else {
new += 1;
}
}
kept.extend(run);
}
file.hunks = kept;
}
fn untracked(root: &Path, rel: &Path) -> FileHunks {
let path = path_of(rel);
let mut file = FileHunks {
path: path.clone(),
old_path: None,
new_path: Some(path),
..FileHunks::default()
};
match read_worktree(root, rel) {
None => file.binary = true,
Some(text) if text.is_empty() => {}
Some(text) => {
let lines: Vec<String> = text.lines().map(|line| format!("+{line}")).collect();
file.hunks.push(Hunk {
old: (0, 0),
new: (1, lines.len()),
lines,
});
}
}
file
}
fn git_hunks(root: &Path, base: &str) -> Result<Vec<FileHunks>> {
let args = [
"-c",
"core.quotepath=off",
"diff",
"-U0",
"--no-color",
"--no-ext-diff",
"--no-textconv",
"--relative",
"--find-renames",
"--diff-filter=ACDMR",
base,
];
let out = crate::workspace::git(root)
.args(args)
.output()
.with_context(|| format!("git {}", args.join(" ")))?;
if !out.status.success() {
bail!(
"git {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr)
);
}
parse_hunks(&String::from_utf8_lossy(&out.stdout))
}
fn parse_hunks(patch: &str) -> Result<Vec<FileHunks>> {
let unquote = |path: &str| path.trim_matches('"').to_string();
let named = |line: &str, prefix: &str| match line {
"/dev/null" => None,
path => Some(unquote(path).trim_start_matches(prefix).to_string()),
};
let mut out: Vec<FileHunks> = Vec::new();
let mut in_hunk = false;
for line in patch.lines() {
if let Some(rest) = line.strip_prefix("diff --git ") {
let (old, new) = rest
.split_once(" b/")
.map(|(old, new)| {
(
unquote(old).trim_start_matches("a/").to_string(),
unquote(new),
)
})
.unwrap_or_else(|| (rest.to_string(), rest.to_string()));
out.push(FileHunks {
path: new.clone(),
old_path: Some(old),
new_path: Some(new),
..FileHunks::default()
});
in_hunk = false;
continue;
}
let Some(file) = out.last_mut() else {
continue;
};
if let Some(range) = line.strip_prefix("@@ ") {
file.hunks.push(
parse_range(range).with_context(|| format!("git diff: malformed hunk {line:?}"))?,
);
in_hunk = true;
continue;
}
if in_hunk {
if line.starts_with('+') || line.starts_with('-') {
if let Some(hunk) = file.hunks.last_mut() {
hunk.lines.push(line.to_string());
}
}
continue;
}
if let Some(path) = line.strip_prefix("--- ") {
file.old_path = named(path, "a/");
} else if let Some(path) = line.strip_prefix("+++ ") {
file.new_path = named(path, "b/");
} else if let Some(path) = line.strip_prefix("rename from ") {
file.old_path = Some(unquote(path));
} else if let Some(path) = line.strip_prefix("rename to ") {
file.new_path = Some(unquote(path));
} else if line.starts_with("new file mode") {
file.old_path = None;
} else if line.starts_with("deleted file mode") {
file.new_path = None;
} else if line.starts_with("Binary files ") {
file.binary = true;
}
if let Some(path) = file.new_path.as_ref().or(file.old_path.as_ref()) {
file.path = path.clone();
}
}
Ok(out)
}
fn parse_range(range: &str) -> Option<Hunk> {
let mut fields = range.split_whitespace();
let side = |field: Option<&str>, sign: char| -> Option<Range> {
let field = field?.strip_prefix(sign)?;
let (start, len) = field.split_once(',').unwrap_or((field, "1"));
Some((start.parse().ok()?, len.parse().ok()?))
};
let old = side(fields.next(), '-')?;
let new = side(fields.next(), '+')?;
Some(Hunk {
old,
new,
lines: Vec::new(),
})
}
pub(super) fn note_lines(scan: &Scan, renamed: &BTreeMap<String, String>) -> Lines {
let key = |path: &Path| {
let path = path_of(path);
renamed.get(&path).cloned().unwrap_or(path)
};
let mut out = Lines::new();
for law in &scan.laws {
let end = law
.clauses
.iter()
.map(|clause| clause.end)
.chain([law.end])
.max()
.unwrap_or(law.loc.line);
out.entry(key(&law.loc.path))
.or_default()
.extend(law.loc.line..=end.max(law.loc.line));
}
for pointer in &scan.pointers {
out.entry(key(&pointer.loc.path))
.or_default()
.insert(pointer.loc.line);
}
out
}
pub(super) fn governed(
files: &FileMap,
sides: Option<&[Side; 2]>,
notes: [Lines; 2],
renamed: &BTreeMap<String, String>,
) -> [Lines; 2] {
let mut out = notes;
for (path, texts) in files {
for (side, text) in [&texts.0, &texts.1].into_iter().enumerate() {
let Some(text) = text else {
continue;
};
let lines = out[side].entry(path.clone()).or_default();
let rel = PathBuf::from(path);
for row in span::marker_rows(&rel, text, None) {
lines.insert(row.idx + 1);
}
let file = span::CodeFile::new(rel, text.clone());
for marker in file.span_markers() {
lines.extend(byte_lines(text, marker.start, marker.end));
for (from, to, _) in file.prefix(marker.start, marker.end) {
lines.extend(byte_lines(text, from, to));
}
}
}
}
let Some(sides) = sides else {
return out;
};
for (at, side) in sides.iter().enumerate() {
for (rel, file) in &side.files {
let Some(markers) = side.markers.get(rel) else {
continue;
};
for marker in markers {
let punch = span::punch_of(markers, marker.line);
let prefix = file.prefix(marker.start, marker.end);
let callees =
side.follow
.followed_callees(rel, marker.start, marker.end, &punch, &prefix);
for callee in callees {
let path = path_of(&callee.path);
let path = renamed.get(&path).cloned().unwrap_or(path);
let Some(text) = side.files.get(&callee.path).map(|f| f.text.as_str()) else {
continue;
};
if files.contains_key(&path) {
out[at].entry(path).or_default().extend(byte_lines(
text,
callee.start,
callee.end,
));
}
}
}
}
}
out
}
fn byte_lines(text: &str, start: usize, end: usize) -> std::ops::RangeInclusive<usize> {
byte_line(text, start)..=byte_line(text, end.saturating_sub(1).max(start))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_patch_reads_as_its_files_and_hunks() {
let patch = "diff --git a/src/a.ts b/src/a.ts\nindex 1..2 100644\n--- a/src/a.ts\n+++ b/src/a.ts\n@@ -2 +2 @@ fn\n- return a;\n+ return b;\n@@ -9,0 +10,2 @@\n+--- not a header\n+x\ndiff --git a/old.md b/new.md\nsimilarity index 100%\nrename from old.md\nrename to new.md\ndiff --git a/gone.rs b/gone.rs\ndeleted file mode 100644\n--- a/gone.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-a\n-b\ndiff --git a/i.png b/i.png\nBinary files a/i.png and b/i.png differ\n";
let files = parse_hunks(patch).unwrap();
assert_eq!(files.len(), 4, "{files:?}");
assert_eq!(files[0].hunks.len(), 2);
assert_eq!(files[0].hunks[0].old, (2, 1));
assert_eq!(files[0].hunks[1].new, (10, 2));
assert_eq!(files[0].hunks[1].lines, ["+--- not a header", "+x"]);
assert_eq!(files[0].counts(), "+3 -1");
assert_eq!(
(files[1].old_path.as_deref(), files[1].path.as_str()),
(Some("old.md"), "new.md")
);
assert_eq!(
(files[2].new_path.as_deref(), files[2].path.as_str()),
(None, "gone.rs")
);
assert!(files[2]
.patch()
.contains("+++ /dev/null\n@@ -1,2 +0,0 @@\n-a\n-b\n"));
assert!(files[3].binary);
assert_eq!(files[3].counts(), "binary");
}
#[test]
fn a_blank_changed_line_is_never_under_no_law() {
let mut file = FileHunks {
path: "src/a.rs".into(),
old_path: Some("src/a.rs".into()),
new_path: Some("src/a.rs".into()),
binary: false,
hunks: vec![
Hunk {
old: (3, 1),
new: (3, 2),
lines: vec!["-".into(), "+".into(), "+ \t".into()],
},
Hunk {
old: (9, 0),
new: (10, 3),
lines: vec!["+x".into(), "+ ".into(), "+y".into()],
},
],
};
drop_governed(&mut file, &[Lines::new(), Lines::new()]);
let lines: Vec<&[String]> = file.hunks.iter().map(|h| h.lines.as_slice()).collect();
assert_eq!(lines, [&["+x".to_string()][..], &["+y".to_string()][..]]);
}
#[test]
fn a_line_a_governed_line_of_its_side_holds_leaves_its_hunk() {
let file = FileHunks {
path: "src/a.rs".into(),
old_path: Some("src/a.rs".into()),
new_path: Some("src/a.rs".into()),
binary: false,
hunks: vec![
Hunk {
old: (2, 1),
new: (2, 1),
lines: vec!["-a".into(), "+b".into()],
},
Hunk {
old: (5, 0),
new: (6, 1),
lines: vec!["+c".into()],
},
Hunk {
old: (9, 1),
new: (9, 0),
lines: vec!["-d".into()],
},
],
};
let lines =
|at: &[usize]| Lines::from([("src/a.rs".to_string(), at.iter().copied().collect())]);
let keep = |governed: [Lines; 2]| {
let mut kept = file.clone();
drop_governed(&mut kept, &governed);
kept.hunks
.iter()
.map(|h| h.lines[0].clone())
.collect::<Vec<_>>()
};
assert_eq!(keep([lines(&[9]), lines(&[6])]), ["-a"]);
assert_eq!(keep([lines(&[2]), lines(&[])]), ["+b", "+c", "-d"]);
assert_eq!(keep([lines(&[5]), lines(&[5, 7])]), ["-a", "+c", "-d"]);
let mut mixed = FileHunks {
hunks: vec![Hunk {
old: (4, 0),
new: (5, 3),
lines: vec!["+x".into(), "+y".into(), "+z".into()],
}],
..file.clone()
};
drop_governed(&mut mixed, &[Lines::new(), lines(&[6])]);
let runs: Vec<(Range, Range, usize)> = mixed
.hunks
.iter()
.map(|h| (h.old, h.new, h.lines.len()))
.collect();
assert_eq!(runs, [((4, 0), (5, 1), 1), ((4, 0), (7, 1), 1)]);
}
}