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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
//! The changes of a comparison that no marker covers and no pin reads: what a reviewer judges
//! for a rule that lacks a law or a marker.

use anyhow::{bail, Context, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use super::{byte_line, path_of, read_worktree, FileMap, Side};
use crate::parse::Scan;
use crate::span;

/// One line range of a hunk: its first line and how many lines it holds.
type Range = (usize, usize);

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Hunk {
    pub(super) old: Range,
    pub(super) new: Range,
    /// Each removed line `-`, then each added line `+`, as git writes them.
    pub(super) lines: Vec<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct FileHunks {
    /// The path on the compared side, or on the comparison side for a deleted file.
    pub(super) path: String,
    pub(super) old_path: Option<String>,
    pub(super) new_path: Option<String>,
    pub(super) binary: bool,
    pub(super) hunks: Vec<Hunk>,
}

impl FileHunks {
    pub(super) fn added(&self) -> usize {
        self.hunks.iter().map(|h| h.new.1).sum()
    }

    pub(super) fn removed(&self) -> usize {
        self.hunks.iter().map(|h| h.old.1).sum()
    }

    pub(super) fn counts(&self) -> String {
        match self.binary {
            true => "binary".to_string(),
            false => format!("+{} -{}", self.added(), self.removed()),
        }
    }

    /// The file's hunks as a git patch, none for a binary file.
    pub(super) fn patch(&self) -> String {
        if self.hunks.is_empty() {
            return String::new();
        }
        let side = |path: &Option<String>, prefix: &str| {
            path.as_ref()
                .map_or("/dev/null".to_string(), |p| format!("{prefix}{p}"))
        };
        let old = self.old_path.as_deref().unwrap_or(&self.path);
        let new = self.new_path.as_deref().unwrap_or(&self.path);
        let mut out = format!(
            "diff --git a/{old} b/{new}\n--- {}\n+++ {}\n",
            side(&self.old_path, "a/"),
            side(&self.new_path, "b/")
        );
        for hunk in &self.hunks {
            out.push_str(&format!(
                "@@ -{},{} +{},{} @@\n",
                hunk.old.0, hunk.old.1, hunk.new.0, hunk.new.1
            ));
            for line in &hunk.lines {
                out.push_str(line);
                out.push('\n');
            }
        }
        out
    }
}

/// The lines of each file, by its path on the compared side, that a marker covers or a pin
/// reads, on each side.
pub(super) type Lines = BTreeMap<String, BTreeSet<usize>>;

/// Each hunk of the files `keep` holds that changed against `base` and that touches no line of
/// `governed`, file by file. A worktree comparison reads untracked files whole.
pub(super) fn ungoverned(
    root: &Path,
    base: &str,
    worktree: bool,
    keep: impl Fn(&FileHunks) -> bool,
    governed: &[Lines; 2],
) -> Result<Vec<FileHunks>> {
    // § gtp41g8tf@nrcav
    let mut files = git_hunks(root, base)?;
    if worktree {
        for rel in super::git_lines(root, &["ls-files", "--others", "--exclude-standard"])? {
            // § r4dndth75.g@9yb3s
            // Git lists a nested checkout as one entry, and no verb reads behind its `.git`.
            if root.join(&rel).join(".git").exists() {
                continue;
            }
            files.push(untracked(root, &rel));
        }
    }
    let mut out = Vec::new();
    for mut file in files.into_iter().filter(|file| keep(file)) {
        let empty = file.hunks.is_empty();
        drop_governed(&mut file, governed);
        let created_or_gone = file.old_path.is_none() || file.new_path.is_none();
        if !file.hunks.is_empty() || file.binary || (empty && created_or_gone) {
            out.push(file);
        }
    }
    out.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(out)
}

/// Keep of each hunk of `file` only its lines that are not blank and that no governed line of
/// their side holds, each run of them a hunk of its own.
fn drop_governed(file: &mut FileHunks, governed: &[Lines; 2]) {
    // § gtp41g8tf@sgwmp
    let empty = BTreeSet::new();
    let old_lines = governed[0].get(&file.path).unwrap_or(&empty);
    let new_lines = governed[1].get(&file.path).unwrap_or(&empty);
    let mut kept = Vec::new();
    for hunk in &file.hunks {
        let (mut old, mut new) = (hunk.old.0, hunk.new.0);
        // A side with no line names the line before the change, as git writes it.
        if hunk.old.1 == 0 {
            old += 1;
        }
        if hunk.new.1 == 0 {
            new += 1;
        }
        let mut run: Option<Hunk> = None;
        for line in &hunk.lines {
            let removed = line.starts_with('-');
            // A blank line carries no rule: it neither stands alone nor joins a run.
            let governs = line[1..].trim().is_empty()
                || match removed {
                    true => old_lines.contains(&old),
                    false => new_lines.contains(&new),
                };
            if governs {
                kept.extend(run.take());
            } else {
                let at = run.get_or_insert_with(|| Hunk {
                    old: (old - 1, 0),
                    new: (new - 1, 0),
                    lines: Vec::new(),
                });
                let side = if removed { &mut at.old } else { &mut at.new };
                if side.1 == 0 {
                    side.0 = if removed { old } else { new };
                }
                side.1 += 1;
                at.lines.push(line.clone());
            }
            if removed {
                old += 1;
            } else {
                new += 1;
            }
        }
        kept.extend(run);
    }
    file.hunks = kept;
}

fn untracked(root: &Path, rel: &Path) -> FileHunks {
    let path = path_of(rel);
    let mut file = FileHunks {
        path: path.clone(),
        old_path: None,
        new_path: Some(path),
        ..FileHunks::default()
    };
    match read_worktree(root, rel) {
        None => file.binary = true,
        Some(text) if text.is_empty() => {}
        Some(text) => {
            let lines: Vec<String> = text.lines().map(|line| format!("+{line}")).collect();
            file.hunks.push(Hunk {
                old: (0, 0),
                new: (1, lines.len()),
                lines,
            });
        }
    }
    file
}

/// The hunks git reads between `base` and the compared side, with no context line.
fn git_hunks(root: &Path, base: &str) -> Result<Vec<FileHunks>> {
    let args = [
        "-c",
        "core.quotepath=off",
        "diff",
        "-U0",
        "--no-color",
        "--no-ext-diff",
        "--no-textconv",
        "--relative",
        "--find-renames",
        "--diff-filter=ACDMR",
        base,
    ];
    let out = crate::workspace::git(root)
        .args(args)
        .output()
        .with_context(|| format!("git {}", args.join(" ")))?;
    if !out.status.success() {
        bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr)
        );
    }
    parse_hunks(&String::from_utf8_lossy(&out.stdout))
}

/// The files and hunks of a `git diff -U0` patch.
fn parse_hunks(patch: &str) -> Result<Vec<FileHunks>> {
    let unquote = |path: &str| path.trim_matches('"').to_string();
    let named = |line: &str, prefix: &str| match line {
        "/dev/null" => None,
        path => Some(unquote(path).trim_start_matches(prefix).to_string()),
    };
    let mut out: Vec<FileHunks> = Vec::new();
    let mut in_hunk = false;
    for line in patch.lines() {
        if let Some(rest) = line.strip_prefix("diff --git ") {
            let (old, new) = rest
                .split_once(" b/")
                .map(|(old, new)| {
                    (
                        unquote(old).trim_start_matches("a/").to_string(),
                        unquote(new),
                    )
                })
                .unwrap_or_else(|| (rest.to_string(), rest.to_string()));
            out.push(FileHunks {
                path: new.clone(),
                old_path: Some(old),
                new_path: Some(new),
                ..FileHunks::default()
            });
            in_hunk = false;
            continue;
        }
        let Some(file) = out.last_mut() else {
            continue;
        };
        if let Some(range) = line.strip_prefix("@@ ") {
            file.hunks.push(
                parse_range(range).with_context(|| format!("git diff: malformed hunk {line:?}"))?,
            );
            in_hunk = true;
            continue;
        }
        if in_hunk {
            if line.starts_with('+') || line.starts_with('-') {
                if let Some(hunk) = file.hunks.last_mut() {
                    hunk.lines.push(line.to_string());
                }
            }
            continue;
        }
        if let Some(path) = line.strip_prefix("--- ") {
            file.old_path = named(path, "a/");
        } else if let Some(path) = line.strip_prefix("+++ ") {
            file.new_path = named(path, "b/");
        } else if let Some(path) = line.strip_prefix("rename from ") {
            file.old_path = Some(unquote(path));
        } else if let Some(path) = line.strip_prefix("rename to ") {
            file.new_path = Some(unquote(path));
        } else if line.starts_with("new file mode") {
            file.old_path = None;
        } else if line.starts_with("deleted file mode") {
            file.new_path = None;
        } else if line.starts_with("Binary files ") {
            file.binary = true;
        }
        if let Some(path) = file.new_path.as_ref().or(file.old_path.as_ref()) {
            file.path = path.clone();
        }
    }
    Ok(out)
}

/// `-a[,b] +c[,d] @@...` as its two ranges, a missing count reading 1.
fn parse_range(range: &str) -> Option<Hunk> {
    let mut fields = range.split_whitespace();
    let side = |field: Option<&str>, sign: char| -> Option<Range> {
        let field = field?.strip_prefix(sign)?;
        let (start, len) = field.split_once(',').unwrap_or((field, "1"));
        Some((start.parse().ok()?, len.parse().ok()?))
    };
    let old = side(fields.next(), '-')?;
    let new = side(fields.next(), '+')?;
    Some(Hunk {
        old,
        new,
        lines: Vec::new(),
    })
}

/// The lines of each decision note a law, a clause or a cite of a side stands on, a note
/// renamed since keyed by its path on the compared side.
pub(super) fn note_lines(scan: &Scan, renamed: &BTreeMap<String, String>) -> Lines {
    // § gtp41g8tf.a@p90kv
    let key = |path: &Path| {
        let path = path_of(path);
        renamed.get(&path).cloned().unwrap_or(path)
    };
    let mut out = Lines::new();
    for law in &scan.laws {
        let end = law
            .clauses
            .iter()
            .map(|clause| clause.end)
            .chain([law.end])
            .max()
            .unwrap_or(law.loc.line);
        out.entry(key(&law.loc.path))
            .or_default()
            .extend(law.loc.line..=end.max(law.loc.line));
    }
    for pointer in &scan.pointers {
        out.entry(key(&pointer.loc.path))
            .or_default()
            .insert(pointer.loc.line);
    }
    out
}

/// The lines of each file of `files` that a marker covers or a pin reads, on each side: every
/// marker line and span, the code before each span that its pin reads, and each body that a
/// pin of the project follows, through `sides` when the diff weighed its pins.
pub(super) fn governed(
    files: &FileMap,
    sides: Option<&[Side; 2]>,
    notes: [Lines; 2],
    renamed: &BTreeMap<String, String>,
) -> [Lines; 2] {
    // § gtp41g8tf.a@jqc92
    let mut out = notes;
    for (path, texts) in files {
        for (side, text) in [&texts.0, &texts.1].into_iter().enumerate() {
            let Some(text) = text else {
                continue;
            };
            let lines = out[side].entry(path.clone()).or_default();
            let rel = PathBuf::from(path);
            for row in span::marker_rows(&rel, text, None) {
                lines.insert(row.idx + 1);
            }
            let file = span::CodeFile::new(rel, text.clone());
            for marker in file.span_markers() {
                lines.extend(byte_lines(text, marker.start, marker.end));
                for (from, to, _) in file.prefix(marker.start, marker.end) {
                    lines.extend(byte_lines(text, from, to));
                }
                for (from, to, punch) in file.above(marker.start, marker.end) {
                    let mut at = from;
                    for (hole, past) in punch.into_iter().chain([(to, to)]) {
                        let kept = &text[at..hole.max(at)];
                        let lead = kept.len() - kept.trim_start().len();
                        if !kept.trim().is_empty() {
                            lines.extend(byte_lines(text, at + lead, at + kept.trim_end().len()));
                        }
                        at = at.max(past);
                    }
                }
            }
        }
    }
    let Some(sides) = sides else {
        return out;
    };
    for (at, side) in sides.iter().enumerate() {
        for (rel, file) in &side.files {
            let Some(markers) = side.markers.get(rel) else {
                continue;
            };
            for marker in markers {
                let punch = span::punch_of(markers, marker.line);
                let prefix = file.prefix(marker.start, marker.end);
                let callees =
                    side.follow
                        .followed_callees(rel, marker.start, marker.end, &punch, &prefix);
                for callee in callees {
                    let path = path_of(&callee.path);
                    let path = renamed.get(&path).cloned().unwrap_or(path);
                    let Some(text) = side.files.get(&callee.path).map(|f| f.text.as_str()) else {
                        continue;
                    };
                    if files.contains_key(&path) {
                        out[at].entry(path).or_default().extend(byte_lines(
                            text,
                            callee.start,
                            callee.end,
                        ));
                    }
                }
            }
        }
    }
    out
}

/// The 1-based lines the bytes `start..end` of `text` stand on.
fn byte_lines(text: &str, start: usize, end: usize) -> std::ops::RangeInclusive<usize> {
    byte_line(text, start)..=byte_line(text, end.saturating_sub(1).max(start))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_patch_reads_as_its_files_and_hunks() {
        let patch = "diff --git a/src/a.ts b/src/a.ts\nindex 1..2 100644\n--- a/src/a.ts\n+++ b/src/a.ts\n@@ -2 +2 @@ fn\n-  return a;\n+  return b;\n@@ -9,0 +10,2 @@\n+--- not a header\n+x\ndiff --git a/old.md b/new.md\nsimilarity index 100%\nrename from old.md\nrename to new.md\ndiff --git a/gone.rs b/gone.rs\ndeleted file mode 100644\n--- a/gone.rs\n+++ /dev/null\n@@ -1,2 +0,0 @@\n-a\n-b\ndiff --git a/i.png b/i.png\nBinary files a/i.png and b/i.png differ\n";
        let files = parse_hunks(patch).unwrap();
        assert_eq!(files.len(), 4, "{files:?}");
        assert_eq!(files[0].hunks.len(), 2);
        assert_eq!(files[0].hunks[0].old, (2, 1));
        assert_eq!(files[0].hunks[1].new, (10, 2));
        assert_eq!(files[0].hunks[1].lines, ["+--- not a header", "+x"]);
        assert_eq!(files[0].counts(), "+3 -1");
        assert_eq!(
            (files[1].old_path.as_deref(), files[1].path.as_str()),
            (Some("old.md"), "new.md")
        );
        assert_eq!(
            (files[2].new_path.as_deref(), files[2].path.as_str()),
            (None, "gone.rs")
        );
        assert!(files[2]
            .patch()
            .contains("+++ /dev/null\n@@ -1,2 +0,0 @@\n-a\n-b\n"));
        assert!(files[3].binary);
        assert_eq!(files[3].counts(), "binary");
    }

    #[test]
    fn a_blank_changed_line_is_never_under_no_law() {
        let mut file = FileHunks {
            path: "src/a.rs".into(),
            old_path: Some("src/a.rs".into()),
            new_path: Some("src/a.rs".into()),
            binary: false,
            hunks: vec![
                Hunk {
                    old: (3, 1),
                    new: (3, 2),
                    lines: vec!["-".into(), "+".into(), "+   \t".into()],
                },
                Hunk {
                    old: (9, 0),
                    new: (10, 3),
                    lines: vec!["+x".into(), "+  ".into(), "+y".into()],
                },
            ],
        };
        drop_governed(&mut file, &[Lines::new(), Lines::new()]);
        let lines: Vec<&[String]> = file.hunks.iter().map(|h| h.lines.as_slice()).collect();
        assert_eq!(lines, [&["+x".to_string()][..], &["+y".to_string()][..]]);
    }

    #[test]
    fn a_line_a_governed_line_of_its_side_holds_leaves_its_hunk() {
        let file = FileHunks {
            path: "src/a.rs".into(),
            old_path: Some("src/a.rs".into()),
            new_path: Some("src/a.rs".into()),
            binary: false,
            hunks: vec![
                Hunk {
                    old: (2, 1),
                    new: (2, 1),
                    lines: vec!["-a".into(), "+b".into()],
                },
                Hunk {
                    old: (5, 0),
                    new: (6, 1),
                    lines: vec!["+c".into()],
                },
                Hunk {
                    old: (9, 1),
                    new: (9, 0),
                    lines: vec!["-d".into()],
                },
            ],
        };
        let lines =
            |at: &[usize]| Lines::from([("src/a.rs".to_string(), at.iter().copied().collect())]);
        let keep = |governed: [Lines; 2]| {
            let mut kept = file.clone();
            drop_governed(&mut kept, &governed);
            kept.hunks
                .iter()
                .map(|h| h.lines[0].clone())
                .collect::<Vec<_>>()
        };
        assert_eq!(keep([lines(&[9]), lines(&[6])]), ["-a"]);
        assert_eq!(keep([lines(&[2]), lines(&[])]), ["+b", "+c", "-d"]);
        assert_eq!(keep([lines(&[5]), lines(&[5, 7])]), ["-a", "+c", "-d"]);
        let mut mixed = FileHunks {
            hunks: vec![Hunk {
                old: (4, 0),
                new: (5, 3),
                lines: vec!["+x".into(), "+y".into(), "+z".into()],
            }],
            ..file.clone()
        };
        drop_governed(&mut mixed, &[Lines::new(), lines(&[6])]);
        let runs: Vec<(Range, Range, usize)> = mixed
            .hunks
            .iter()
            .map(|h| (h.old, h.new, h.lines.len()))
            .collect();
        assert_eq!(runs, [((4, 0), (5, 1), 1), ((4, 0), (7, 1), 1)]);
    }
}