use anyhow::{bail, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use crate::marker::MarkerAddr;
use crate::model::{Law, PointerKind, Scan, Target};
use crate::parse;
use crate::published;
use crate::resolve;
use crate::span;
use crate::walk;
use crate::workspace::{ProjectRef, Workspace};
use crate::write::{self, WritePlan};
struct Gone<'a> {
project: &'a str,
ids: BTreeSet<String>,
letter: Option<&'a str>,
}
impl Gone<'_> {
fn names(&self, from: &str, qualifier: Option<&str>, id: &str, letter: Option<&str>) -> bool {
qualifier.unwrap_or(from) == self.project
&& self.ids.contains(id)
&& self.letter.is_none_or(|l| letter == Some(l))
}
}
#[derive(Default)]
pub(crate) struct Cut {
lines: BTreeSet<usize>,
blocks: BTreeSet<usize>,
pub(crate) rewrites: BTreeMap<usize, String>,
}
impl Cut {
pub(crate) fn block(&mut self, start: usize, end: usize) {
self.blocks.insert(start);
self.lines.extend(start..=end);
}
pub(crate) fn apply(&self, text: &str) -> String {
let mut out: Vec<&str> = Vec::new();
for (idx, line) in text.lines().enumerate() {
let n = idx + 1;
if let Some(next) = self.rewrites.get(&n) {
out.push(next);
continue;
}
if !self.lines.contains(&n) {
out.push(line);
continue;
}
let starts = self.blocks.contains(&n) && !self.lines.contains(&(n - 1));
if starts && out.last().is_some_and(|l| l.trim().is_empty()) {
out.pop();
}
}
let mut next = out.join("\n");
if text.ends_with('\n') && !next.is_empty() {
next.push('\n');
}
next
}
}
type Cuts = BTreeMap<(String, PathBuf), Cut>;
pub fn run(
ws: &Workspace,
project: &ProjectRef,
scan: &Scan,
law: &Law,
letter: Option<&str>,
dry_run: bool,
) -> Result<()> {
let root = project.dir.as_path();
let label = match letter {
Some(letter) => format!("{}.{letter}", law.id),
None => law.id.clone(),
};
let removes = letter.is_none() && !active_at_base(ws, root, law)?;
let gone = Gone {
project: &project.key,
ids: std::iter::once(&law.id)
.chain(&law.aliases)
.cloned()
.collect(),
letter,
};
let mut cuts = Cuts::new();
let mut actions = Vec::new();
let mut refused = Vec::new();
if removes {
let cut = cuts
.entry((project.key.clone(), law.loc.path.clone()))
.or_default();
cut.block(law.loc.line, law.end);
for al in &law.clauses {
cut.block(al.loc.line, al.end);
}
actions.push(format!(
"REMOVE {}:{} § {}",
law.loc.path.display(),
law.loc.line,
law.id
));
}
for other in ws.local() {
let owned;
let other_scan = if other.key == project.key {
scan
} else {
owned = parse::scan_root(&other.dir)?;
&owned
};
unmark(&gone, other, other_scan, &mut cuts, &mut actions)?;
if removes {
drop_references(
&gone,
other,
other_scan,
law,
&mut cuts,
&mut actions,
&mut refused,
)?;
}
}
if !refused.is_empty() {
bail!(
"accept would leave references to the removed § {label}. Rewrite each one without it first:\n {}",
refused.join("\n ")
);
}
for action in &actions {
println!(" {action}");
}
let tail = if removes || letter.is_some() {
String::new()
} else {
format!(
" Its struck text stays until the published tree holds the strike: run `silcrow accept {label}` again after the merge."
)
};
if cuts.is_empty() {
println!("✓ § {label} carries no marker.{tail}");
return Ok(());
}
let projects: BTreeMap<&str, &ProjectRef> = ws
.local()
.into_iter()
.filter(|p| cuts.keys().any(|(key, _)| *key == p.key))
.map(|p| (p.key.as_str(), p))
.collect();
let mut plans: BTreeMap<&str, Vec<(PathBuf, String, String)>> = BTreeMap::new();
for ((key, rel), cut) in &cuts {
let dir = &projects[key.as_str()].dir;
let text = std::fs::read_to_string(dir.join(rel))?;
let next = cut.apply(&text);
plans
.entry(key.as_str())
.or_default()
.push((rel.clone(), text, next));
}
let sandbox = if dry_run {
Some(write::Sandbox::of(ws)?)
} else {
None
};
let target = sandbox.as_ref().map_or(ws, |s| &s.ws);
for (key, files) in &plans {
let project = match &sandbox {
Some(s) => s.project(projects[key])?,
None => projects[key],
};
let red_before = red(target, project)?;
let writes = files
.iter()
.map(|(rel, _, next)| (rel.clone(), next.clone()));
write::apply(
&WritePlan {
writes: writes.collect(),
},
&project.dir,
false,
)?;
let red_after = red(target, project)?;
let moved: BTreeSet<&Ranked> = red_after.difference(&red_before).collect();
repin_moved(target, project, &moved, dry_run)?;
}
if let Some(sandbox) = &sandbox {
sandbox.show(ws)?;
println!("\nNothing was written: run `silcrow accept {label} --write` to write it.{tail}");
return Ok(());
}
if removes {
println!("✓ Removed § {label}.");
} else {
println!("✓ Removed the markers of § {label}.{tail}");
}
Ok(())
}
fn active_at_base(ws: &Workspace, root: &Path, law: &Law) -> Result<bool> {
let Some(base) = ws.base_ref("HEAD")? else {
return Ok(false);
};
Ok(published::at(root, &base)?
.law_of(law)
.is_some_and(|held| !held.struck))
}
fn unmark(
gone: &Gone,
project: &ProjectRef,
scan: &Scan,
cuts: &mut Cuts,
actions: &mut Vec<String>,
) -> Result<()> {
let mut files: BTreeSet<PathBuf> = walk::code_files(&project.dir)?.into_iter().collect();
files.extend(walk::doc_files(&project.dir)?);
for path in files {
let text = std::fs::read_to_string(&path)?;
if !text.contains('§') {
continue;
}
let rel = PathBuf::from(parse::display_path(&path, &project.dir));
for row in span::marker_rows(&rel, &text, None) {
let idx = row.idx;
let from = project.key.as_str();
let names = |addr: &MarkerAddr| {
gone.names(
from,
addr.project.as_deref(),
&addr.id,
addr.letter.as_deref(),
)
};
let kept = crate::marker::is_one(row.line)
.then(|| crate::marker::drop_from_one(row.line, names))
.flatten();
for addr in row.markers.into_iter().chain(row.end) {
if names(&addr) {
let cut = cuts.entry((project.key.clone(), rel.clone())).or_default();
match &kept {
Some(next) => {
cut.rewrites.insert(idx + 1, next.clone());
}
None => {
cut.lines.insert(idx + 1);
}
}
actions.push(format!(
"UNMARK [{}] {}:{} § {}",
project.key,
rel.display(),
idx + 1,
addr.display()
));
}
}
}
}
for adoption in &scan.adoptions {
if adoption.project == project.key
|| !gone.names(
&project.key,
Some(&adoption.project),
&adoption.id,
adoption.letter.as_deref(),
)
{
continue;
}
let line = adoption.loc.line;
cuts.entry((project.key.clone(), adoption.loc.path.clone()))
.or_default()
.block(line, line);
actions.push(format!(
"UNADOPT [{}] {}:{line}",
project.key,
adoption.loc.path.display()
));
}
Ok(())
}
fn drop_references(
gone: &Gone,
project: &ProjectRef,
scan: &Scan,
removed: &Law,
cuts: &mut Cuts,
actions: &mut Vec<String>,
refused: &mut Vec<String>,
) -> Result<()> {
let key = project.key.as_str();
let refs: Vec<_> = scan
.pointers
.iter()
.filter(|p| p.kind == PointerKind::Cite)
.chain(&scan.mentions)
.collect();
let names = |ptr: &crate::model::Pointer| match &ptr.target {
Target::Stable { id, letter } => {
gone.names(key, ptr.project.as_deref(), id, letter.as_deref())
}
_ => false,
};
let mut texts: BTreeMap<PathBuf, String> = BTreeMap::new();
for ptr in refs.iter().filter(|p| names(p)) {
let (path, line) = (&ptr.loc.path, ptr.loc.line);
let cut = cuts.entry((key.to_string(), path.clone())).or_default();
if cut.lines.contains(&line) {
continue;
}
let at = format!("[{key}] {}:{line}", path.display());
if let Some(holder) = law_text_at(scan, removed, key == gone.project, path, line) {
refused.push(format!("{at}: § {holder} names it in its text, and its id or its pins would move. Rewrite it first."));
continue;
}
if !texts.contains_key(path) {
texts.insert(
path.clone(),
std::fs::read_to_string(project.dir.join(path))?,
);
}
let text = texts[path].lines().nth(line - 1).unwrap_or_default();
let alone = refs
.iter()
.filter(|p| p.loc.path == *path && p.loc.line == line)
.all(|p| names(p));
if alone && parse::is_reference_only(text) {
cut.block(line, line);
actions.push(format!("UNCITE {at}"));
} else {
refused.push(format!("{at}: names it in prose."));
}
}
Ok(())
}
fn law_text_at(scan: &Scan, removed: &Law, own: bool, path: &Path, line: usize) -> Option<String> {
scan.laws
.iter()
.filter(|law| !(own && law.id == removed.id) && law.loc.path == path)
.find(|law| {
(law.loc.line..=law.end).contains(&line)
|| law
.clauses
.iter()
.any(|al| (al.loc.line..=al.end).contains(&line))
})
.map(|law| law.id.clone())
}
type Ranked = (PathBuf, String, usize);
fn red(ws: &Workspace, project: &ProjectRef) -> Result<BTreeSet<Ranked>> {
let texts = resolve::project_pin_texts(ws, project)?;
let mut out = BTreeSet::new();
for (rel, line, addr) in span::unpinned(&project.dir, &texts, &|_| true)? {
let text = std::fs::read_to_string(project.dir.join(&rel))?;
let rank = rank(&rel, &text, line, &addr);
out.insert((rel, addr, rank));
}
Ok(out)
}
fn rank(rel: &Path, text: &str, line: usize, addr: &str) -> usize {
span::marker_rows(rel, text, None)
.into_iter()
.take_while(|row| row.idx + 1 < line)
.flat_map(|row| row.markers)
.filter(|m| marker_address(m) == addr)
.count()
}
fn marker_address(m: &MarkerAddr) -> String {
MarkerAddr {
digest: None,
..m.clone()
}
.display()
}
fn repin_moved(
ws: &Workspace,
project: &ProjectRef,
moved: &BTreeSet<&Ranked>,
dry_run: bool,
) -> Result<()> {
if moved.is_empty() {
return Ok(());
}
let addrs: BTreeSet<&str> = moved.iter().map(|(_, addr, _)| addr.as_str()).collect();
let texts = resolve::project_pin_texts(ws, project)?;
let plan = span::repin_where(&project.dir, &texts, &|m| {
addrs.contains(marker_address(m).as_str())
})?;
let mut writes = Vec::new();
for (rel, next) in plan.writes {
let text = std::fs::read_to_string(project.dir.join(&rel))?;
let mut rows: BTreeMap<usize, Vec<MarkerAddr>> = span::marker_rows(&rel, &text, None)
.into_iter()
.map(|row| (row.idx, row.markers))
.collect();
let mut seen: BTreeMap<String, usize> = BTreeMap::new();
let mut out = Vec::new();
for (idx, (now, then)) in text.lines().zip(next.lines()).enumerate() {
let mut take = false;
for m in rows.remove(&idx).unwrap_or_default() {
let addr = marker_address(&m);
let n = seen.entry(addr.clone()).or_default();
if moved.contains(&(rel.clone(), addr.clone(), *n)) {
take = true;
println!(
" {} [{}] {} § {addr}: the removal moved its span or a callee it follows",
if dry_run { "would REPIN" } else { "REPIN" },
project.key,
rel.display()
);
}
*n += 1;
}
out.push(if take { then } else { now });
}
let mut joined = out.join("\n");
if text.ends_with('\n') {
joined.push('\n');
}
if joined != text {
writes.push((rel, joined));
}
}
write::apply(&WritePlan { writes }, &project.dir, false)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_block_takes_its_blank_line_and_a_marker_line_goes_alone() {
let mut cut = Cut::default();
cut.block(3, 3);
cut.block(5, 5);
let note = "# A\n\n**§ abcdefgh1 ~~Old.~~**\n\n- (a) ~~First.~~\n\n**§ abcdefgh2 Kept.**\n";
assert_eq!(cut.apply(note), "# A\n\n**§ abcdefgh2 Kept.**\n");
let mut cut = Cut::default();
cut.lines.insert(2);
let code = "fn f() {\n // § abcdefgh1\n\n g();\n}\n";
assert_eq!(cut.apply(code), "fn f() {\n\n g();\n}\n");
}
#[test]
fn a_law_is_named_by_any_of_its_ids_from_its_project_or_qualified() {
let gone = Gone {
project: ".",
ids: BTreeSet::from(["abcdefgh1".to_string(), "abcdefgh2".to_string()]),
letter: None,
};
assert!(gone.names(".", None, "abcdefgh1", Some("a")));
assert!(gone.names("lib", Some("."), "abcdefgh2", None));
assert!(!gone.names("lib", None, "abcdefgh1", None));
assert!(!gone.names(".", None, "abcdefgh3", None));
let clause = Gone {
letter: Some("b"),
..gone
};
assert!(clause.names(".", None, "abcdefgh1", Some("b")));
assert!(!clause.names(".", None, "abcdefgh1", Some("a")));
assert!(!clause.names(".", None, "abcdefgh1", None));
}
}