use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use crate::hash;
use crate::marker::MarkerAddr;
use crate::parse;
use crate::published;
use crate::remove;
use crate::resolve;
use crate::span;
use crate::workspace::{ProjectRef, Workspace};
use crate::write;
pub fn run(ws: &Workspace, project: &ProjectRef, addrs: &[String], dry_run: bool) -> Result<()> {
let mut seen = BTreeSet::new();
let addrs: Vec<&str> = addrs
.iter()
.map(String::as_str)
.filter(|addr| seen.insert(*addr))
.collect();
match addrs[..] {
[addr] => run_one(ws, project, addr, dry_run),
_ => run_many(ws, project, &addrs, dry_run),
}
}
fn run_many(ws: &Workspace, project: &ProjectRef, addrs: &[&str], dry_run: bool) -> Result<()> {
let scan = parse::scan_root(&project.dir)?;
let mut repins = Vec::new();
for addr in addrs {
match step(ws, project, &scan, addr) {
Ok(Step::Repin(at)) => repins.push(at),
Ok(Step::Law(law)) if hash::mint_id(&law.name) == law.id => repins.push(law.id.clone()),
Ok(_) => bail!(
"§ {addr} would remint or remove a law, which is accepted alone: run `silcrow accept {addr}` on its own. Nothing was written."
),
Err(e) => return Err(e.context(format!("§ {addr} fails, so nothing was written"))),
}
}
let mode = if dry_run { Mode::DryRun } else { Mode::Write };
repin_in(ws, project, &repins, mode)
}
pub fn run_drifted(
ws: &Workspace,
projects: &[&ProjectRef],
paths: &[PathBuf],
label: Option<&str>,
dry_run: bool,
) -> Result<()> {
let tagged = projects.len() > 1;
let mut plans = Vec::new();
for project in projects {
let mut addrs = BTreeSet::new();
let mut lines = BTreeSet::new();
for (drift, reads) in crate::check::drifted_pins(ws, project)? {
if !paths.is_empty() && !reads.iter().any(|read| paths.contains(read)) {
continue;
}
lines.insert((drift.path.clone(), drift.line - 1));
let addr = MarkerAddr {
digest: None,
..drift.pin
}
.display();
println!(
" DRIFTED {}{}:{} § {addr}",
tag(tagged, project),
drift.path.display(),
drift.line,
);
addrs.insert(addr);
}
let scan = parse::scan_root(&project.dir)?;
for addr in &addrs {
match step(ws, project, &scan, addr) {
Ok(Step::Repin(_)) => {}
Ok(Step::Law(law)) if hash::mint_id(&law.name) == law.id => {}
Ok(_) => bail!(
"{}§ {addr} would remint or remove a law, which is accepted alone: run `silcrow accept {addr}` on its own. Nothing was written.",
tag(tagged, project)
),
Err(e) => {
return Err(e.context(format!(
"{}§ {addr} fails, so nothing was written",
tag(tagged, project)
)))
}
}
}
let addrs: Vec<String> = addrs.into_iter().collect();
refuse_unhashable(&project.dir, &addrs)?;
plans.push((project, addrs, lines));
}
let mode = if dry_run { Mode::DryRun } else { Mode::Write };
let again = match (tagged, label) {
(true, None) => "--drifted --all".to_string(),
(false, None) => "--drifted".to_string(),
(true, Some(label)) => format!("--drifted --all {label}"),
(false, Some(label)) => format!("--drifted {label}"),
};
let mut planned = Vec::new();
for (project, addrs, lines) in plans {
let repins = match (addrs.is_empty(), paths.is_empty()) {
(true, _) => None,
(false, true) => Some(plan_as(ws, project, &addrs, mode)?),
(false, false) => Some(plan_lines(ws, project, &addrs, &lines, mode)?),
};
planned.push((project, addrs, repins));
}
let done = match paths.is_empty() {
true => None,
false => Some("✓ Re-pinned each pin named above, and no other pin of its address."),
};
for (project, addrs, repins) in planned {
if tagged {
println!("[{}]", project.key);
}
let Some(repins) = repins else {
println!("✓ No pin drifts.");
continue;
};
let done = done.map_or_else(|| format!("✓ Re-pinned {}.", shown(&addrs)), str::to_string);
write_repins(project, &repins, &addrs, mode, &again, &done)?;
}
Ok(())
}
fn tag(tagged: bool, project: &ProjectRef) -> String {
match tagged {
true => format!("[{}] ", project.key),
false => String::new(),
}
}
enum Step<'a> {
Repin(String),
Law(&'a parse::Law),
Remove(&'a parse::Law, Option<String>),
}
fn step<'a>(
ws: &Workspace,
project: &ProjectRef,
scan: &'a parse::Scan,
addr: &str,
) -> Result<Step<'a>> {
let (origin, local) = match addr.rsplit_once(':') {
Some((origin, local)) if origin != project.key => (Some(origin), local),
Some((_, local)) => (None, local),
None => (None, addr),
};
let (id, letter) = match local.split_once('.') {
Some((id, letter)) => (id, Some(letter)),
None => (local, None),
};
if id.len() != 9 {
bail!(
"accept expects `[projectpath:]id` or `[projectpath:]id.letter`, with a 9-character id"
);
}
if let Some(origin) = origin {
return repin_qualified(ws, project, origin, id, letter).map(Step::Repin);
}
let Some(law) = scan.laws.iter().find(|law| law.id == id) else {
if let Some(keeper) = scan
.laws
.iter()
.find(|law| law.aliases.iter().any(|a| a == id))
{
return accept_alias(keeper, local, letter).map(Step::Repin);
}
bail!("no declared law carries § {id}");
};
if let Some(letter) = letter {
let Some(clause) = law
.clauses
.iter()
.find(|al| al.letter.as_deref() == Some(letter))
else {
bail!("§ {id} has no clause ({letter})");
};
if law.struck || clause.struck {
return Ok(Step::Remove(law, Some(letter.to_string())));
}
return Ok(Step::Repin(local.to_string()));
}
if law.struck {
return Ok(Step::Remove(law, None));
}
Ok(Step::Law(law))
}
fn run_one(ws: &Workspace, project: &ProjectRef, addr: &str, dry_run: bool) -> Result<()> {
let root = project.dir.as_path();
let scan = parse::scan_root(root)?;
let law = match step(ws, project, &scan, addr)? {
Step::Repin(at) => return repin(ws, project, &at, dry_run),
Step::Remove(law, letter) => {
return remove::run(ws, project, &scan, law, letter.as_deref(), dry_run)
}
Step::Law(law) => law,
};
let id = law.id.as_str();
let new_id = hash::mint_id(&law.name);
let old_sentences = head_sentences(root, std::iter::once(law))?;
let names = |q: &ProjectRef, of_id: &str, p: &MarkerAddr| {
let here = match p.project.as_deref() {
None => q.key == project.key,
Some(key) => key == project.key,
};
here && p.letter.is_some() && p.id == of_id
};
if new_id == id {
let held = sentence_held(ws, project, project, &old_sentences, &|p| {
names(project, id, p)
})?;
if held.is_empty() {
return repin(ws, project, id, dry_run);
}
let sandbox = if dry_run {
Some(write::Sandbox::of(ws)?)
} else {
None
};
let target = sandbox.as_ref().map_or(ws, |s| &s.ws);
let here = match &sandbox {
Some(s) => s.project(project)?.clone(),
None => project.clone(),
};
let texts = resolve::project_pin_texts(target, &here)?;
let plan = span::repin_at(&here.dir, texts, &held, &|p| names(project, id, p))?;
for (rel, _) in &plan.writes {
println!(
" {} {} § {id} clauses, the carrying sentence they hash moved",
repin_word(dry_run),
rel.display()
);
}
write::apply(&plan, &here.dir, false)?;
let mode = if dry_run { Mode::Sandbox } else { Mode::Write };
let result = repin_in(target, &here, &[id.to_string()], mode);
if let Some(sandbox) = &sandbox {
sandbox.show(ws)?;
nothing_written(id);
}
return result;
}
if let Some(other) = scan.laws.iter().find(|other| other.id == new_id) {
bail!(
"§ {id} would remint to {new_id}, which the law at {}:{} already carries: a duplicate id is refused. Reword one of the two carrying sentences.",
other.loc.path.display(),
other.loc.line
);
}
if let Some(keeper) = scan
.laws
.iter()
.find(|other| other.loc != law.loc && other.aliases.contains(&new_id))
{
bail!(
"§ {id} would remint to {new_id}, an alias anchor of § {} at {}:{}: an alias anchor is a taken id, and a marker or a cite of it resolves to the law that keeps it. Reword the carrying sentence.",
keeper.id,
keeper.loc.path.display(),
keeper.loc.line
);
}
if !law.aliases.contains(&new_id) {
let frozen = ws.frozen(root, &BTreeSet::from([new_id.clone()]))?;
if frozen.contains(&new_id) {
bail!(
"§ {id} would remint to {new_id}, which a removed law carried in the published history: an id never comes back with another meaning. Reword the carrying sentence."
);
}
}
refuse_unhashable(root, &[id.to_string()])?;
let mut remap = BTreeMap::new();
remap.insert(id.to_string(), new_id.clone());
let mut own = resolve::plan_remap(root, remap.clone())?;
let mut others = Vec::new();
for other in ws
.local()
.into_iter()
.filter(|other| other.key != project.key)
{
let plan = resolve::plan_remap_qualified(&other.dir, &project.key, &remap)?;
own.kept.extend(plan.kept.iter().cloned());
others.push((other, plan.plan));
}
if law.aliases.contains(&new_id) {
let Some((_, text)) = own
.plan
.writes
.writes
.iter_mut()
.find(|(rel, _)| *rel == law.loc.path)
else {
bail!(
"{}: the remint of § {id} rewrote no head",
law.loc.path.display()
);
};
*text = drop_alias(text, law.loc.line, &new_id)?;
}
let alias = is_published(ws, root, id)? || own.kept.contains(id);
if alias {
let Some((_, text)) = own
.plan
.writes
.writes
.iter_mut()
.find(|(rel, _)| *rel == law.loc.path)
else {
bail!(
"{}: the remint of § {id} rewrote no head",
law.loc.path.display()
);
};
*text = add_alias(text, law.loc.line, &new_id, id)?;
}
let citing = citing_addresses(ws, project, &scan, id)?;
let cites = |q: &ProjectRef, p: &MarkerAddr| {
let key = p.project.as_deref().unwrap_or(&q.key);
let letter = p.letter.as_ref().map_or(String::new(), |l| format!(".{l}"));
citing.contains(&format!("{key}:{}{letter}", p.id))
};
let mut held = Vec::new();
for q in std::iter::once(project).chain(others.iter().map(|(other, _)| *other)) {
let at = sentence_held(ws, project, q, &old_sentences, &|p| {
names(q, id, p) || cites(q, p)
})?;
held.push((q, at));
}
for action in &own.plan.actions {
println!(" {action}");
}
for warn in &own.plan.warnings {
println!(" {warn}");
}
if alias {
println!(" ALIAS {} keeps #{id}", law.loc.path.display());
}
let sandbox = if dry_run {
Some(write::Sandbox::of(ws)?)
} else {
None
};
let target = sandbox.as_ref().map_or(ws, |s| &s.ws);
let at = |q: &ProjectRef| -> Result<ProjectRef> {
Ok(match &sandbox {
Some(s) => s.project(q)?.clone(),
None => q.clone(),
})
};
write::apply(&own.plan.writes, &at(project)?.dir, false)?;
for (other, plan) in &others {
for warn in &plan.warnings {
println!(" [{}] {warn}", other.key);
}
write::apply(&plan.writes, &at(other)?.dir, false)?;
}
for (q, held_at) in &held {
let q = at(q)?;
let texts = resolve::project_pin_texts(target, &q)?;
let plan = span::repin_at(&q.dir, texts, held_at, &|p| {
names(&q, &new_id, p) || cites(&q, p)
})?;
for (rel, next) in &plan.writes {
let old = std::fs::read_to_string(q.dir.join(rel))?;
for pin in repinned(&old, next) {
let what = if names(&q, &new_id, &pin) {
format!("a clause of § {new_id}")
} else {
format!("a law that cites § {new_id}")
};
println!(
" {} {} § {}, {what}: only the id moved",
repin_word(dry_run),
rel.display(),
pin.display()
);
}
}
write::apply(&plan, &q.dir, false)?;
}
let mode = if dry_run { Mode::Sandbox } else { Mode::Write };
let result = repin_in(target, &at(project)?, std::slice::from_ref(&new_id), mode);
if let Some(sandbox) = &sandbox {
sandbox.show(ws)?;
nothing_written(id);
}
match (dry_run, result) {
(false, Ok(())) => {
println!("✓ {id} -> {new_id}");
Ok(())
}
(false, Err(e)) => Err(e.context(format!("§ {id} is reminted to {new_id} and written"))),
(true, result) => result,
}
}
fn repinned(old: &str, next: &str) -> Vec<MarkerAddr> {
old.lines()
.zip(next.lines())
.filter(|(was, now)| was != now)
.flat_map(|(was, now)| {
let before = crate::marker::markers_in_line(was);
crate::marker::markers_in_line(now)
.into_iter()
.filter(move |pin| !before.contains(pin))
})
.collect()
}
fn citing_addresses(
ws: &Workspace,
project: &ProjectRef,
own: &parse::Scan,
id: &str,
) -> Result<BTreeSet<String>> {
let cite = regex::Regex::new(&format!(r"\b{id}\b"))?;
let scans = ws.law_scans(&project.key)?;
let mut out = BTreeSet::new();
for (key, scan) in std::iter::once((&project.key, own)).chain(&scans.scans) {
for law in scan.laws.iter().filter(|law| law.id != id) {
if cite.is_match(&law.pin_text()) {
out.insert(format!("{key}:{}", law.id));
}
for clause in &law.clauses {
if let Some(letter) = clause
.letter
.as_ref()
.filter(|_| cite.is_match(&clause.body))
{
out.insert(format!("{key}:{}.{letter}", law.id));
}
}
}
}
Ok(out)
}
pub(crate) fn head_sentences<'a>(
root: &Path,
laws: impl Iterator<Item = &'a crate::model::Law>,
) -> Result<BTreeMap<String, String>> {
let born = crate::workspace::git(root)
.args(["rev-parse", "--verify", "-q", "HEAD"])
.output()?;
if !born.status.success() {
return Ok(BTreeMap::new());
}
let head = published::at(root, "HEAD")?;
Ok(laws
.filter_map(|law| {
let old = head.law_of(law)?;
(old.name != law.name).then(|| (law.id.clone(), old.name.clone()))
})
.collect())
}
pub(crate) fn sentence_held(
ws: &Workspace,
owner: &ProjectRef,
q: &ProjectRef,
old: &BTreeMap<String, String>,
of: &dyn Fn(&MarkerAddr) -> bool,
) -> Result<BTreeSet<(std::path::PathBuf, usize)>> {
let mut held = span::held_pins(&q.dir, resolve::project_pin_texts(ws, q)?, of)?;
if !old.is_empty() {
let texts = span::PinTexts::with_sentences(
&parse::scan_root(&q.dir)?,
&ws.law_scans(&q.key)?,
&owner.key,
old,
);
held.extend(span::held_pins(&q.dir, texts, of)?);
}
Ok(held)
}
fn refuse_unhashable(root: &Path, addrs: &[String]) -> Result<()> {
let errors = span::unhashable(root, &|p| addrs.contains(&p.display()))?;
if errors.is_empty() {
return Ok(());
}
for err in &errors {
println!(" {err}");
}
bail!(
"{} pin(s) of {} cannot be hashed: write the code each line above names so the grammar parses it, then run `silcrow accept {}` again",
errors.len(),
shown(addrs),
addrs.join(" ")
)
}
fn shown(addrs: &[String]) -> String {
addrs
.iter()
.map(|addr| format!("§ {addr}"))
.collect::<Vec<_>>()
.join(", ")
}
fn repin_qualified(
ws: &Workspace,
project: &ProjectRef,
origin: &str,
id: &str,
letter: Option<&str>,
) -> Result<String> {
let Some(declaring) = ws.get(origin) else {
bail!("`{origin}` names no project. Projects: {}", ws.list());
};
let scans = ws.law_scans(&project.key)?;
let Some(law) = scans.scans[&declaring.key]
.laws
.iter()
.find(|law| law.id == id)
else {
bail!("project `{origin}` declares no § {id}");
};
Ok(match letter {
Some(letter) => {
if !law
.clauses
.iter()
.any(|al| al.letter.as_deref() == Some(letter))
{
bail!("§ {origin}:{id} has no clause ({letter})");
}
format!("{origin}:{id}.{letter}")
}
None => format!("{origin}:{id}"),
})
}
fn is_published(ws: &Workspace, root: &Path, id: &str) -> Result<bool> {
let Some(base) = ws.base_ref("HEAD")? else {
return Ok(false);
};
Ok(published::at(root, &base)?.keys().contains(id))
}
fn drop_alias(text: &str, line: usize, id: &str) -> Result<String> {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let Some(head) = lines.get_mut(line - 1) else {
bail!("head of § {id} is not at line {line}");
};
*head = head.replace(&format!("<a id=\"{id}\"></a>"), "");
let mut out = lines.join("\n");
if text.ends_with('\n') {
out.push('\n');
}
Ok(out)
}
pub fn add_alias(text: &str, line: usize, new_id: &str, old_id: &str) -> Result<String> {
let anchor = format!("<a id=\"{new_id}\">{new_id}</a>");
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let Some(head) = lines.get_mut(line - 1) else {
bail!("head of § {new_id} is not at line {line}");
};
let Some(pos) = head.find(&anchor) else {
bail!("head of § {new_id} carries no anchor to alias");
};
head.insert_str(pos + anchor.len(), &format!("<a id=\"{old_id}\"></a>"));
let mut out = lines.join("\n");
if text.ends_with('\n') {
out.push('\n');
}
Ok(out)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
Write,
DryRun,
Sandbox,
}
fn accept_alias(keeper: &parse::Law, addr: &str, letter: Option<&str>) -> Result<String> {
let current = match letter {
Some(letter) => format!("{}.{letter}", keeper.id),
None => keeper.id.clone(),
};
let struck = match letter {
Some(letter) => {
let Some(clause) = keeper
.clauses
.iter()
.find(|al| al.letter.as_deref() == Some(letter))
else {
bail!(
"§ {addr} names § {}, which has no clause ({letter})",
keeper.id
);
};
keeper.struck || clause.struck
}
None => keeper.struck,
};
if struck || (letter.is_none() && hash::mint_id(&keeper.name) != keeper.id) {
bail!(
"§ {addr} names an alias anchor of § {}, which this accept would remint or remove: run `silcrow accept {current}`",
keeper.id
);
}
Ok(addr.to_string())
}
fn repin(ws: &Workspace, project: &ProjectRef, addr: &str, dry_run: bool) -> Result<()> {
let mode = if dry_run { Mode::DryRun } else { Mode::Write };
repin_in(ws, project, &[addr.to_string()], mode)
}
fn repin_in(ws: &Workspace, project: &ProjectRef, addrs: &[String], mode: Mode) -> Result<()> {
repin_as(ws, project, addrs, mode, &addrs.join(" "))
}
fn repin_as(
ws: &Workspace,
project: &ProjectRef,
addrs: &[String],
mode: Mode,
again: &str,
) -> Result<()> {
let repins = plan_as(ws, project, addrs, mode)?;
let done = format!("✓ Re-pinned {}.", shown(addrs));
write_repins(project, &repins, addrs, mode, again, &done)
}
struct Repins {
plan: write::WritePlan,
named: Vec<String>,
}
fn plan_as(ws: &Workspace, project: &ProjectRef, addrs: &[String], mode: Mode) -> Result<Repins> {
let root = project.dir.as_path();
refuse_unhashable(root, addrs)?;
let texts = resolve::project_pin_texts(ws, project)?;
let laws: BTreeSet<&str> = addrs
.iter()
.map(String::as_str)
.filter(|addr| {
!addr
.rsplit_once(':')
.map_or(*addr, |(_, local)| local)
.contains('.')
})
.collect();
let of = |p: &crate::marker::MarkerAddr| {
let shown = p.display();
addrs.contains(&shown)
|| shown
.rsplit_once('.')
.is_some_and(|(law, _)| laws.contains(law))
};
let plan = span::repin_where(root, &texts, &of)?;
let mut named = Vec::new();
for (rel, next) in &plan.writes {
let text = std::fs::read_to_string(root.join(rel))?;
let moved: BTreeSet<String> = repinned(&text, next)
.into_iter()
.filter(|p| of(p))
.map(|p| MarkerAddr { digest: None, ..p }.display())
.collect();
for pin in moved {
named.push(format!(
" {} {} § {pin}",
repin_word(mode != Mode::Write),
rel.display()
));
}
}
Ok(Repins { plan, named })
}
fn write_repins(
project: &ProjectRef,
repins: &Repins,
addrs: &[String],
mode: Mode,
again: &str,
done: &str,
) -> Result<()> {
for line in &repins.named {
println!("{line}");
}
if repins.plan.writes.is_empty() {
println!("✓ Every pin of {} already matches.", shown(addrs));
return Ok(());
}
write::apply(&repins.plan, &project.dir, mode == Mode::DryRun).with_context(|| {
format!(
"[{}] a write failed: each file written before it holds its new pins, every other file is as it was. Run `silcrow check` for the drift left.",
project.key
)
})?;
match mode {
Mode::DryRun => nothing_written(again),
Mode::Write => println!("{done}"),
Mode::Sandbox => {}
}
Ok(())
}
fn plan_lines(
ws: &Workspace,
project: &ProjectRef,
addrs: &[String],
lines: &BTreeSet<(PathBuf, usize)>,
mode: Mode,
) -> Result<Repins> {
let root = project.dir.as_path();
let texts = resolve::project_pin_texts(ws, project)?;
let of = |p: &MarkerAddr| addrs.contains(&p.display());
let plan = span::repin_at(root, texts, lines, &of)?;
let mut named = Vec::new();
for (rel, next) in &plan.writes {
let text = std::fs::read_to_string(root.join(rel))?;
for (idx, (was, now)) in text.lines().zip(next.lines()).enumerate() {
if was == now {
continue;
}
for pin in crate::marker::markers_in_line(was)
.into_iter()
.filter(|p| of(p))
{
named.push(format!(
" {} {}:{} § {}",
repin_word(mode != Mode::Write),
rel.display(),
idx + 1,
MarkerAddr {
digest: None,
..pin
}
.display()
));
}
}
}
Ok(Repins { plan, named })
}
fn repin_word(dry_run: bool) -> &'static str {
match dry_run {
true => "would REPIN",
false => "REPIN",
}
}
fn nothing_written(addr: &str) {
println!("\nNothing was written: run `silcrow accept {addr} --write` to write it.");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn alias_sits_after_the_anchor() {
let text = "# N\n\n**§ <a id=\"vv137kd0v\">vv137kd0v</a> Sentence.**\n";
let out = add_alias(text, 3, "vv137kd0v", "n0k16nsjq").unwrap();
assert_eq!(
out,
"# N\n\n**§ <a id=\"vv137kd0v\">vv137kd0v</a><a id=\"n0k16nsjq\"></a> Sentence.**\n"
);
assert_eq!(hash::aliases_in(&out), vec!["n0k16nsjq".to_string()]);
}
#[test]
fn a_remint_back_drops_the_alias_of_its_own_id() {
let text = "# N\n\n**§ <a id=\"n0k16nsjq\">n0k16nsjq</a><a id=\"n0k16nsjq\"></a><a id=\"abcdefgh1\"></a> Sentence.**\n";
assert_eq!(
drop_alias(text, 3, "n0k16nsjq").unwrap(),
"# N\n\n**§ <a id=\"n0k16nsjq\">n0k16nsjq</a><a id=\"abcdefgh1\"></a> Sentence.**\n"
);
}
}