greengate-runtime 6.3.1

The amont hook logic: registry, dispatchers, checks and the trust model
Documentation
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! `amont changelog new|collect|check` — release notes as one file per PR.
//!
//! A pull request that edits `CHANGELOG.md` under `## Unreleased` conflicts
//! with every sibling and every release that does the same (relais drive-only
//! t16: 24 of 26 conflicts in one drive). A fragment is a NEW file under
//! `changes/`, which never conflicts; `collect` folds the fragments into the
//! `## v<version>` section when a release is cut, and `check` refuses the
//! direct edit that brings the conflict back.
//!
//! The text handling is pure functions over `&str`, tested below. Git and the
//! file system are touched only in the three `run_*` functions.

use crate::names::BIN;
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};

const DIR: &str = "changes";
const FILE: &str = "CHANGELOG.md";
const PLACEHOLDER: &str = "<!-- Release note for this change: one or two sentences on what an upgrader gets. Replace this line. -->\n";

/// Print to stdout and ignore a closed pipe: `println!` would panic on EPIPE,
/// and `collect` must never be interrupted between its writes and its
/// deletes by a reader that hung up.
fn out(line: &str) {
    let mut handle = std::io::stdout().lock();
    if let Err(e) = writeln!(handle, "{line}") {
        if e.kind() != std::io::ErrorKind::BrokenPipe {
            eprintln!("{BIN}: changelog: cannot write to stdout: {e}");
        }
    }
}

/// Text with every `<!-- … -->` span removed. An unterminated comment removes
/// the rest, which is what a markdown renderer shows too.
fn strip_comments(text: &str) -> String {
    let mut res = String::new();
    let mut rest = text;
    while let Some(i) = rest.find("<!--") {
        res.push_str(&rest[..i]);
        match rest[i..].find("-->") {
            Some(j) => rest = &rest[i + j + 3..],
            None => return res,
        }
    }
    res.push_str(rest);
    res
}

/// A fragment with no words once comments are gone, e.g. an untouched
/// placeholder.
fn is_empty_fragment(text: &str) -> bool {
    strip_comments(text).trim().is_empty()
}

/// A character a slug may hold.
fn is_slug_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')
}

/// A markdown code-fence line, which opens or closes a fence.
fn is_fence(line: &str) -> bool {
    let opener = line.trim_start();
    opener.starts_with("```") || opener.starts_with("~~~")
}

fn valid_slug(slug: &str) -> bool {
    slug.chars()
        .next()
        .is_some_and(|c| c.is_ascii_alphanumeric())
        && slug.chars().all(is_slug_char)
        && !slug.eq_ignore_ascii_case("readme")
}

/// A branch name as a slug: characters outside `[A-Za-z0-9._-]` become `-`,
/// leading `-` and `.` are dropped.
fn slugify(branch: &str) -> String {
    let mapped: String = branch
        .chars()
        .map(|c| if is_slug_char(c) { c } else { '-' })
        .collect();
    mapped.trim_start_matches(['-', '.']).to_string()
}

/// `1.2.3`, `v1.2.3`, `1.2.3-rc.1` → the version without the `v`.
fn parse_version(text: &str) -> Option<String> {
    let unprefixed = text.strip_prefix('v').unwrap_or(text);
    let (core, pre) = match unprefixed.split_once('-') {
        Some((core, pre)) => (core, Some(pre)),
        None => (unprefixed, None),
    };
    let nums: Vec<&str> = core.split('.').collect();
    let numeric = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
    if nums.len() != 3 || !nums.iter().all(|p| numeric(p)) {
        return None;
    }
    if let Some(pre_release) = pre {
        if pre_release.is_empty()
            || !pre_release
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
        {
            return None;
        }
    }
    Some(unprefixed.to_string())
}

/// Byte ranges of the section under `heading`: `(body_start, body_end)`.
/// `body_start` is just after the heading line's newline (or the text's end);
/// the section ends at the next `## ` line outside a code fence, or at EOF.
/// Shared by `collect` and `check`, so the two cannot disagree.
fn section_of(text: &str, heading: &str) -> Option<(usize, usize)> {
    let mut fence = false;
    let mut pos = 0;
    let mut body_start = None;
    for line in text.split_inclusive('\n') {
        let end = pos + line.len();
        let trimmed = line.trim_end();
        if is_fence(trimmed) {
            fence = !fence;
        } else if !fence {
            match body_start {
                None if trimmed == heading => body_start = Some(end),
                Some(start) if trimmed.starts_with("## ") => return Some((start, pos)),
                _ => {}
            }
        }
        pos = end;
    }
    body_start.map(|start| (start, text.len()))
}

fn unreleased_section(text: &str) -> Option<(usize, usize)> {
    section_of(text, "## Unreleased")
}

/// Is there already a `## v<version>` heading (outside a fence)?
fn has_version_heading(text: &str, version: &str) -> bool {
    let want = format!("## v{version}");
    let mut fence = false;
    for line in text.lines() {
        let trimmed = line.trim_end();
        if is_fence(trimmed) {
            fence = !fence;
        } else if !fence && trimmed == want {
            return true;
        }
    }
    false
}

/// The `## Unreleased` body, trimmed and with `\n` endings.
fn unreleased_body(text: &str) -> Option<String> {
    let (body_start, body_end) = unreleased_section(text)?;
    Some(
        text[body_start..body_end]
            .replace("\r\n", "\n")
            .trim()
            .to_string(),
    )
}

/// `CHANGELOG.md` after folding `fragments` (already trimmed, in order) into a
/// new `## v<version>` section right below `## Unreleased`. Text that was under
/// Unreleased goes first (a repository mid-transition loses nothing).
fn fold(changelog: &str, version: &str, fragments: &[String]) -> Result<String, String> {
    let crlf = changelog.contains("\r\n");
    let text = changelog.replace("\r\n", "\n");
    if has_version_heading(&text, version) {
        return Err(format!("{FILE} already has a `## v{version}` section"));
    }
    let Some((head, end)) = unreleased_section(&text) else {
        return Err(format!("{FILE} has no `## Unreleased` heading"));
    };
    let mut parts: Vec<String> = Vec::new();
    let old = text[head..end].trim();
    if !old.is_empty() {
        parts.push(old.to_string());
    }
    parts.extend(fragments.iter().cloned());
    let mut res = text[..head].to_string();
    if !res.ends_with('\n') {
        res.push('\n');
    }
    res.push_str(&format!("\n## v{version}\n\n{}\n", parts.join("\n\n")));
    let rest = &text[end..];
    if !rest.is_empty() {
        res.push('\n');
        res.push_str(rest);
    }
    Ok(if crlf { res.replace('\n', "\r\n") } else { res })
}

/// Fragment names (`x.md`) in a git-log stream, earliest first. The stream is
/// `git log --first-parent -m --diff-filter=A --name-only -z --format= --reverse`:
/// NUL-separated paths. A path added again after a release was collected
/// (a reused slug) ranks by its LAST sighting, so it sorts with its new merge.
fn order_from_log(log: &[u8]) -> Vec<String> {
    let prefix = format!("{DIR}/");
    let mut seen: Vec<String> = Vec::new();
    for token in log.split(|byte| *byte == 0) {
        let Ok(path) = std::str::from_utf8(token) else {
            continue;
        };
        let path = path.trim_matches('\n');
        if let Some(name) = path.strip_prefix(&prefix) {
            if !name.contains('/') {
                seen.retain(|earlier| earlier != name);
                seen.push(name.to_string());
            }
        }
    }
    seen
}

fn repo_root() -> Result<PathBuf, String> {
    crate::git::stdout(&["rev-parse", "--show-toplevel"])
        .filter(|s| !s.is_empty())
        .map(PathBuf::from)
        .ok_or_else(|| "not inside a git repository".to_string())
}

/// The fragments: regular `*.md` files directly in `changes/`, other than
/// README, as `(name, text)` in name order. A symlink is ignored.
fn read_fragments(root: &Path) -> Result<Vec<(String, String)>, String> {
    let dir = root.join(DIR);
    let mut names = Vec::new();
    let entries = match std::fs::read_dir(&dir) {
        Ok(e) => e,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(format!("cannot read {DIR}/: {e}")),
    };
    for entry in entries {
        let entry = entry.map_err(|e| format!("cannot read {DIR}/: {e}"))?;
        let name = entry
            .file_name()
            .into_string()
            .map_err(|raw| format!("{DIR}/{raw:?}: the name is not UTF-8; rename it"))?;
        let kind = entry
            .file_type()
            .map_err(|e| format!("cannot read {DIR}/{name}: {e}"))?;
        if kind.is_file() && name.ends_with(".md") && !name.eq_ignore_ascii_case("README.md") {
            names.push(name);
        }
    }
    names.sort();
    let mut res = Vec::new();
    for name in names {
        let text = std::fs::read_to_string(dir.join(&name))
            .map_err(|e| format!("cannot read {DIR}/{name}: {e}"))?;
        res.push((name, text));
    }
    Ok(res)
}

/// The first line outside a code fence that would start a `#` or `##` heading:
/// folded in, it would split the release section the workflow reads.
fn heading_line(text: &str) -> Option<&str> {
    let mut fenced = false;
    for line in text.lines() {
        if is_fence(line) {
            fenced = !fenced;
        } else if !fenced && (line.starts_with("# ") || line.starts_with("## ")) {
            return Some(line);
        }
    }
    None
}

/// What is wrong with the fragments themselves, one line each.
fn fragment_problems(fragments: &[(String, String)]) -> Vec<String> {
    let mut problems = Vec::new();
    for (name, text) in fragments {
        if text.trim_start().starts_with("---") {
            problems.push(format!(
                "{DIR}/{name}: starts with `---`, which is reserved for front matter; start with the note's text"
            ));
        } else if is_empty_fragment(text) {
            problems.push(format!("{DIR}/{name}: holds no note (only the placeholder or blank); write it or delete the file"));
        } else if let Some(line) = heading_line(text) {
            problems.push(format!(
                "{DIR}/{name}: has the heading {line:?}; a note is plain paragraphs (use `###` or deeper if it needs one)"
            ));
        }
    }
    problems
}

fn usage() -> i32 {
    eprintln!("usage: {BIN} changelog new [<slug>]");
    eprintln!("       {BIN} changelog collect <version> [--dry-run]");
    eprintln!("       {BIN} changelog check [--base <ref>]");
    eprintln!("(`{BIN} changelog --help` says more)");
    2
}

fn help() -> i32 {
    out(&format!(
        "{BIN} changelog — release notes as one file per pull request"
    ));
    out("");
    out("  new [<slug>]            write changes/<slug>.md (slug: the branch name) to fill in");
    out("  collect <version>       fold changes/*.md into `## v<version>` below `## Unreleased`,");
    out("                          in merge order, and delete them; stages and commits nothing");
    out("                          [--dry-run: print what would happen, write nothing]");
    out("  check [--base <ref>]    refuse a direct edit under `## Unreleased` (base: the");
    out("                          merge-base with origin/main) and any empty fragment");
    0
}

/// `amont changelog …`; `args` is what follows the verb.
pub fn command(args: &[OsString]) -> i32 {
    let words: Vec<String> = args
        .iter()
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    let Some(verb) = words.first() else {
        eprintln!("{BIN}: changelog: no subcommand (new, collect or check)");
        return usage();
    };
    // Flags end at `--`; what follows is operands, whatever it starts with.
    let (flags, operands): (&[String], &[String]) = match words[1..].iter().position(|w| w == "--")
    {
        Some(at) => (&words[1..=at], &words[at + 2..]),
        None => (&words[1..], &[]),
    };
    if flags.iter().any(|w| w == "--help" || w == "-h") || verb == "--help" || verb == "-h" {
        return help();
    }
    let positional: Vec<&String> = flags
        .iter()
        .filter(|w| !w.starts_with('-'))
        .chain(operands.iter())
        .collect();
    match verb.as_str() {
        "help" => help(),
        "new" => {
            if flags.iter().any(|w| w.starts_with('-') && w != "--") || positional.len() > 1 {
                eprintln!("{BIN}: changelog new: takes at most one slug");
                return usage();
            }
            run_new(positional.first().map(|w| w.as_str()))
        }
        "collect" => {
            let mode = if flags.iter().any(|w| w == "--dry-run") {
                Collect::DryRun
            } else {
                Collect::Write
            };
            if let Some(other) = flags
                .iter()
                .find(|w| w.starts_with('-') && *w != "--dry-run" && *w != "--")
            {
                eprintln!("{BIN}: changelog collect: unknown flag {other:?}");
                return usage();
            }
            if positional.len() != 1 {
                eprintln!("{BIN}: changelog collect: needs exactly one version (1.2.3 or v1.2.3)");
                return usage();
            }
            let Some(version) = parse_version(positional[0]) else {
                eprintln!(
                    "{BIN}: changelog collect: {:?} is not a version (1.2.3, v1.2.3 or 1.2.3-rc.1)",
                    positional[0]
                );
                return usage();
            };
            run_collect(&version, mode)
        }
        "check" => {
            let mut base = None;
            let mut remaining = flags.iter();
            while let Some(word) = remaining.next() {
                if word == "--base" {
                    match remaining.next() {
                        Some(base_ref) => base = Some(base_ref.clone()),
                        None => {
                            eprintln!("{BIN}: changelog check: --base needs a ref");
                            return usage();
                        }
                    }
                } else if let Some(base_ref) = word.strip_prefix("--base=") {
                    base = Some(base_ref.to_string());
                } else if word == "--" {
                    // Flags end here; `check` takes no operands.
                } else {
                    eprintln!("{BIN}: changelog check: unexpected {word:?}");
                    return usage();
                }
            }
            if !operands.is_empty() {
                eprintln!("{BIN}: changelog check: unexpected {:?}", operands[0]);
                return usage();
            }
            run_check(base.as_deref())
        }
        other => {
            eprintln!("{BIN}: changelog: unknown subcommand {other:?}");
            usage()
        }
    }
}

fn run_new(slug: Option<&str>) -> i32 {
    let root = match repo_root() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("{BIN}: changelog new: {e}");
            return 1;
        }
    };
    let slug = match slug {
        Some(given_slug) => {
            if !valid_slug(given_slug) {
                eprintln!(
                    "{BIN}: changelog new: {given_slug:?} is not a slug: letters, digits, `.`, `_`, `-`, starting with a letter or digit, and not README"
                );
                return usage();
            }
            given_slug.to_string()
        }
        None => {
            let branch = crate::git::stdout(&["symbolic-ref", "--quiet", "--short", "HEAD"]);
            let derived = branch
                .filter(|b| b != "main" && b != "master")
                .map(|b| slugify(&b))
                .filter(|s| valid_slug(s));
            match derived {
                Some(s) => s,
                None => {
                    eprintln!(
                        "{BIN}: changelog new: no slug to take from the branch (detached, main or empty); run `{BIN} changelog new <slug>`"
                    );
                    return usage();
                }
            }
        }
    };
    let dir = root.join(DIR);
    if let Err(e) = std::fs::create_dir_all(&dir) {
        eprintln!("{BIN}: changelog new: cannot create {DIR}/: {e}");
        return 1;
    }
    let path = dir.join(format!("{slug}.md"));
    let made = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
        .and_then(|mut f| f.write_all(PLACEHOLDER.as_bytes()));
    match made {
        Ok(()) => {
            out(&format!("{DIR}/{slug}.md"));
            eprintln!("{BIN}: edit {DIR}/{slug}.md: replace the placeholder with the release note");
            0
        }
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            eprintln!(
                "{BIN}: changelog new: {DIR}/{slug}.md exists; edit it, or run `{BIN} changelog new <other-slug>`"
            );
            1
        }
        Err(e) => {
            eprintln!("{BIN}: changelog new: cannot write {DIR}/{slug}.md: {e}");
            1
        }
    }
}

/// Whether `collect` writes, or only says what it would do.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Collect {
    Write,
    DryRun,
}

/// Remove the collected fragments (and `changes/` once empty). The leftovers,
/// each with the error that kept it.
fn remove_fragments(root: &Path, names: &[&str]) -> Vec<(String, std::io::Error)> {
    let mut left = Vec::new();
    for name in names {
        if let Err(e) = std::fs::remove_file(root.join(DIR).join(name)) {
            left.push((name.to_string(), e));
        }
    }
    // Fails while README or a stranger is still in `changes/`; that is fine.
    drop(std::fs::remove_dir(root.join(DIR))); // reason: only an empty directory goes
    left
}

fn run_collect(version: &str, mode: Collect) -> i32 {
    let root = match repo_root() {
        Ok(root) => root,
        Err(e) => {
            eprintln!("{BIN}: changelog collect: {e}");
            return 1;
        }
    };
    let root_str = root.to_string_lossy().into_owned();
    let fragments = match read_fragments(&root) {
        Ok(found) => found,
        Err(e) => {
            eprintln!("{BIN}: changelog collect: {e}");
            return 1;
        }
    };
    if fragments.is_empty() {
        eprintln!("{BIN}: changelog collect: {DIR}/ has no fragment to collect; write one with `{BIN} changelog new`");
        return 1;
    }
    let problems = fragment_problems(&fragments);
    if !problems.is_empty() {
        for problem in &problems {
            eprintln!("{BIN}: changelog collect: {problem}");
        }
        return 1;
    }
    let log = match crate::git::stdout_raw_or_why(&[
        "-C",
        &root_str,
        "-c",
        "core.quotepath=off",
        "log",
        "--first-parent",
        "-m",
        "--diff-filter=A",
        "--name-only",
        "-z",
        "--format=",
        "--reverse",
        "--",
        DIR,
    ]) {
        Ok(log) => log,
        Err(why) => {
            eprintln!("{BIN}: changelog collect: git log failed: {why}");
            return 1;
        }
    };
    if crate::git::stdout(&["-C", &root_str, "rev-parse", "--is-shallow-repository"])
        .is_some_and(|answer| answer == "true")
    {
        eprintln!("{BIN}: changelog collect: shallow clone: the merge order may be incomplete; unknown fragments go by name");
    }
    let order = order_from_log(&log);
    let rank = |name: &str| order.iter().position(|o| o == name).unwrap_or(usize::MAX);
    let mut sorted: Vec<&(String, String)> = fragments.iter().collect();
    sorted.sort_by(|a, b| rank(&a.0).cmp(&rank(&b.0)).then_with(|| a.0.cmp(&b.0)));
    let names: Vec<&str> = sorted.iter().map(|(name, _)| name.as_str()).collect();
    let bodies: Vec<String> = sorted
        .iter()
        .map(|(_, text)| text.replace("\r\n", "\n").trim().to_string())
        .collect();

    let path = root.join(FILE);
    let changelog = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(e) => {
            eprintln!("{BIN}: changelog collect: cannot read {FILE}: {e}");
            return 1;
        }
    };
    let prefix = if mode == Collect::DryRun {
        "dry run: "
    } else {
        ""
    };
    // A run cut off between the write and the deletes leaves the section and
    // the fragments: finish the deletes rather than refuse.
    let unified = changelog.replace("\r\n", "\n");
    // Only the version's own section counts: a short note may well appear
    // under an older release.
    let already_written = section_of(&unified, &format!("## v{version}"))
        .is_some_and(|(start, end)| bodies.iter().all(|body| unified[start..end].contains(body)));
    if !already_written {
        let new_text = match fold(&changelog, version, &bodies) {
            Ok(text) => text,
            Err(e) => {
                eprintln!("{BIN}: changelog collect: {e}");
                return 1;
            }
        };
        if mode == Collect::Write {
            if let Err(e) = write_atomic(&path, &new_text) {
                eprintln!("{BIN}: changelog collect: cannot write {FILE}: {e}");
                return 1;
            }
        }
    } else {
        let verb = if mode == Collect::DryRun {
            "would remove"
        } else {
            "removing"
        };
        eprintln!("{BIN}: changelog collect: {FILE} already holds these notes under `## v{version}`; {verb} the fragments");
    }
    if mode == Collect::Write {
        let left = remove_fragments(&root, &names);
        if !left.is_empty() {
            eprintln!("{BIN}: changelog collect: {FILE} is updated, but these fragments stayed:");
            for (name, e) in &left {
                eprintln!("  {DIR}/{name}: {e}");
                eprintln!("  rm {DIR}/{name}");
            }
            eprintln!("then `git add -A -- {FILE} {DIR}`");
            return 1;
        }
    }
    for name in &names {
        out(&format!(
            "{prefix}collected {DIR}/{name} into ## v{version}"
        ));
    }
    if mode == Collect::DryRun {
        out("dry run: nothing written");
    } else {
        eprintln!("next: git add -A -- {FILE} {DIR}");
    }
    0
}

/// Write `text` over `path` through a temp file in the same directory, whose
/// name carries this process id so two runs never share one.
fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> {
    let tmp = path.with_extension(format!("md.tmp-{}", std::process::id()));
    let written = (|| {
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)?;
        file.write_all(text.as_bytes())?;
        file.sync_all()?;
        if let Ok(meta) = std::fs::metadata(path) {
            // Keep the mode; a failure to copy it must not lose the release notes.
            drop(std::fs::set_permissions(&tmp, meta.permissions()));
        }
        std::fs::rename(&tmp, path)
    })();
    if written.is_err() {
        // The write error is the one worth reporting; the temp file is best effort.
        drop(std::fs::remove_file(&tmp));
    }
    written
}

fn run_check(base: Option<&str>) -> i32 {
    let root = match repo_root() {
        Ok(r) => r,
        Err(e) => {
            eprintln!("{BIN}: changelog check: {e}");
            return 1;
        }
    };
    let root_s = root.to_string_lossy().into_owned();
    let mut bad = false;
    match read_fragments(&root) {
        Ok(f) => {
            for p in fragment_problems(&f) {
                eprintln!("{BIN}: changelog check: {p}");
                bad = true;
            }
        }
        Err(e) => {
            eprintln!("{BIN}: changelog check: {e}");
            return 1;
        }
    }
    let current = match std::fs::read_to_string(root.join(FILE)) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return i32::from(bad),
        Err(e) => {
            eprintln!("{BIN}: changelog check: cannot read {FILE}: {e}");
            return 1;
        }
    };
    let base_ref = match base {
        Some(b) => {
            let spec = format!("{b}^{{commit}}");
            if crate::git::stdout(&["-C", &root_s, "rev-parse", "--verify", "--quiet", &spec])
                .is_none()
            {
                eprintln!(
                    "{BIN}: changelog check: cannot resolve --base {b:?}; pass a ref that exists"
                );
                return 1;
            }
            b.to_string()
        }
        None => {
            let found = ["origin/main", "main"]
                .iter()
                .find_map(|r| crate::git::stdout(&["-C", &root_s, "merge-base", "HEAD", r]));
            match found {
                Some(s) => s,
                None => {
                    eprintln!("{BIN}: changelog check: no merge-base with origin/main or main; pass `--base <ref>`");
                    return 1;
                }
            }
        }
    };
    let spec = format!("{base_ref}:{FILE}");
    let base_text = if crate::git::succeeds(&["-C", &root_s, "cat-file", "-e", &spec]) {
        match crate::git::stdout_raw(&["-C", &root_s, "show", &spec]) {
            Some(b) => String::from_utf8_lossy(&b).into_owned(),
            None => {
                eprintln!("{BIN}: changelog check: git could not read {spec}; pass `--base <ref>`");
                return 1;
            }
        }
    } else {
        String::new()
    };
    let now = unreleased_body(&current).unwrap_or_default();
    let then = unreleased_body(&base_text).unwrap_or_default();
    if !now.is_empty() && now != then {
        eprintln!(
            "{BIN}: changelog check: {FILE} changed under `## Unreleased`; release notes go in a fragment now: `{BIN} changelog new`, and undo the edit in {FILE}"
        );
        bad = true;
    }
    i32::from(bad)
}

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

    #[test]
    fn a_placeholder_alone_is_empty() {
        assert!(is_empty_fragment(PLACEHOLDER));
        assert!(is_empty_fragment("<!-- a -->\n\n<!-- b -->"));
        assert!(!is_empty_fragment("<!-- a -->\nSomething."));
        assert!(is_empty_fragment("<!-- never closed"));
    }

    #[test]
    fn slugs() {
        assert!(valid_slug("t18-x_1.2"));
        for bad in ["", "-x", ".x", "a/b", "README", "readme", "a b", ".."] {
            assert!(!valid_slug(bad), "{bad}");
        }
        assert_eq!(slugify("prog/drive-only/t18"), "prog-drive-only-t18");
        assert_eq!(slugify("-.x"), "x");
    }

    #[test]
    fn versions() {
        assert_eq!(parse_version("v1.2.3").as_deref(), Some("1.2.3"));
        assert_eq!(parse_version("1.2.3-rc.1").as_deref(), Some("1.2.3-rc.1"));
        for bad in ["1.2", "v1.2.x", "1.2.3\n# x", "", "1.2.3-", "a.b.c", "1..3"] {
            assert!(parse_version(bad).is_none(), "{bad:?}");
        }
    }

    const BASE: &str = "# Changelog\n\nintro\n\n## Unreleased\n\n## v1.0.0\n\nold\n";

    #[test]
    fn folds_in_order_below_unreleased() {
        let got = fold(BASE, "1.1.0", &["first".into(), "second".into()]).unwrap();
        assert_eq!(
            got,
            "# Changelog\n\nintro\n\n## Unreleased\n\n## v1.1.0\n\nfirst\n\nsecond\n\n## v1.0.0\n\nold\n"
        );
    }

    #[test]
    fn folds_old_unreleased_text_first() {
        let t = "## Unreleased\n\nlegacy\n\n## v1.0.0\n\nold\n";
        let got = fold(t, "1.1.0", &["new".into()]).unwrap();
        assert_eq!(
            got,
            "## Unreleased\n\n## v1.1.0\n\nlegacy\n\nnew\n\n## v1.0.0\n\nold\n"
        );
    }

    #[test]
    fn unreleased_at_the_end_of_the_file() {
        let got = fold("## Unreleased\n", "1.0.0", &["n".into()]).unwrap();
        assert_eq!(got, "## Unreleased\n\n## v1.0.0\n\nn\n");
        let got = fold("## Unreleased", "1.0.0", &["n".into()]).unwrap();
        assert_eq!(got, "## Unreleased\n\n## v1.0.0\n\nn\n");
    }

    #[test]
    fn crlf_is_kept() {
        let t = BASE.replace('\n', "\r\n");
        let got = fold(&t, "1.1.0", &["a".into()]).unwrap();
        assert!(got.contains("## v1.1.0\r\n\r\na\r\n"));
        assert!(!got.replace("\r\n", "").contains('\n'));
    }

    #[test]
    fn a_fence_hides_headings() {
        let t = "## Unreleased\n\n```\n## v9.9.9\n## Unreleased\n```\n\n## v1.0.0\n";
        let (a, b) = unreleased_section(t).unwrap();
        assert!(t[a..b].contains("## Unreleased"));
        assert!(t[b..].starts_with("## v1.0.0"));
        assert!(!has_version_heading(t, "9.9.9"));
        assert!(has_version_heading(t, "1.0.0"));
    }

    #[test]
    fn refusals() {
        assert!(fold(BASE, "1.0.0", &["x".into()])
            .unwrap_err()
            .contains("already"));
        assert!(fold("# x\n", "1.0.0", &["x".into()])
            .unwrap_err()
            .contains("Unreleased"));
    }

    #[test]
    fn the_log_gives_last_sightings_in_order() {
        let log = b"changes/b.md\0changes/a.md\0\0changes/b.md\0changes/sub/x.md\0other.md\0";
        assert_eq!(order_from_log(log), vec!["a.md", "b.md"]);
    }

    #[test]
    fn body_of_unreleased() {
        assert_eq!(unreleased_body(BASE).as_deref(), Some(""));
        assert_eq!(
            unreleased_body("## Unreleased\r\n\r\nx\r\n\r\n## v1\r\n").as_deref(),
            Some("x")
        );
        assert_eq!(unreleased_body("# none\n"), None);
    }

    #[test]
    fn a_section_is_found_by_its_own_heading() {
        let text = "## Unreleased\n\n## v2.0.0\n\nFix.\n\n## v1.0.0\n\nOther.\n";
        let (start, end) = section_of(text, "## v2.0.0").unwrap();
        assert_eq!(text[start..end].trim(), "Fix.");
        assert!(section_of(text, "## v3.0.0").is_none());
        let (start, end) = section_of(text, "## v1.0.0").unwrap();
        assert!(!text[start..end].contains("Fix."));
    }

    #[test]
    fn headings_are_refused_outside_a_fence() {
        assert!(heading_line("text\n## v9\n").is_some());
        assert!(heading_line("# Title").is_some());
        assert!(heading_line("```\n## v9\n```\nok\n### fine\n").is_none());
    }

    #[test]
    fn reserved_front_matter_and_empties_are_named() {
        let f = vec![
            ("a.md".to_string(), "---\ntitle: x\n---\nbody".to_string()),
            ("b.md".to_string(), PLACEHOLDER.to_string()),
            ("c.md".to_string(), "fine".to_string()),
        ];
        let p = fragment_problems(&f);
        assert_eq!(p.len(), 2);
        assert!(p[0].contains("a.md") && p[1].contains("b.md"));
    }
}