silcrow 0.1.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use anyhow::{bail, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

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;

/// Accept a clause as it now stands. For a law whose sentence moved, remint the id,
/// rewrite every pointer, and keep the published id as an alias anchor in the head.
/// Then re-pin every marker of the clause.
pub fn run(ws: &Workspace, project: &ProjectRef, addr: &str, dry_run: bool) -> Result<()> {
    // § xnsbksxv6.b@143jw
    let root = project.dir.as_path();
    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, dry_run);
    }
    let scan = parse::scan_root(root)?;
    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(ws, project, keeper, local, letter, dry_run);
        }
        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 remove::run(ws, project, &scan, law, Some(letter), dry_run);
        }
        return repin(ws, project, local, dry_run);
    }
    // § vw7bmw3s3.e@xxnw6
    if law.struck {
        return remove::run(ws, project, &scan, law, None, dry_run);
    }
    // § end vw7bmw3s3.e
    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);
        }
        // Two steps, the second reading what the first wrote: a dry run runs both on a copy.
        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, mode);
        if let Some(sandbox) = &sandbox {
            sandbox.show(ws)?;
            nothing_written(id);
        }
        return result;
    }
    // § cmx8g7zp2.a@zexbv
    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
        );
    }
    // § end cmx8g7zp2.a
    // § cmx8g7zp2.d@1gnz2
    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
        );
    }
    // § end cmx8g7zp2.d
    if !law.aliases.contains(&new_id) {
        // § cmx8g7zp2.b@hde40
        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)?;
    let mut remap = BTreeMap::new();
    remap.insert(id.to_string(), new_id.clone());
    let mut own = resolve::plan_remap(root, remap.clone())?;
    // § z75jh6fxe@c8g6g
    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));
    }
    // § end z75jh6fxe
    if law.aliases.contains(&new_id) {
        // § b73qzqyt9.d@27db9
        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)?;
    }
    // A cite left in another law's carrying sentence resolves through the alias anchor.
    let alias = is_published(ws, root, id)? || own.kept.contains(id);
    if alias {
        // § b73qzqyt9@kjdtr
        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)?;
    }
    // A clause pin of the law hashes its address: the ones that held before the remint
    // re-pin with it, since nothing they bind but the id moved.
    // § xnsbksxv6.e@t8rtp
    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());
    }
    // § z50y8eyxx.e@vygsf
    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)?, &new_id, mode);
    if let Some(sandbox) = &sandbox {
        sandbox.show(ws)?;
        nothing_written(id);
    }
    // § end z50y8eyxx.e
    // § end xnsbksxv6.e
    // § xnsbksxv6.f@39pjs
    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,
    }
    // § end xnsbksxv6.f
}

/// The markers of `next` whose pin differs from the one on the same line of `old`, as a re-pin
/// writes them in place.
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()
}

/// Every address, `<projectpath>:<id>[.<letter>]`, of a law other than `id` whose pinned text
/// names `id`: the remint rewrites that cite and nothing else they hash.
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)
}

/// The carrying sentence `HEAD` holds for each of `laws` whose sentence the tree changed, by
/// id: what its clause pins hashed until the sentence moved.
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())
}

/// The pins of project `q` that `of` accepts and that hold, under the texts of the tree or
/// under those with each law of `owner` that `old` keys read with the sentence it maps to:
/// nothing they bind but that carrying sentence, or the id it mints, moved.
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)>> {
    // § xnsbksxv6.e@yfzrv
    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)
}

/// Fails, naming each parse error, when a pin of `addr` cannot be hashed: a re-pin would
/// otherwise leave its old digest and report it as matching.
fn refuse_unhashable(root: &Path, addr: &str) -> Result<()> {
    // § d1bc2zca5.c@2r1nc
    let errors = span::unhashable(root, &|p| p.display() == addr)?;
    if errors.is_empty() {
        return Ok(());
    }
    for err in &errors {
        println!("  {err}");
    }
    bail!(
        "{} pin(s) of § {addr} cannot be hashed: write the code each line above names so the grammar parses it, then run `silcrow accept {addr}` again",
        errors.len()
    )
}

/// A marker of another project's clause is re-pinned here; the law itself is that project's.
fn repin_qualified(
    ws: &Workspace,
    project: &ProjectRef,
    origin: &str,
    id: &str,
    letter: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    // § xnsbksxv6.d@axfen
    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}");
    };
    let addr = 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}"),
    };
    repin(ws, project, &addr, dry_run)
}

/// An id the base does not hold is provisional, so its remint keeps no alias anchor.
fn is_published(ws: &Workspace, root: &Path, id: &str) -> Result<bool> {
    // § b73qzqyt9.a@fet4y
    let Some(base) = ws.base_ref("HEAD")? else {
        return Ok(false);
    };
    Ok(published::at(root, &base)?.keys().contains(id))
}

/// The head at `line` without the alias anchor of `id`, which it now carries as its 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,
    /// A step of a dry run inside a `write::Sandbox`: it writes the copy, and the run shows
    /// the result once at its end.
    Sandbox,
}

/// Only the current project's markers: every other project re-pins its own.
/// An address spelled with an alias anchor of `keeper` resolves to it: its markers are re-pinned
/// under the spelling they carry, which `fix` rewrites, never `accept`. A remint or a removal
/// is the current id's to take.
fn accept_alias(
    ws: &Workspace,
    project: &ProjectRef,
    keeper: &parse::Law,
    addr: &str,
    letter: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    // § b73qzqyt9.b@8amnf
    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
        );
    }
    repin(ws, project, addr, dry_run)
}

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, mode)
}

fn repin_in(ws: &Workspace, project: &ProjectRef, addr: &str, mode: Mode) -> Result<()> {
    // § xnsbksxv6.d@5jbad
    let root = project.dir.as_path();
    refuse_unhashable(root, addr)?;
    let texts = resolve::project_pin_texts(ws, project)?;
    // A law takes every pin of it, its clause markers included.
    let local = addr.rsplit_once(':').map_or(addr, |(_, local)| local);
    let law_grain = !local.contains('.');
    let of = |p: &crate::marker::MarkerAddr| {
        let shown = p.display();
        shown == addr || (law_grain && shown.rsplit_once('.').map(|(law, _)| law) == Some(addr))
    };
    let plan = span::repin_where(root, &texts, &of)?;
    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 {
            println!(
                "  {} {} § {pin}",
                repin_word(mode != Mode::Write),
                rel.display()
            );
        }
    }
    // § end xnsbksxv6.d
    // § xnsbksxv6.f@tjn1m
    if plan.writes.is_empty() {
        println!("✓ Every pin of § {addr} already matches.");
        return Ok(());
    }
    write::apply(&plan, root, mode == Mode::DryRun)?;
    match mode {
        Mode::DryRun => nothing_written(addr),
        Mode::Write => println!("✓ Re-pinned § {addr}."),
        Mode::Sandbox => {}
    }
    Ok(())
}

/// The word of a re-pin line: what a dry run would do, or what the write did.
fn repin_word(dry_run: bool) -> &'static str {
    // § z50y8eyxx.g@rxgg9
    match dry_run {
        true => "would REPIN",
        false => "REPIN",
    }
}

/// The last line of a dry run of `accept`.
fn nothing_written(addr: &str) {
    // § z50y8eyxx.g@dr70h
    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"
        );
    }
}