cfggraft 0.2.2

Inject declared items into config files owned by another program. Applies what it can prove it wrote, reports what it cannot, and never overwrites a disagreement.
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
//! Marker-delimited spans of a text file, addressed by marker name.
//!
//! For a file a person also writes. Only the span between the markers is
//! managed; everything outside it is theirs.
//!
//! ```markdown
//! hand-written text, theirs
//!
//! <!-- ===PROFILE=== generated by cfggraft; edit config/profile.md instead; sha256=9c91… -->
//! the managed body
//! <!-- ===/PROFILE=== -->
//!
//! more hand-written text, also theirs
//! ```
//!
//! # One item, and provenance in the file
//!
//! A span is a single item: the marker name is its address and the body is its
//! value. So the run is all-or-nothing, not because text works differently from
//! a structured document, but because one item is being decided instead of many.
//!
//! Text can carry a comment, so the record of what was last written lives in the
//! begin marker as a digest of the body it introduced. Nothing external is
//! needed, and the whole arrangement is visible in the file being managed. That
//! digest is what answers "is this body ours?":
//!
//! - it matches what is between the markers — the body is ours, so a changed
//!   declaration replaces it;
//! - it does not match — the body was edited by hand, and nothing is written;
//! - there is none — the span cannot be claimed, so it is adopted only if it
//!   already holds exactly the declared body.
//!
//! Without that check a "generated" span silently eats whatever is typed into
//! it, which inverts the reason for having markers at all.
//!
//! # What is a marker line
//!
//! A marker is a whole line in the configured comment style, and nothing else
//! on that line:
//!
//! ```text
//! marker := indent* opener ws* token (ws anything)? closer ws*
//! token  := ===NAME===  |  ===/NAME===
//! html   :  opener "<!--", closer "-->" on the same line, nothing after it
//! hash   :  opener "#", no closer
//! ```
//!
//! The token must be followed by the end of the comment or by whitespace, so
//! `===PROFILE===` does not match `===PROFILE2===`. Text after the token and
//! inside the comment is allowed; that is where the begin marker carries its
//! provenance. Indentation is allowed. Everything else is not a marker: a
//! mention in prose, a marker inside backticks or in the middle of a line, a
//! marker in the other comment style, or a comment with text after its closer.
//! Those lines are theirs, and the contract that everything outside the markers
//! is left alone holds for them too.
//!
//! A line inside a fenced code block that has this shape is still a marker;
//! fences are not tracked. A file that holds the same begin marker twice is
//! refused rather than having the first occurrence win, so an example region
//! in a file that also holds the real one has to use a different name.
//!
//! A marker name consists of ASCII letters, digits, `_`, `-` and `.`, since
//! anything else — whitespace, `=`, `/` — would blur the edge of the token.
//!
//! # The marker name is a long-lived contract
//!
//! Renaming a marker orphans every file carrying the old name: the span stops
//! being found, and a second region is appended below the first.
//!
//! # Compatibility
//!
//! A span whose begin marker carries no digest and whose body differs from the
//! declaration is refused rather than overwritten, because nothing shows the
//! body was ever this tool's. Adopting such a span is a deliberate act:
//! overwrite it once with `--force`, after which the digest is recorded and
//! ordinary updates apply.

use crate::error::{Error, Result};
use crate::port::{Addr, Item, Observed, Output, Ownership, Repr, State, Store};
use sha2::{Digest, Sha256};

/// How marker lines are commented.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommentStyle {
    /// `<!-- ... -->`, for markdown and html.
    Html,
    /// `# ...`, for shell, toml and yaml.
    Hash,
}

/// The SHA-256 of a string, hex encoded.
pub fn sha256_hex(s: &str) -> String {
    let mut h = Sha256::new();
    h.update(s.as_bytes());
    format!("{:x}", h.finalize())
}

fn begin_line(
    name: &str,
    source: Option<&str>,
    digest: Option<&str>,
    style: CommentStyle,
) -> String {
    let instead = match source {
        Some(s) if !s.is_empty() => format!("edit {s} instead"),
        _ => "DO NOT EDIT".to_string(),
    };
    let mut body = format!("==={name}=== generated by cfggraft; {instead}");
    if let Some(d) = digest {
        body.push_str(&format!("; sha256={d}"));
    }
    match style {
        CommentStyle::Html => format!("<!-- {body} -->"),
        CommentStyle::Hash => format!("# {body}"),
    }
}

fn end_line(name: &str, style: CommentStyle) -> String {
    match style {
        CommentStyle::Html => format!("<!-- ==={}=== -->", format_args!("/{name}")),
        CommentStyle::Hash => format!("# ===/{name}==="),
    }
}

/// The inside of `line` if the whole line is one comment in `style`.
///
/// Indentation and trailing whitespace are ignored. For `html` the closer has
/// to end the line: a comment followed by text is not a marker line, since the
/// text would be overwritten along with it.
fn comment_text(line: &str, style: CommentStyle) -> Option<&str> {
    let t = line.trim();
    match style {
        CommentStyle::Html => t.strip_prefix("<!--")?.strip_suffix("-->"),
        CommentStyle::Hash => t.strip_prefix('#'),
    }
    .map(str::trim)
}

/// Whether `text` starts with `token` as a whole word: at the end of the text,
/// or followed by whitespace. `===P===` must not match `===P2===`.
fn leads_with(text: &str, token: &str) -> bool {
    text.strip_prefix(token)
        .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace))
}

fn is_begin(line: &str, name: &str, style: CommentStyle) -> bool {
    comment_text(line, style).is_some_and(|t| leads_with(t, &format!("==={name}===")))
}

fn is_end(line: &str, name: &str, style: CommentStyle) -> bool {
    comment_text(line, style).is_some_and(|t| leads_with(t, &format!("===/{name}===")))
}

/// Whether `name` can sit inside `===NAME===` without blurring its edges.
fn is_valid_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
}

/// Pull the recorded digest out of a begin marker, if it carries one.
///
/// A truncated or malformed digest counts as none: a partial record cannot
/// establish ownership, and treating it as one would claim a span on the
/// strength of a typo.
fn recorded_digest(line: &str) -> Option<String> {
    let rest = line.split("sha256=").nth(1)?;
    let hex: String = rest
        .chars()
        .take_while(char::is_ascii_hexdigit)
        .take(64)
        .collect();
    (hex.len() == 64).then_some(hex)
}

/// Where a region sits in the file, by line index of its marker lines.
#[derive(Debug, Clone, Copy)]
struct Span {
    begin: usize,
    end: usize,
}

/// One marker-delimited span of a text file.
#[derive(Debug)]
pub struct MarkerSpan {
    name: String,
    style: CommentStyle,
    source: Option<String>,
    lines: Vec<String>,
    span: Option<Span>,
    recorded: Option<String>,
    declared: Repr,
    trailing_newline: bool,
    wrote: bool,
}

impl MarkerSpan {
    /// Find the named span in `target` and prepare to set it to `body`.
    ///
    /// `init` permits appending the region when the marker is absent. Without
    /// it a missing marker is an error rather than an addition, so that a
    /// mistyped name or a wrong file cannot quietly grow a new region.
    pub fn new(
        target: &str,
        name: &str,
        body: &str,
        style: CommentStyle,
        source: Option<&str>,
        init: bool,
    ) -> Result<Self> {
        if name.is_empty() {
            return Err(Error::invalid("a marker name must not be empty"));
        }
        if !is_valid_name(name) {
            return Err(Error::invalid(format!(
                "marker name `{name}` may contain only ASCII letters, digits, `_`, `-` and `.`"
            )));
        }
        let lines: Vec<String> = target.lines().map(str::to_string).collect();
        let trailing_newline = target.is_empty() || target.ends_with('\n');

        // A region is one item, so a file holds its begin marker once. Letting
        // the first occurrence win would silently manage the wrong one — an
        // example region in a fenced code block, say — and leave the real one
        // below it untouched.
        let begins: Vec<usize> = (0..lines.len())
            .filter(|&i| is_begin(&lines[i], name, style))
            .collect();
        if begins.len() > 1 {
            let at: Vec<String> = begins.iter().map(|i| (i + 1).to_string()).collect();
            return Err(Error::invalid(format!(
                "marker `{name}` begins on lines {}; a region is one item, so a file holds it once",
                at.join(", ")
            )));
        }

        let span = match begins.first().copied() {
            Some(begin) => {
                let end = lines
                    .iter()
                    .enumerate()
                    .skip(begin + 1)
                    .find(|(_, l)| is_end(l, name, style))
                    .map(|(i, _)| i)
                    .ok_or_else(|| {
                        Error::invalid(format!(
                            "the begin marker `{name}` on line {} has no matching end marker",
                            begin + 1
                        ))
                    })?;
                Some(Span { begin, end })
            }
            None if init => None,
            None => {
                return Err(Error::invalid(format!(
                    "marker `{name}` not found; pass --init to create the region"
                )))
            }
        };

        let recorded = span.and_then(|s| recorded_digest(&lines[s.begin]));

        Ok(MarkerSpan {
            name: name.to_string(),
            style,
            source: source.map(str::to_string),
            lines,
            span,
            recorded,
            declared: Repr::new(normalise(body)),
            trailing_newline,
            wrote: false,
        })
    }

    /// The address of this span: its marker name.
    pub fn addr(&self) -> Addr {
        Addr::new(self.name.clone())
    }

    /// The body currently between the markers.
    fn body(&self) -> Option<String> {
        self.span.map(|s| self.lines[s.begin + 1..s.end].join("\n"))
    }

    /// Whether the digest should be written on this run.
    ///
    /// Only after actually writing the body, or when adopting a span that
    /// already holds exactly what is declared. Never after a refusal — stamping
    /// a digest onto a hand-edited span would silently bless the edit and make
    /// the next run overwrite it.
    fn should_record(&self) -> bool {
        if self.wrote {
            return true;
        }
        self.recorded.is_none() && self.body().as_deref() == Some(self.declared.as_str())
    }

    fn render(&self) -> String {
        let mut s = self.lines.join("\n");
        if self.trailing_newline {
            s.push('\n');
        }
        s
    }
}

/// Normalise a body to the form held between the markers: lines joined by a
/// newline, with no trailing one. The file's own trailing newline is a property
/// of the file, not of the body.
fn normalise(body: &str) -> String {
    body.lines().collect::<Vec<_>>().join("\n")
}

impl Store for MarkerSpan {
    fn declared(&self) -> Result<Vec<Item>> {
        Ok(vec![Item::new(self.addr(), self.declared.clone())])
    }

    /// Empty: provenance is in the file, so there is nothing for the engine to
    /// carry between runs. The single item this adapter manages is always
    /// declared, so nothing can be known only to provenance.
    fn owned(&self) -> Vec<Item> {
        Vec::new()
    }

    fn state(&self, _addr: &Addr) -> Result<State> {
        let Some(body) = self.body() else {
            return Ok(State::new(Observed::Absent, Ownership::Unknown));
        };
        let observed = Observed::Present(Repr::new(body.clone()));
        let actual = sha256_hex(&body);

        Ok(match &self.recorded {
            None => State::new(observed, Ownership::Unknown)
                .with_note("no digest is recorded, so this span cannot be claimed".to_string()),
            Some(recorded) if recorded == &actual => State::new(observed, Ownership::Ours),
            Some(recorded) => State::new(observed, Ownership::Diverged).with_note(format!(
                "recorded sha256={}…, actual sha256={}…",
                &recorded[..12],
                &actual[..12]
            )),
        })
    }

    fn write(&mut self, _addr: &Addr) -> Result<()> {
        let body: Vec<String> = self.declared.as_str().lines().map(str::to_string).collect();

        match self.span {
            Some(s) => {
                let mut rest = self.lines.split_off(s.end);
                self.lines.truncate(s.begin + 1);
                self.lines.extend(body.iter().cloned());
                self.lines.append(&mut rest);
                self.span = Some(Span {
                    begin: s.begin,
                    end: s.begin + 1 + body.len(),
                });
            }
            None => {
                if self.lines.last().is_some_and(|l| !l.trim().is_empty()) {
                    self.lines.push(String::new());
                }
                let begin = self.lines.len();
                self.lines.push(begin_line(
                    &self.name,
                    self.source.as_deref(),
                    None,
                    self.style,
                ));
                self.lines.extend(body.iter().cloned());
                self.lines.push(end_line(&self.name, self.style));
                self.span = Some(Span {
                    begin,
                    end: begin + 1 + body.len(),
                });
            }
        }
        self.wrote = true;
        Ok(())
    }

    /// Remove the region, markers included.
    fn retract(&mut self, _addr: &Addr) -> Result<()> {
        if let Some(s) = self.span {
            self.lines.drain(s.begin..=s.end);
            self.span = None;
            self.wrote = true;
        }
        Ok(())
    }

    fn finish(&mut self, _owned: &[Item]) -> Result<Output> {
        if let Some(s) = self.span {
            if self.should_record() {
                let digest = sha256_hex(&self.body().unwrap_or_default());
                self.lines[s.begin] = begin_line(
                    &self.name,
                    self.source.as_deref(),
                    Some(&digest),
                    self.style,
                );
            }
        }
        Ok(Output {
            document: self.render(),
            // Provenance is inline, so there is nothing to persist elsewhere.
            prior: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::{run, Options};
    use crate::policy::{Decision, Reason};

    const HTML: CommentStyle = CommentStyle::Html;

    fn apply(
        target: &str,
        body: &str,
        init: bool,
        opts: Options,
    ) -> (String, Decision, Option<String>) {
        let mut s = MarkerSpan::new(target, "PROFILE", body, HTML, None, init).expect("marker");
        let (report, out) = run(&mut s, opts).expect("run");
        let entry = &report.entries[0];
        (out.document, entry.decision, entry.note.clone())
    }

    #[test]
    fn init_appends_the_region_and_keeps_the_hand_text() {
        let mut s = MarkerSpan::new(
            "hand written\n",
            "PROFILE",
            "gen\n",
            HTML,
            Some("src/"),
            true,
        )
        .unwrap();
        let (report, out) = run(&mut s, Options::default()).unwrap();
        assert_eq!(report.entries[0].decision, Decision::Add);
        assert!(out.document.starts_with("hand written\n"));
        assert!(out.document.contains("<!-- ===PROFILE==="));
        assert!(out.document.contains("edit src/ instead"));
        assert!(out.document.contains("sha256="));
        assert!(out.document.contains("gen"));
        assert!(out.document.trim_end().ends_with("<!-- ===/PROFILE=== -->"));
        assert!(out.prior.is_none(), "provenance is inline");
    }

    #[test]
    fn adoption_alters_the_document_even_though_no_item_changed() {
        // The decision here is Skip — the span already holds the declared body —
        // but the document still gains the digest that claims it. A caller that
        // decides whether to write by asking the report what changed would drop
        // that, and the region would stay unclaimable for ever.
        let input = "<!-- ===PROFILE=== -->\nmanaged\n<!-- ===/PROFILE=== -->\n";
        let mut s = MarkerSpan::new(input, "PROFILE", "managed\n", HTML, None, false).unwrap();
        let (report, out) = run(&mut s, Options::default()).unwrap();

        assert!(!report.changed(), "no item changed");
        assert_ne!(out.document, input, "yet the document did");
        assert!(out.document.contains("sha256="));
    }

    #[test]
    fn a_missing_marker_without_init_is_an_error() {
        let err = MarkerSpan::new("x\n", "PROFILE", "b\n", HTML, None, false).unwrap_err();
        assert!(err.to_string().contains("--init"), "got: {err}");
    }

    #[test]
    fn an_unterminated_region_is_an_error() {
        let err =
            MarkerSpan::new("<!-- ===P=== -->\nbody\n", "P", "x\n", HTML, None, false).unwrap_err();
        assert!(
            err.to_string().contains("no matching end marker"),
            "got: {err}"
        );
    }

    #[test]
    fn a_settled_region_is_left_alone() {
        let (first, _, _) = apply("top\n", "one\ntwo\n", true, Options::default());
        let (second, decision, _) = apply(&first, "one\ntwo\n", false, Options::default());
        assert_eq!(decision, Decision::Skip);
        assert_eq!(first, second, "an unchanged run must not rewrite the file");
    }

    #[test]
    fn updates_the_body_and_preserves_both_hand_zones() {
        let (seeded, _, _) = apply("above\n", "old\n", true, Options::default());
        let seeded = format!("{seeded}below\n");
        let (out, decision, _) = apply(&seeded, "new\n", false, Options::default());
        assert_eq!(decision, Decision::Update);
        assert!(out.starts_with("above\n"));
        assert!(out.ends_with("below\n"));
        assert!(out.contains("new"));
        assert!(!out.contains("old"));
    }

    #[test]
    fn refuses_a_hand_edited_span_and_changes_nothing() {
        let (seeded, _, _) = apply("", "generated\n", true, Options::default());
        let tampered = seeded.replace("generated", "someone typed this");
        let (out, decision, note) = apply(&tampered, "next\n", false, Options::default());
        assert_eq!(decision, Decision::Refuse(Reason::HandEdited));
        assert_eq!(out, tampered, "the input must come back byte for byte");
        assert!(note.unwrap().contains("recorded sha256="));
    }

    #[test]
    fn force_overrides_a_hand_edit() {
        let (seeded, _, _) = apply("", "generated\n", true, Options::default());
        let tampered = seeded.replace("generated", "someone typed this");
        let opts = Options {
            force: true,
            ..Options::default()
        };
        let (out, decision, _) = apply(&tampered, "next\n", false, opts);
        assert_eq!(decision, Decision::Update);
        assert!(out.contains("next"));
        assert!(!out.contains("someone typed this"));
    }

    #[test]
    fn an_undigested_span_holding_the_declared_body_is_adopted() {
        let input = "<!-- ===PROFILE=== -->\nmanaged\n<!-- ===/PROFILE=== -->\n";
        let (out, decision, _) = apply(input, "managed\n", false, Options::default());
        assert_eq!(decision, Decision::Skip);
        assert!(out.contains("sha256="), "adoption records the digest");
        assert!(out.contains("managed"));
    }

    #[test]
    fn an_undigested_span_holding_something_else_is_refused() {
        let input = "<!-- ===PROFILE=== -->\nhand rolled\n<!-- ===/PROFILE=== -->\n";
        let (out, decision, note) = apply(input, "managed\n", false, Options::default());
        assert_eq!(decision, Decision::Refuse(Reason::Conflict));
        assert_eq!(out, input, "nothing is written without a claim");
        assert!(
            !out.contains("sha256="),
            "a refusal must not stamp a digest"
        );
        assert!(note.unwrap().contains("no digest"));
    }

    #[test]
    fn adopting_an_undigested_span_needs_force_once() {
        let input = "<!-- ===PROFILE=== -->\nhand rolled\n<!-- ===/PROFILE=== -->\n";
        let opts = Options {
            force: true,
            ..Options::default()
        };
        let (out, decision, _) = apply(input, "managed\n", false, opts);
        assert_eq!(decision, Decision::Update);
        assert!(out.contains("managed"));
        assert!(out.contains("sha256="));

        // Having been claimed, ordinary updates apply.
        let (out2, decision2, _) = apply(&out, "next\n", false, Options::default());
        assert_eq!(decision2, Decision::Update);
        assert!(out2.contains("next"));
    }

    #[test]
    fn an_end_marker_is_not_mistaken_for_a_begin_marker() {
        assert!(is_begin("<!-- ===PROFILE=== x -->", "PROFILE", HTML));
        assert!(!is_begin("<!-- ===/PROFILE=== -->", "PROFILE", HTML));
        assert!(is_end("<!-- ===/PROFILE=== -->", "PROFILE", HTML));
    }

    #[test]
    fn a_marker_is_a_whole_comment_line_in_the_configured_style() {
        let generated = begin_line("P", Some("src/"), Some(&"a".repeat(64)), HTML);
        let hash_generated = begin_line("P", None, None, CommentStyle::Hash);
        let cases: &[(&str, CommentStyle, bool)] = &[
            // Marker lines.
            (generated.as_str(), HTML, true),
            ("<!-- ===P=== -->", HTML, true),
            ("<!--===P===-->", HTML, true),
            ("   <!-- ===P=== -->", HTML, true),
            ("<!-- ===P=== -->   ", HTML, true),
            (hash_generated.as_str(), CommentStyle::Hash, true),
            ("# ===P=== extra words", CommentStyle::Hash, true),
            ("#===P===", CommentStyle::Hash, true),
            // Not marker lines.
            ("<!-- ===P2=== -->", HTML, false),
            ("<!-- ===P===x -->", HTML, false),
            ("read up to `<!-- ===P=== -->` first", HTML, false),
            ("the marker name ===P=== appears in prose", HTML, false),
            ("<!-- ===P=== --> is the begin line", HTML, false),
            ("<!-- ===P===", HTML, false),
            ("# ===P===", HTML, false),
            ("<!-- ===P=== -->", CommentStyle::Hash, false),
            ("## ===P===", CommentStyle::Hash, false),
            ("#!/bin/sh ===P===", CommentStyle::Hash, false),
        ];
        for (line, style, expected) in cases {
            assert_eq!(
                is_begin(line, "P", *style),
                *expected,
                "is_begin({line:?}, {style:?})"
            );
            assert!(!is_end(line, "P", *style), "is_end({line:?}, {style:?})");
        }
        assert!(is_end("  <!-- ===/P=== -->", "P", HTML));
        assert!(is_end("# ===/P===", "P", CommentStyle::Hash));
        assert!(!is_end("see `<!-- ===/P=== -->`", "P", HTML));
    }

    #[test]
    fn a_line_that_mentions_the_marker_is_not_the_marker() {
        // Issue #1: the begin marker mentioned in prose, above the real region.
        // Adopting with --force used to rewrite the sentence into a marker line.
        let input = "intro\n\nread up to the marker line (`<!-- ===PROFILE=== -->`) first,\n\
                     then stop at `<!-- ===/PROFILE=== -->`.\n\n\
                     <!-- ===PROFILE=== -->\nbody\n<!-- ===/PROFILE=== -->\n";
        let opts = Options {
            force: true,
            ..Options::default()
        };
        let (out, decision, _) = apply(input, "body\n", false, opts);
        assert_eq!(decision, Decision::Skip, "the real region is the one found");
        assert!(out.starts_with(
            "intro\n\nread up to the marker line (`<!-- ===PROFILE=== -->`) first,\n\
             then stop at `<!-- ===/PROFILE=== -->`.\n\n"
        ));
        assert_eq!(out.matches("<!-- ===/PROFILE=== -->").count(), 2);
        assert!(out.contains("sha256="), "the real region was adopted");
    }

    #[test]
    fn a_marker_in_the_other_comment_style_is_not_found() {
        let input = "the hash form `# ===PROFILE===` in prose\n\n\
                     <!-- ===PROFILE=== -->\nbody\n<!-- ===/PROFILE=== -->\n";
        let (_, decision, _) = apply(input, "body\n", false, Options::default());
        assert_eq!(decision, Decision::Skip);

        let hash_only = "# ===PROFILE===\nbody\n# ===/PROFILE===\n";
        let err = MarkerSpan::new(hash_only, "PROFILE", "body\n", HTML, None, false).unwrap_err();
        assert!(err.to_string().contains("not found"), "got: {err}");
    }

    #[test]
    fn a_second_begin_marker_is_refused_with_both_line_numbers() {
        let input =
            "intro\n\n```\n<!-- ===PROFILE=== -->\nexample\n<!-- ===/PROFILE=== -->\n```\n\n\
                     <!-- ===PROFILE=== -->\nbody\n<!-- ===/PROFILE=== -->\n";
        let err = MarkerSpan::new(input, "PROFILE", "body\n", HTML, None, false).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("lines 4, 9"), "got: {msg}");
        assert!(msg.contains("holds it once"), "got: {msg}");
    }

    #[test]
    fn an_indented_marker_is_still_a_marker() {
        let input = "  <!-- ===PROFILE=== -->\nbody\n  <!-- ===/PROFILE=== -->\n";
        let (out, decision, _) = apply(input, "body\n", false, Options::default());
        assert_eq!(decision, Decision::Skip);
        assert!(out.contains("sha256="));
    }

    #[test]
    fn a_marker_name_is_limited_to_safe_characters() {
        for bad in ["a b", "a=b", "/x", "x/", "a>b", "P-->"] {
            let err = MarkerSpan::new("", bad, "b", HTML, None, true).unwrap_err();
            assert!(err.to_string().contains("ASCII letters"), "{bad}: {err}");
        }
        for good in ["P", "profile-2", "a.b_c"] {
            assert!(
                MarkerSpan::new("", good, "b", HTML, None, true).is_ok(),
                "{good}"
            );
        }
    }

    #[test]
    fn the_hash_comment_style_is_used_throughout() {
        let mut s = MarkerSpan::new("", "P", "b\n", CommentStyle::Hash, None, true).unwrap();
        let (_, out) = run(&mut s, Options::default()).unwrap();
        assert!(out.document.contains("# ===P==="));
        assert!(out.document.contains("# ===/P==="));
        assert!(!out.document.contains("<!--"));
    }

    #[test]
    fn a_partial_digest_does_not_establish_ownership() {
        assert!(recorded_digest("sha256=abc").is_none());
        let full = "a".repeat(64);
        assert_eq!(recorded_digest(&format!("x sha256={full} -->")), Some(full));
    }

    #[test]
    fn an_empty_marker_name_is_rejected() {
        let err = MarkerSpan::new("", "", "b", HTML, None, true).unwrap_err();
        assert!(err.to_string().contains("must not be empty"), "got: {err}");
    }

    #[test]
    fn retracting_removes_the_region_with_its_markers() {
        let (seeded, _, _) = apply("above\n", "body\n", true, Options::default());
        let mut s = MarkerSpan::new(&seeded, "PROFILE", "body\n", HTML, None, false).unwrap();
        s.retract(&s.addr()).unwrap();
        let out = s.finish(&[]).unwrap();
        assert!(!out.document.contains("PROFILE"));
        assert!(out.document.starts_with("above\n"));
    }
}