use anyhow::{bail, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use crate::workspace::Workspace;
#[derive(Debug, PartialEq, Eq)]
pub struct Block {
pub open: usize,
pub ours: std::ops::Range<usize>,
pub base: Option<std::ops::Range<usize>>,
pub theirs: std::ops::Range<usize>,
pub close: usize,
}
fn opens(line: &str, mark: &str) -> bool {
let line = line.trim_end_matches('\r');
line.strip_prefix(mark)
.is_some_and(|rest| rest.is_empty() || rest.starts_with(' '))
}
pub fn blocks(lines: &[&str]) -> Vec<Block> {
let mut out = Vec::new();
let mut open: Option<usize> = None;
let mut base: Option<usize> = None;
let mut split: Option<usize> = None;
for (idx, line) in lines.iter().enumerate() {
if opens(line, "<<<<<<<") {
(open, base, split) = (Some(idx), None, None);
} else if let Some(start) = open {
if split.is_none() && base.is_none() && opens(line, "|||||||") {
base = Some(idx);
} else if split.is_none() && opens(line, "=======") {
split = Some(idx);
} else if let Some(mid) = split.filter(|_| opens(line, ">>>>>>>")) {
let ours_end = base.unwrap_or(mid);
out.push(Block {
open: start,
ours: start + 1..ours_end,
base: base.map(|b| b + 1..mid),
theirs: mid + 1..idx,
close: idx,
});
(open, base, split) = (None, None, None);
}
}
}
out
}
fn unmerged(root: &Path) -> Result<BTreeSet<PathBuf>> {
let out = crate::workspace::git(root)
.args(["diff", "--name-only", "--diff-filter=U"])
.output()?;
if !out.status.success() {
bail!(
"git diff --name-only --diff-filter=U: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.map(PathBuf::from)
.collect())
}
fn opening_files(ws: &Workspace) -> Result<Vec<PathBuf>> {
if !ws.root.join(".git").exists() {
return Ok(Vec::new());
}
let out = crate::workspace::git(&ws.root)
.args(["grep", "--untracked", "-I", "-l", "-E", "^<<<<<<<( |$)"])
.output()?;
if !out.status.success() && !(out.status.code() == Some(1) && out.stdout.is_empty()) {
bail!(
"git grep for conflict blocks: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
Ok(String::from_utf8_lossy(&out.stdout)
.lines()
.map(|rel| ws.root.join(rel))
.filter(|path| {
path.parent()
.and_then(|dir| ws.enclosing(dir))
.is_some_and(|project| !project.external)
})
.collect())
}
fn operation(root: &Path) -> Result<Option<&'static str>> {
for (head, name) in [
("REBASE_HEAD", "a rebase"),
("CHERRY_PICK_HEAD", "a cherry-pick"),
("MERGE_HEAD", "a merge"),
] {
let out = crate::workspace::git(root)
.args(["rev-parse", "--git-path", head])
.output()?;
if !out.status.success() {
bail!(
"git rev-parse --git-path {head}: {}",
String::from_utf8_lossy(&out.stderr).trim()
);
}
let path = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
if root.join(path).is_file() {
return Ok(Some(name));
}
}
Ok(None)
}
pub fn refuse(ws: &Workspace, texts: &BTreeMap<PathBuf, String>) -> Result<()> {
let git = ws.root.join(".git").exists();
let mut found: BTreeMap<PathBuf, Option<usize>> = BTreeMap::new();
if git {
for rel in unmerged(&ws.root)? {
found.insert(rel, None);
}
}
for path in opening_files(ws)? {
let text = match texts.get(&path) {
Some(text) => text.clone(),
None => std::fs::read_to_string(&path)?,
};
let lines: Vec<&str> = text.lines().collect();
if let Some(block) = blocks(&lines).first() {
let rel = path.strip_prefix(&ws.root).unwrap_or(&path).to_path_buf();
found.insert(rel, Some(block.open + 1));
}
}
if found.is_empty() {
return Ok(());
}
let during = match git.then(|| operation(&ws.root)).transpose()?.flatten() {
Some(name) => format!("{name} is in progress and left conflicts"),
None => "no merge, rebase or cherry-pick is in progress, and the tree holds conflicts"
.to_string(),
};
let lines: Vec<String> = found
.iter()
.map(|(rel, line)| match line {
Some(line) => format!(" {}:{line}: a conflict block opens here", rel.display()),
None => format!(
" {}: git holds it unmerged with no conflict block left in it: `git add` it once it is resolved",
rel.display()
),
})
.collect();
bail!(
"{during}, so Silcrow reads no tree:\n{}\nResolve these conflicts, then run `silcrow check`.",
lines.join("\n")
)
}
fn without_digests(line: &str, keep: impl Fn(usize) -> bool) -> String {
let mut out = line.to_string();
for (at, written) in crate::marker::written(line).iter().enumerate().rev() {
if let Some(digest) = written.digest.as_ref().filter(|_| !keep(at)) {
out.replace_range(digest.start - 1..digest.end, "");
}
}
out
}
fn digest_only(lines: &[&str], block: &Block) -> Option<Vec<(String, Option<String>)>> {
let ours = &lines[block.ours.clone()];
let theirs = &lines[block.theirs.clone()];
if ours.len() != theirs.len() {
return None;
}
let mut out = Vec::new();
for (mine, other) in ours.iter().zip(theirs) {
if mine == other {
out.push((mine.to_string(), None));
continue;
}
if without_digests(mine, |_| false) != without_digests(other, |_| false) {
return None;
}
let (a, b) = (crate::marker::written(mine), crate::marker::written(other));
let same = |at: usize| {
let digest = |w: &[crate::marker::Written], line: &str| {
w.get(at)
.and_then(|w| w.digest.clone())
.map(|d| line[d].to_string())
};
digest(&a, mine) == digest(&b, other)
};
let bare: Vec<String> = a
.iter()
.enumerate()
.filter(|(at, _)| !same(*at))
.map(|(_, w)| {
crate::marker::MarkerAddr {
digest: None,
..w.addr.clone()
}
.display()
})
.collect();
out.push((without_digests(mine, same), Some(bare.join(", "))));
}
Some(out)
}
fn resolve_text(text: &str) -> Option<(String, Vec<(usize, String)>)> {
let lines: Vec<&str> = text.lines().collect();
let mut out: Vec<String> = Vec::new();
let mut bare = Vec::new();
let mut next = 0;
let mut resolved = false;
for block in blocks(&lines) {
let Some(common) = digest_only(&lines, &block) else {
continue;
};
out.extend(lines[next..block.open].iter().map(|l| l.to_string()));
for (line, addrs) in common {
out.push(line);
if let Some(addrs) = addrs {
bare.push((out.len(), addrs));
}
}
next = block.close + 1;
resolved = true;
}
if !resolved {
return None;
}
out.extend(lines[next..].iter().map(|l| l.to_string()));
let mut joined = out.join("\n");
if text.ends_with('\n') {
joined.push('\n');
}
Some((joined, bare))
}
pub fn resolve_digests(
ws: &Workspace,
projects: &[&crate::workspace::ProjectRef],
dry_run: bool,
) -> Result<BTreeMap<PathBuf, String>> {
let opening = opening_files(ws)?;
let mut texts = BTreeMap::new();
for project in projects {
let mut addrs = BTreeSet::new();
let mine = opening
.iter()
.filter(|path| path.parent().and_then(|dir| ws.enclosing(dir)) == Some(*project));
for path in mine {
let text = std::fs::read_to_string(path)?;
let Some((next, bare)) = resolve_text(&text) else {
continue;
};
let rel = path.strip_prefix(&project.dir).unwrap_or(path);
for (line, addr) in &bare {
println!(
" {} {}:{line} § {addr}: the two sides of its conflict differ only in this digest, so the marker is written bare",
if dry_run { "would RESOLVE" } else { "RESOLVE" },
rel.display()
);
addrs.extend(addr.split(", ").map(str::to_string));
}
if !dry_run {
std::fs::write(path, &next)?;
}
texts.insert(path.clone(), next);
}
if addrs.is_empty() {
continue;
}
let run_in = match project.key.as_str() {
"." => String::new(),
key => format!("-C {key} "),
};
println!(
"Read each against its law or clause with `silcrow diff`, then run `silcrow {run_in}accept {}`.",
addrs.into_iter().collect::<Vec<_>>().join(" ")
);
}
Ok(texts)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_block_that_differs_only_in_marker_digests_resolves_to_its_bare_markers() {
let text = "fn f() {\n<<<<<<< HEAD\n // § abcdefgh1.a@aaaaa\n // § abcdefgh1.b@ccccc\n||||||| base\n // § abcdefgh1.a@zzzzz\n // § abcdefgh1.b@ccccc\n=======\n // § abcdefgh1.a@bbbbb\n // § abcdefgh1.b@ccccc\n>>>>>>> other\n go();\n}\n";
let (next, bare) = resolve_text(text).unwrap();
assert_eq!(
next,
"fn f() {\n // § abcdefgh1.a\n // § abcdefgh1.b@ccccc\n go();\n}\n"
);
assert_eq!(bare, vec![(2, "abcdefgh1.a".to_string())]);
let one = "<<<<<<< HEAD\n// § one abcdefgh1.a@aaaaa, abcdefgh2@ddddd\n=======\n// § one abcdefgh1.a@bbbbb, abcdefgh2@ddddd\n>>>>>>> other\n";
let (next, bare) = resolve_text(one).unwrap();
assert_eq!(next, "// § one abcdefgh1.a, abcdefgh2@ddddd\n");
assert_eq!(bare, vec![(1, "abcdefgh1.a".to_string())]);
}
#[test]
fn a_block_that_differs_in_anything_but_a_digest_stays() {
for text in [
"<<<<<<< HEAD\n// § abcdefgh1@aaaaa\ngo();\n=======\n// § abcdefgh1@bbbbb\nstop();\n>>>>>>> other\n",
"<<<<<<< HEAD\n// § abcdefgh1@aaaaa\n||||||| base\n// § abcdefgh1@aaaaa\n=======\n// § abcdefgh1@bbbbb\ngo();\n>>>>>>> other\n",
"<<<<<<< HEAD\n// § abcdefgh1@aaaaa\n=======\n// § abcdefgh2@aaaaa\n>>>>>>> other\n",
"<<<<<<< HEAD\nlet a = \"x@aaaaa\";\n=======\nlet a = \"x@bbbbb\";\n>>>>>>> other\n",
] {
assert_eq!(resolve_text(text), None, "{text}");
}
let mixed = "<<<<<<< HEAD\n// § abcdefgh1@aaaaa\n=======\n// § abcdefgh1@bbbbb\n>>>>>>> other\nmid\n<<<<<<< HEAD\ngo();\n=======\nstop();\n>>>>>>> other\n";
let (next, _) = resolve_text(mixed).unwrap();
assert_eq!(
next,
"// § abcdefgh1\nmid\n<<<<<<< HEAD\ngo();\n=======\nstop();\n>>>>>>> other\n"
);
}
#[test]
fn a_block_runs_from_its_open_to_its_close_with_an_optional_base() {
let text = "a\n<<<<<<< HEAD\nx\n||||||| base\ny\n=======\nz\n>>>>>>> other\nb\n";
let lines: Vec<&str> = text.lines().collect();
assert_eq!(
blocks(&lines),
vec![Block {
open: 1,
ours: 2..3,
base: Some(4..5),
theirs: 6..7,
close: 7,
}]
);
let plain = "<<<<<<< HEAD\nx\n=======\nz\n>>>>>>> other\n";
let lines: Vec<&str> = plain.lines().collect();
assert_eq!(blocks(&lines)[0].base, None);
for cut in [
"<<<<<<< HEAD\nx\n=======\nz\n",
"Title\n=======\n>>>>>>> x\n",
"<<<<<<<< wide\nx\n=======\n>>>>>>> x\n",
] {
let lines: Vec<&str> = cut.lines().collect();
assert!(blocks(&lines).is_empty(), "{cut}");
}
}
}