use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use crate::workspace::{in_workspace, ProjectRef, Workspace};
use crate::write::{self, WritePlan};
use crate::{follow, harness, hook, marker, parse, walk};
#[derive(Default)]
struct Plan {
texts: BTreeMap<PathBuf, String>,
removes: BTreeSet<PathBuf>,
prune: Vec<PathBuf>,
}
impl Plan {
fn current(&self, root: &Path, rel: &Path) -> Result<String> {
match self.texts.get(rel) {
Some(text) => Ok(text.clone()),
None => read(&root.join(rel)),
}
}
fn set(&mut self, rel: PathBuf, original: &str, next: String) {
if next != original {
self.texts.insert(rel, next);
}
}
fn remove(&mut self, rel: PathBuf) {
self.texts.remove(&rel);
self.removes.insert(rel);
}
}
pub fn run(ws: &Workspace, projects: &[&ProjectRef], dry_run: bool) -> Result<()> {
refuse_dangling(ws, projects)?;
let mut plan = Plan::default();
for project in projects {
plan_project(ws, project, &mut plan)?;
}
if ws.local().iter().all(|project| projects.contains(project)) {
plan_workspace(&ws.root, &mut plan)?;
}
if plan.texts.is_empty() && plan.removes.is_empty() {
println!("✓ Nothing to eject.");
return Ok(());
}
for rel in plan.texts.keys() {
println!(" EJECT {}", rel.display());
}
for rel in &plan.removes {
println!(" DELETE {}", rel.display());
}
let writes = WritePlan {
writes: plan.texts.into_iter().collect(),
};
write::apply(&writes, &ws.root, dry_run)?;
let removes: Vec<PathBuf> = plan.removes.into_iter().collect();
write::remove(&removes, &ws.root, dry_run)?;
if dry_run {
println!("\nRun with --write to apply.");
return Ok(());
}
for rel in &plan.prune {
prune_empty(&ws.root, rel)?;
}
println!("\n✓ Silcrow ejected.");
Ok(())
}
fn refuse_dangling(ws: &Workspace, projects: &[&ProjectRef]) -> Result<()> {
let ejected: BTreeSet<&str> = projects
.iter()
.map(|project| project.key.as_str())
.collect();
let mut refs = Vec::new();
for project in ws.local() {
if ejected.contains(project.key.as_str()) {
continue;
}
let scan = parse::scan_root(&project.dir)?;
let named = scan
.pointers
.iter()
.filter_map(|p| p.project.as_deref().map(|key| (key, &p.name, &p.loc)))
.chain(
scan.adoptions
.iter()
.map(|a| (a.project.as_str(), &a.id, &a.loc)),
);
for (key, id, loc) in named {
if ejected.contains(key) {
refs.push(format!(
"[{}] {}:{}: § {key}:{id}",
project.key,
loc.path.display(),
loc.line
));
}
}
}
if !refs.is_empty() {
bail!(
"eject would leave references into an ejected project. Remove them, or eject that project too:\n {}",
refs.join("\n ")
);
}
Ok(())
}
fn plan_project(ws: &Workspace, project: &ProjectRef, plan: &mut Plan) -> Result<()> {
for path in walk::decision_files(&project.dir)? {
let text = read(&path)?;
let rel = PathBuf::from(parse::display_path(&path, &project.dir));
let next = demark_note(&rel, &text);
plan.set(in_workspace(&project.key, &rel), &text, next);
}
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 = read(&path)?;
let rel = PathBuf::from(parse::display_path(&path, &project.dir));
plan.set(
in_workspace(&project.key, &rel),
&text,
strip_marks(&rel, &text),
);
}
plan_agents(ws, project, plan)
}
fn plan_agents(ws: &Workspace, project: &ProjectRef, plan: &mut Plan) -> Result<()> {
let rel = in_workspace(&project.key, Path::new("AGENTS.md"));
let text = plan.current(&ws.root, &rel)?;
let next = harness::strip_block(&text)
.with_context(|| format!("{} carries no Silcrow block", rel.display()))?;
if next.trim().is_empty() {
plan.remove(rel);
} else {
plan.texts.insert(rel, next);
}
Ok(())
}
fn plan_workspace(root: &Path, plan: &mut Plan) -> Result<()> {
for path in harness::skill_copies(root)? {
let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
plan.prune.push(rel.clone());
plan.remove(rel);
}
for path in hook::installed(root)? {
plan.remove(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
}
Ok(())
}
fn prune_empty(root: &Path, rel: &Path) -> Result<()> {
for dir in rel.ancestors().skip(1) {
if dir.as_os_str().is_empty() {
break;
}
let path = root.join(dir);
if std::fs::read_dir(&path)?.next().is_some() {
break;
}
std::fs::remove_dir(&path)?;
}
Ok(())
}
fn strip_marks(rel: &Path, text: &str) -> String {
let unmarked = marker::unmarked_lines(marker::Dialect::of(rel), text);
let literal = crate::span::lines_opening_in(text, &crate::span::literal_ranges(rel, text));
text.split_inclusive('\n')
.enumerate()
.filter(|&(idx, line)| {
unmarked.get(idx).copied().unwrap_or(false)
|| literal.get(idx).copied().unwrap_or(false)
|| !is_mark(line.trim_end_matches(['\n', '\r']))
})
.map(|(_, line)| line)
.collect()
}
fn is_mark(line: &str) -> bool {
marker::is_pointer_line(line)
|| follow::parse_decl_mark(line).is_some()
|| follow::parse_call_mark(line).is_some()
}
fn demark_note(rel: &Path, text: &str) -> String {
let scan = parse::scan_text(rel, text);
let mut cut = Cut::default();
let mut heads = BTreeSet::new();
for law in &scan.laws {
if law.struck {
cut.lines(law.loc.line, law.end);
} else {
heads.insert(law.loc.line);
}
for al in law.clauses.iter().filter(|al| law.struck || al.struck) {
cut.lines(al.loc.line, al.end);
}
}
for adoption in &scan.adoptions {
cut.lines(adoption.loc.line, adoption.loc.line);
}
let fence = parse::fenced(text);
let mut out: Vec<String> = Vec::new();
for (idx, line) in text.lines().enumerate() {
let n = idx + 1;
if cut.lines.contains(&n) {
if cut.starts.contains(&n) {
pop_blank(&mut out);
}
continue;
}
if fence[idx] {
out.push(line.to_string());
continue;
}
let head = if heads.contains(&n) {
parse::demark_head(line)
} else {
line.to_string()
};
let next = parse::uncite(&head);
if next == head {
out.push(head);
} else if next.trim().is_empty() {
pop_blank(&mut out);
} else {
out.push(next.trim_end().to_string());
}
}
let mut joined = out.join("\n");
if text.ends_with('\n') && !joined.is_empty() {
joined.push('\n');
}
joined
}
#[derive(Default)]
struct Cut {
lines: BTreeSet<usize>,
starts: BTreeSet<usize>,
}
impl Cut {
fn lines(&mut self, start: usize, end: usize) {
self.starts.insert(start);
self.lines.extend(start..=end);
}
}
fn pop_blank(out: &mut Vec<String>) {
if out.last().is_some_and(|line| line.trim().is_empty()) {
out.pop();
}
}
fn read(path: &Path) -> Result<String> {
std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strips_every_mark_line_and_nothing_else() {
let text = "fn a() {\n // § abcdefgh1.a@k3n7q\n # § packages/billing:abcdefgh2\n let x = 1; // § abcdefgh1\n // § end abcdefgh1.a\n // silcrow:skip\n -- silcrow:technical\n}\n<!-- § abcdefgh1 -->\n<!-- § end abcdefgh1 -->\n";
assert_eq!(
strip_marks(Path::new("a.txt"), text),
"fn a() {\n let x = 1; // § abcdefgh1\n}\n"
);
}
#[test]
fn keeps_a_mark_line_inside_a_string() {
let text = "fn a() {\n // § abcdefgh1.a@k3n7q\n let s = r\"\n// § abcdefgh1.a@k3n7q\n// silcrow:skip\n\";\n}\n";
assert_eq!(
strip_marks(Path::new("src/a.rs"), text),
"fn a() {\n let s = r\"\n// § abcdefgh1.a@k3n7q\n// silcrow:skip\n\";\n}\n"
);
let doc = "# § abcdefgh1.a\n\n<!-- § abcdefgh1.a@k3n7q -->\nProse.\n";
assert_eq!(
strip_marks(Path::new("docs/guide.md"), doc),
"# § abcdefgh1.a\n\nProse.\n"
);
}
#[test]
fn demarks_a_note() {
let text = "# N\n\nWhy, see [abcdefgh3.a](o.md#abcdefgh3) and `[x](o.md#abcdefgh3)`.\n\n**§ <a id=\"abcdefgh1\">abcdefgh1</a><a id=\"abcdefgh2\"></a> Live law.**\n\n| A | B |\n| - | - |\n\n- (a) Kept.\n\n- (b) ~~Struck.~~\n\n ```text\n attached\n ```\n\n- (c) **Retired.**\n\n- (d) Kept too.\n\nContext stays.\n\n**§ abcdefgh4 ~~Struck law.~~**\n\n- (a) Its letter.\n\n**§ packages/billing:abcdefgh5**\n\nEnd.\n";
assert_eq!(
demark_note(Path::new("docs/decisions/n.md"), text),
"# N\n\nWhy, see abcdefgh3.a and `[x](o.md#abcdefgh3)`.\n\n**Live law.**\n\n| A | B |\n| - | - |\n\n- (a) Kept.\n\n- (d) Kept too.\n\nContext stays.\n\nEnd.\n"
);
}
#[test]
fn strips_the_block_and_its_separator() {
let text = "<silcrow notes=\"docs/decisions/**/*.md\">\nx\n</silcrow>\n\n# Mine\n";
assert_eq!(harness::strip_block(text).as_deref(), Some("# Mine\n"));
assert_eq!(
harness::strip_block("<silcrow notes=\"docs/decisions/**/*.md\">\n</silcrow>\n")
.as_deref(),
Some("")
);
}
}