silcrow 0.2.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
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};

/// What leaves the tree: a struck law of `project`, named by its id or an alias anchor, or one
/// of its letters.
struct Gone<'a> {
    project: &'a str,
    ids: BTreeSet<String>,
    letter: Option<&'a str>,
}

impl Gone<'_> {
    /// A reference written in project `from`, qualified or not.
    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))
    }
}

/// The 1-based lines to delete in one file. A block also takes the blank line above it, the
/// separator every paragraph of a note carries.
#[derive(Default)]
pub(crate) struct Cut {
    lines: BTreeSet<usize>,
    blocks: BTreeSet<usize>,
    /// Lines that stay with another text: a `§ one` line that keeps the entries of other laws,
    /// or a tombstone.
    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
    }
}

/// Every file to cut, keyed by its project and its path in that project.
type Cuts = BTreeMap<(String, PathBuf), Cut>;

/// `accept` on a struck law or clause: everything that only existed for it leaves the tree.
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(),
    };
    // § vw7bmw3s3.c@k8hym
    let removes = letter.is_none() && !active_at_base(ws, root, law)?;
    // § end vw7bmw3s3.c
    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 {
        // § vw7bmw3s3.a@2q13v
        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() {
        // § vw7bmw3s3.b@bmj7z
        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));
    }
    // § z50y8eyxx.e@je05p
    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],
        };
        // § vw7bmw3s3.d@rwbpz
        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(());
    }
    // § end z50y8eyxx.e
    if removes {
        println!("✓ Removed § {label}.");
    } else {
        println!("✓ Removed the markers of § {label}.{tail}");
    }
    Ok(())
}

/// The published tree holds the law, and not struck: its strike is not published yet.
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))
}

/// Every marker and explicit end of the law in one project, and every adoption of it there.
fn unmark(
    gone: &Gone,
    project: &ProjectRef,
    scan: &Scan,
    cuts: &mut Cuts,
    actions: &mut Vec<String>,
) -> Result<()> {
    // § vw7bmw3s3.a@9j6tw
    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(())
}

/// Every cite and mention of the removed law in one project: a line that holds only references
/// to it goes, and any other one refuses the removal.
fn drop_references(
    gone: &Gone,
    project: &ProjectRef,
    scan: &Scan,
    removed: &Law,
    cuts: &mut Cuts,
    actions: &mut Vec<String>,
    refused: &mut Vec<String>,
) -> Result<()> {
    // § vw7bmw3s3.a@126gv
    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());
        // § vw7bmw3s3.b@kc7q4
        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;
        }
        // § end vw7bmw3s3.b
        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(())
}

/// The law, other than the removed one, whose head or clause holds that line.
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())
}

/// A marker by its file, its address and its rank among the markers of that address in the
/// file, which a removal of other lines keeps.
type Ranked = (PathBuf, String, usize);

/// Every marker of the project a re-pin would change: drifted, or bare.
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()
}

/// Re-pins exactly the markers the removal turned red, and no other line.
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;
                    // § z50y8eyxx.g@8p59c
                    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));
    }
}