oakum 0.12.1

A polyglot release tool that derives dependent version bumps from the dependency graph
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Parse and write bump-file bodies (ADR-0005 intersection + ADR-0028 none/empty).
//!
//! Pure string I/O for one bump file's body. Skip-list discovery, workspace
//! membership, and continue-on-malformed live in [`super::read`] (`okm-wnp`);
//! foreign-parser fixtures are `okm-x4u`.
//!
//! Release levels: line 1 exactly `---`; one `name: patch|minor|major` per line;
//! unquoted keys except scoped npm names (quoted); no blank lines; no duplicate
//! keys; closing `---`; no preamble; no BOM. ADR-0028 also allows `none` and an
//! empty frontmatter block. The note after the closing delimiter is kept
//! verbatim.

use alloc::collections::BTreeSet;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::str::FromStr;

use crate::plan::BumpLevel;

/// One bump file after parsing the intersection grammar.
///
/// Package names are the frontmatter keys as written (quotes stripped). Mapping
/// onto [`crate::plan::PackageId`] needs a workspace and is a later step.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChangeFile {
    entries: Vec<(String, BumpLevel)>,
    note: String,
}

impl ChangeFile {
    #[must_use]
    pub fn entries(&self) -> &[(String, BumpLevel)] {
        &self.entries
    }

    #[must_use]
    pub fn note(&self) -> &str {
        &self.note
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParseError {
    Bom,
    MissingOpeningDelimiter,
    MissingClosingDelimiter,
    BlankLineInFrontmatter,
    DuplicatePackage(String),
    InvalidLine(String),
    UnquotedScopedName(String),
    QuotedUnscopedName(String),
    UnknownLevel(String),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bom => f.write_str("bump file must not start with a UTF-8 BOM"),
            Self::MissingOpeningDelimiter => f.write_str("bump file must start with --- on line 1"),
            Self::MissingClosingDelimiter => f.write_str("bump file is missing the closing ---"),
            Self::BlankLineInFrontmatter => {
                f.write_str("bump file frontmatter must not contain blank lines")
            }
            Self::DuplicatePackage(name) => {
                write!(f, "bump file names package `{name}` more than once")
            }
            Self::InvalidLine(line) => {
                write!(f, "bump file frontmatter line is not `name: level`: {line}")
            }
            Self::UnquotedScopedName(name) => write!(
                f,
                "scoped package `{name}` must be quoted (`\"{name}\": level`)"
            ),
            Self::QuotedUnscopedName(name) => write!(
                f,
                "package `{name}` must not be quoted (only scoped npm names are quoted)"
            ),
            Self::UnknownLevel(level) => {
                write!(
                    f,
                    "bump level `{level}` is not none, patch, minor, or major"
                )
            }
        }
    }
}

impl core::error::Error for ParseError {}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum WriteError {
    EmptyPackageName,
    DuplicatePackage(String),
    /// Name contains characters that cannot appear in an intersection key
    /// (quotes, colon, or line breaks).
    InvalidPackageName(String),
    /// Scoped npm name plus `knope.toml`: quoted form is invisible to knope
    /// (ADR-0005). Refuse rather than write a silent no-op for one reader.
    ScopedPackageWithKnope(String),
}

impl fmt::Display for WriteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyPackageName => f.write_str("bump file package name must not be empty"),
            Self::DuplicatePackage(name) => {
                write!(f, "bump file names package `{name}` more than once")
            }
            Self::InvalidPackageName(name) => {
                write!(f, "bump file package name `{name}` is not writable in the intersection grammar")
            }
            Self::ScopedPackageWithKnope(name) => write!(
                f,
                "refusing to write scoped package `{name}` while knope.toml is present (quoted keys are invisible to knope)"
            ),
        }
    }
}

impl core::error::Error for WriteError {}

/// Whether a `knope.toml` shares the repo (ADR-0005 scoped-quote refuse).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KnopePresence {
    Absent,
    Present,
}

/// # Errors
///
/// Returns [`ParseError`] when the text is outside the intersection grammar.
pub fn parse(text: &str) -> Result<ChangeFile, ParseError> {
    parse_with(text, false)
}

/// Like [`parse`], but accepts quoted unscoped keys (`"pkg": patch`).
/// `@changesets/cli` quotes every key; `migrate` rewrites those files
/// into the intersection grammar [`write`] emits.
///
/// # Errors
///
/// Same as [`parse`], except [`ParseError::QuotedUnscopedName`] is not
/// returned for quoted unscoped keys.
pub fn parse_migration(text: &str) -> Result<ChangeFile, ParseError> {
    parse_with(text, true)
}

fn parse_with(text: &str, allow_quoted_unscoped: bool) -> Result<ChangeFile, ParseError> {
    if text.starts_with('\u{FEFF}') || text.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) {
        return Err(ParseError::Bom);
    }

    let mut lines = LineCursor::new(text);
    let Some((_, first)) = lines.next_line() else {
        return Err(ParseError::MissingOpeningDelimiter);
    };
    if first != "---" {
        return Err(ParseError::MissingOpeningDelimiter);
    }

    let mut entries = Vec::new();
    let mut seen = BTreeSet::new();
    let mut closed_at = None;

    while let Some((_, line)) = lines.next_line() {
        if line == "---" {
            closed_at = Some(lines.position_after_current_line());
            break;
        }
        if line.trim().is_empty() {
            return Err(ParseError::BlankLineInFrontmatter);
        }
        let (name, level) = parse_entry(line, allow_quoted_unscoped)?;
        if !seen.insert(name.clone()) {
            return Err(ParseError::DuplicatePackage(name));
        }
        entries.push((name, level));
    }

    let Some(note_start) = closed_at else {
        return Err(ParseError::MissingClosingDelimiter);
    };

    Ok(ChangeFile {
        entries,
        note: String::from(&text[note_start..]),
    })
}

/// Render a bump-file body (LF line endings).
///
/// An empty `entries` slice writes intentionally empty frontmatter (ADR-0028
/// `--empty`). Scoped names (`@scope/pkg`) are quoted. With
/// [`KnopePresence::Present`], a scoped name is refused instead: knope retains
/// the quotes and skips the file.
///
/// # Errors
///
/// Returns [`WriteError`] for illegal or duplicate names, or a scoped package
/// while knope is present.
pub fn write(
    entries: &[(impl AsRef<str>, BumpLevel)],
    note: &str,
    knope: KnopePresence,
) -> Result<String, WriteError> {
    let mut seen = BTreeSet::new();
    let mut out = String::from("---\n");
    for (name, level) in entries {
        let name = name.as_ref();
        validate_write_name(name)?;
        if !seen.insert(String::from(name)) {
            return Err(WriteError::DuplicatePackage(String::from(name)));
        }
        if is_scoped(name) {
            if knope == KnopePresence::Present {
                return Err(WriteError::ScopedPackageWithKnope(String::from(name)));
            }
            out.push('"');
            out.push_str(name);
            out.push('"');
        } else {
            out.push_str(name);
        }
        out.push_str(": ");
        out.push_str(&level.to_string());
        out.push('\n');
    }
    out.push_str("---\n");
    out.push_str(note);
    Ok(out)
}

fn validate_write_name(name: &str) -> Result<(), WriteError> {
    if name.trim().is_empty() {
        return Err(WriteError::EmptyPackageName);
    }
    if invalid_plain_key(name) {
        return Err(WriteError::InvalidPackageName(String::from(name)));
    }
    Ok(())
}

pub(super) fn invalid_plain_key(name: &str) -> bool {
    name != name.trim()
        || name.contains(['"', '\'', '\n', '\r', ':'])
        || yaml_plain_key_coerces(name)
}

/// YAML parses unquoted keys. Refuse tokens `@changesets/parse` would rename,
/// plus YAML 1.1 bools and radix prefixes.
fn yaml_plain_key_coerces(name: &str) -> bool {
    matches!(
        name,
        "~" | "null"
            | "Null"
            | "NULL"
            | "y"
            | "Y"
            | "n"
            | "N"
            | "yes"
            | "Yes"
            | "YES"
            | "no"
            | "No"
            | "NO"
            | "true"
            | "True"
            | "TRUE"
            | "false"
            | "False"
            | "FALSE"
            | "on"
            | "On"
            | "ON"
            | "off"
            | "Off"
            | "OFF"
            | ".inf"
            | ".Inf"
            | ".INF"
            | "-.inf"
            | "-.Inf"
            | "-.INF"
            | "+.inf"
            | "+.Inf"
            | "+.INF"
            | ".nan"
            | ".NaN"
            | ".NAN"
    ) || yaml_integer_prefix(name)
        || yaml_decimal_or_float_coerces(name)
}

fn yaml_integer_prefix(name: &str) -> bool {
    if let Some(digits) = name.strip_prefix("0x").or_else(|| name.strip_prefix("0X")) {
        return !digits.is_empty() && digits.chars().all(|c| c.is_ascii_hexdigit());
    }
    if let Some(digits) = name.strip_prefix("0o").or_else(|| name.strip_prefix("0O")) {
        return !digits.is_empty() && digits.chars().all(|c| matches!(c, '0'..='7'));
    }
    if let Some(digits) = name.strip_prefix("0b").or_else(|| name.strip_prefix("0B")) {
        return !digits.is_empty() && digits.chars().all(|c| matches!(c, '0' | '1'));
    }
    false
}

fn yaml_decimal_or_float_coerces(name: &str) -> bool {
    if let Some(rest) = name.strip_prefix('+') {
        return yaml_numeric_body(rest);
    }
    let body = name.strip_prefix('-').unwrap_or(name);
    if looks_like_yaml_float(body) {
        return true;
    }
    (body == "0" && name != "0")
        || (body.len() > 1 && body.starts_with('0') && body.bytes().all(|b| b.is_ascii_digit()))
        || yaml_js_int_loses_precision(body)
}

/// Integers above JS `Number.MAX_SAFE_INTEGER`. Some exact doubles in that
/// range (`2^53`, `2^53+2`) stay identity under yaml 2.9.
fn yaml_js_int_loses_precision(body: &str) -> bool {
    const MAX_SAFE: u64 = 9_007_199_254_740_991;
    if body.is_empty() || !body.bytes().all(|b| b.is_ascii_digit()) {
        return false;
    }
    match body.parse::<u64>() {
        Ok(n) => n > MAX_SAFE,
        Err(_) => true,
    }
}

fn yaml_numeric_body(body: &str) -> bool {
    !body.is_empty() && (looks_like_yaml_float(body) || body.bytes().all(|b| b.is_ascii_digit()))
}

fn looks_like_yaml_float(body: &str) -> bool {
    let has_dot = body.contains('.');
    let exp_at = body.find(['e', 'E']);
    if !has_dot && exp_at.is_none() {
        return false;
    }
    let (mantissa, exp_ok) = match exp_at {
        Some(i) => {
            let mantissa = &body[..i];
            let mut exp = &body[i + 1..];
            exp = exp.strip_prefix(['+', '-']).unwrap_or(exp);
            if exp.is_empty() || !exp.bytes().all(|b| b.is_ascii_digit()) {
                return false;
            }
            (mantissa, true)
        }
        None => (body, false),
    };
    if mantissa.is_empty() {
        return false;
    }
    let Some((left, frac)) = mantissa.split_once('.') else {
        return exp_ok && mantissa.bytes().all(|b| b.is_ascii_digit());
    };
    if left.is_empty() && frac.is_empty() {
        return false;
    }
    left.bytes().all(|b| b.is_ascii_digit()) && frac.bytes().all(|b| b.is_ascii_digit())
}

fn is_scoped(name: &str) -> bool {
    name.starts_with('@')
}

fn parse_entry(line: &str, allow_quoted_unscoped: bool) -> Result<(String, BumpLevel), ParseError> {
    let Some((raw_key, raw_level)) = line.split_once(':') else {
        return Err(ParseError::InvalidLine(String::from(line)));
    };
    // YAML mapping form; `core:minor` is a scalar to @changesets/parse.
    if !raw_level.starts_with([' ', '\t']) {
        return Err(ParseError::InvalidLine(String::from(line)));
    }
    let key = raw_key.trim();
    let level_text = raw_level.trim();
    if key.is_empty() || level_text.is_empty() {
        return Err(ParseError::InvalidLine(String::from(line)));
    }

    let (name, quoted) = decode_package_key(key, line)?;
    if name.is_empty() {
        return Err(ParseError::InvalidLine(String::from(line)));
    }

    if is_scoped(name) {
        if !quoted {
            return Err(ParseError::UnquotedScopedName(String::from(name)));
        }
    } else if quoted && !allow_quoted_unscoped {
        return Err(ParseError::QuotedUnscopedName(String::from(name)));
    }

    if validate_write_name(name).is_err() {
        return Err(ParseError::InvalidLine(String::from(line)));
    }

    let level = BumpLevel::from_str(level_text)
        .map_err(|err| ParseError::UnknownLevel(String::from(err.text())))?;
    Ok((String::from(name), level))
}

/// Either YAML quote style counts as quoted: Prettier with `singleQuote`
/// rewrites `"@scope/pkg"` to `'@scope/pkg'`, and `@changesets/cli` reads both.
fn decode_package_key<'a>(key: &'a str, line: &str) -> Result<(&'a str, bool), ParseError> {
    let quote = match (key.contains('"'), key.contains('\'')) {
        (false, false) => return Ok((key, false)),
        (true, false) => b'"',
        (false, true) => b'\'',
        (true, true) => return Err(ParseError::InvalidLine(String::from(line))),
    };
    match strip_quotes(key, quote) {
        Some(inner) if !inner.as_bytes().contains(&quote) => Ok((inner, true)),
        _ => Err(ParseError::InvalidLine(String::from(line))),
    }
}

fn strip_quotes(key: &str, quote: u8) -> Option<&str> {
    let bytes = key.as_bytes();
    if bytes.len() >= 2 && bytes[0] == quote && bytes[bytes.len() - 1] == quote {
        Some(&key[1..key.len() - 1])
    } else {
        None
    }
}

/// Byte-oriented line walk so the note can be sliced from the source.
struct LineCursor<'a> {
    text: &'a str,
    pos: usize,
    line_end: usize,
}

impl<'a> LineCursor<'a> {
    fn new(text: &'a str) -> Self {
        Self {
            text,
            pos: 0,
            line_end: 0,
        }
    }

    fn next_line(&mut self) -> Option<(usize, &'a str)> {
        if self.pos > self.text.len() {
            return None;
        }
        if self.pos == self.text.len() {
            // At EOF after the previous line — do not invent an empty line.
            return None;
        }

        let start = self.pos;
        let bytes = self.text.as_bytes();
        let mut i = start;
        while i < bytes.len() && bytes[i] != b'\n' {
            i += 1;
        }
        let mut content_end = i;
        if content_end > start && bytes[content_end - 1] == b'\r' {
            content_end -= 1;
        }
        let content = &self.text[start..content_end];
        self.line_end = if i < bytes.len() { i + 1 } else { bytes.len() };
        self.pos = self.line_end;
        Some((start, content))
    }

    fn position_after_current_line(&self) -> usize {
        self.line_end
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;

    #[test]
    fn round_trips_unscoped_intersection_file() {
        let body = "---\ncore: minor\nutils: patch\n---\n\nNotes here.\n";
        let parsed = parse(body).expect("parse");
        assert_eq!(
            parsed.entries(),
            &[
                ("core".to_string(), BumpLevel::Minor),
                ("utils".to_string(), BumpLevel::Patch),
            ]
        );
        assert_eq!(parsed.note(), "\nNotes here.\n");
        let written = write(parsed.entries(), parsed.note(), KnopePresence::Absent).expect("write");
        assert_eq!(written, body);
    }

    #[test]
    fn accepts_crlf_and_keeps_note_bytes() {
        let body = "---\r\ncore: major\r\n---\r\nbody\r\n";
        let parsed = parse(body).expect("parse");
        assert_eq!(parsed.entries(), &[("core".to_string(), BumpLevel::Major)]);
        assert_eq!(parsed.note(), "body\r\n");
    }

    #[test]
    fn writes_and_parses_quoted_scoped_name() {
        let written = write(
            &[("@oakum/core", BumpLevel::Minor)],
            "note\n",
            KnopePresence::Absent,
        )
        .expect("write");
        assert_eq!(written, "---\n\"@oakum/core\": minor\n---\nnote\n");
        let parsed = parse(&written).expect("parse");
        assert_eq!(
            parsed.entries(),
            &[("@oakum/core".to_string(), BumpLevel::Minor)]
        );
    }

    #[test]
    fn refuses_scoped_write_when_knope_present() {
        let err = write(
            &[("@oakum/core", BumpLevel::Patch)],
            "",
            KnopePresence::Present,
        )
        .unwrap_err();
        assert_eq!(
            err,
            WriteError::ScopedPackageWithKnope("@oakum/core".to_string())
        );
    }

    #[test]
    fn rejects_bom() {
        assert_eq!(
            parse("\u{FEFF}---\ncore: patch\n---\n"),
            Err(ParseError::Bom)
        );
    }

    #[test]
    fn rejects_preamble() {
        assert_eq!(
            parse("preamble\n---\ncore: patch\n---\n"),
            Err(ParseError::MissingOpeningDelimiter)
        );
    }

    #[test]
    fn rejects_blank_line_in_frontmatter() {
        assert_eq!(
            parse("---\ncore: patch\n\nutils: minor\n---\n"),
            Err(ParseError::BlankLineInFrontmatter)
        );
        assert_eq!(
            parse("---\ncore: patch\n   \nutils: minor\n---\n"),
            Err(ParseError::BlankLineInFrontmatter)
        );
    }

    #[test]
    fn rejects_duplicate_package() {
        assert_eq!(
            parse("---\ncore: patch\ncore: minor\n---\n"),
            Err(ParseError::DuplicatePackage("core".to_string()))
        );
    }

    #[test]
    fn accepts_empty_frontmatter() {
        let parsed = parse("---\n---\nnote\n").expect("empty");
        assert_eq!(parsed.entries(), []);
        assert_eq!(parsed.note(), "note\n");
    }

    #[test]
    fn accepts_none_and_rejects_unknown_levels() {
        let parsed = parse("---\ncore: none\n---\n").expect("none");
        assert_eq!(parsed.entries(), &[("core".to_string(), BumpLevel::None)]);
        assert_eq!(
            parse("---\ncore: Major\n---\n"),
            Err(ParseError::UnknownLevel("Major".to_string()))
        );
    }

    #[test]
    fn rejects_unquoted_scoped_and_quoted_unscoped() {
        assert_eq!(
            parse("---\n@oakum/core: minor\n---\n"),
            Err(ParseError::UnquotedScopedName("@oakum/core".to_string()))
        );
        assert_eq!(
            parse("---\n\"core\": minor\n---\n"),
            Err(ParseError::QuotedUnscopedName("core".to_string()))
        );
    }

    #[test]
    fn parse_migration_accepts_quoted_unscoped_and_still_requires_quoted_scoped() {
        let parsed = parse_migration("---\n\"core\": minor\n\"@oakum/cli\": patch\n---\nnote\n")
            .expect("quoted changesets form");
        assert_eq!(
            parsed.entries(),
            &[
                ("core".to_string(), BumpLevel::Minor),
                ("@oakum/cli".to_string(), BumpLevel::Patch),
            ]
        );
        let written = write(parsed.entries(), parsed.note(), KnopePresence::Absent).expect("write");
        assert_eq!(
            written,
            "---\ncore: minor\n\"@oakum/cli\": patch\n---\nnote\n"
        );
        assert_eq!(
            parse_migration("---\n@oakum/core: minor\n---\n"),
            Err(ParseError::UnquotedScopedName("@oakum/core".to_string()))
        );
        assert_eq!(
            parse_migration("---\n\" core \": patch\n---\n"),
            Err(ParseError::InvalidLine("\" core \": patch".to_string()))
        );
        assert_eq!(
            parse_migration("---\n\" \": patch\n---\n"),
            Err(ParseError::InvalidLine("\" \": patch".to_string()))
        );
    }

    #[test]
    fn rejects_missing_closing_delimiter() {
        assert_eq!(
            parse("---\ncore: patch\n"),
            Err(ParseError::MissingClosingDelimiter)
        );
    }

    #[test]
    fn write_empty_frontmatter_round_trips() {
        let empty: Vec<(String, BumpLevel)> = vec![];
        let body = write(&empty, "docs only\n", KnopePresence::Absent).expect("write");
        assert_eq!(body, "---\n---\ndocs only\n");
        let parsed = parse(&body).expect("parse");
        assert_eq!(parsed.entries(), []);
        assert_eq!(parsed.note(), "docs only\n");
    }

    #[test]
    fn write_rejects_empty_and_illegal_names() {
        assert_eq!(
            write(&[("", BumpLevel::Patch)], "", KnopePresence::Absent),
            Err(WriteError::EmptyPackageName)
        );
        assert_eq!(
            write(&[(" ", BumpLevel::Patch)], "", KnopePresence::Absent),
            Err(WriteError::EmptyPackageName)
        );
        assert_eq!(
            write(
                &[("core:extra", BumpLevel::Patch)],
                "",
                KnopePresence::Absent
            ),
            Err(WriteError::InvalidPackageName("core:extra".to_string()))
        );
        assert_eq!(
            write(&[("a\nb", BumpLevel::Patch)], "", KnopePresence::Absent),
            Err(WriteError::InvalidPackageName("a\nb".to_string()))
        );
        assert_eq!(
            write(
                &[("\"core\"", BumpLevel::Patch)],
                "",
                KnopePresence::Present
            ),
            Err(WriteError::InvalidPackageName("\"core\"".to_string()))
        );
    }

    #[test]
    fn write_rejects_yaml_renamed_keys() {
        for name in [
            "null",
            "0x10",
            "0o10",
            "01",
            "1.0",
            "1e2",
            "0777",
            "-0",
            "+1",
            ".5",
            "True",
            "TRUE",
            "False",
            "FALSE",
            ".inf",
            "-.inf",
            ".nan",
            "9007199254740993",
        ] {
            assert_eq!(
                write(&[(name, BumpLevel::Patch)], "", KnopePresence::Absent),
                Err(WriteError::InvalidPackageName(name.to_string())),
                "{name}"
            );
        }
    }

    #[test]
    fn write_rejects_yaml_conservative_keys() {
        for name in [
            "yes",
            "no",
            "on",
            "off",
            "0X10",
            "0b10",
            "9007199254740992",
            "9007199254740994",
        ] {
            assert_eq!(
                write(&[(name, BumpLevel::Patch)], "", KnopePresence::Absent),
                Err(WriteError::InvalidPackageName(name.to_string())),
                "{name}"
            );
        }
    }

    #[test]
    fn write_keeps_names_that_only_resemble_yaml_tokens() {
        for name in ["core", "yes-please", "on-call", "42"] {
            write(&[(name, BumpLevel::Patch)], "n\n", KnopePresence::Absent).expect(name);
        }
    }

    #[test]
    fn write_rejects_duplicate_packages() {
        assert_eq!(
            write(
                &[("core", BumpLevel::Patch), ("core", BumpLevel::Minor)],
                "",
                KnopePresence::Absent,
            ),
            Err(WriteError::DuplicatePackage("core".to_string()))
        );
    }

    #[test]
    fn writes_unscoped_when_knope_present() {
        let written =
            write(&[("core", BumpLevel::Patch)], "n\n", KnopePresence::Present).expect("write");
        assert_eq!(written, "---\ncore: patch\n---\nn\n");
        assert_eq!(parse(&written).expect("parse").note(), "n\n");
    }

    #[test]
    fn rejects_invalid_frontmatter_lines() {
        assert_eq!(
            parse("---\ncore patch\n---\n"),
            Err(ParseError::InvalidLine("core patch".to_string()))
        );
        assert_eq!(
            parse("---\n: patch\n---\n"),
            Err(ParseError::InvalidLine(": patch".to_string()))
        );
        assert_eq!(
            parse("---\ncore:\n---\n"),
            Err(ParseError::InvalidLine("core:".to_string()))
        );
        assert_eq!(
            parse("---\ncore:minor\n---\n"),
            Err(ParseError::InvalidLine("core:minor".to_string()))
        );
        assert_eq!(
            parse("---\n\"\": patch\n---\n"),
            Err(ParseError::InvalidLine("\"\": patch".to_string()))
        );
    }

    #[test]
    fn rejects_malformed_quoting() {
        assert_eq!(
            parse("---\n\"core: patch\n---\n"),
            Err(ParseError::InvalidLine("\"core: patch".to_string()))
        );
        assert_eq!(
            parse("---\n'@oakum/core\": minor\n---\n"),
            Err(ParseError::InvalidLine("'@oakum/core\": minor".to_string()))
        );
        assert_eq!(
            parse("---\n\"@oakum/core: minor\n---\n"),
            Err(ParseError::InvalidLine("\"@oakum/core: minor".to_string()))
        );
    }

    #[test]
    fn accepts_whitespace_around_key_and_level() {
        let parsed = parse("---\n core : minor \n---\n").expect("parse");
        assert_eq!(parsed.entries(), &[("core".to_string(), BumpLevel::Minor)]);
    }

    #[test]
    fn round_trips_empty_note() {
        let body = "---\ncore: patch\n---\n";
        let parsed = parse(body).expect("parse");
        assert_eq!(parsed.note(), "");
        assert_eq!(
            write(parsed.entries(), "", KnopePresence::Absent).expect("write"),
            body
        );
    }

    /// Every fenced bump file in the README oakum writes has to parse. A README
    /// showing a form the parser rejects is worse than no README: `init` and
    /// `migrate` write it into the repository, so the reader trusts it over the
    /// tool.
    ///
    /// This covers the examples, not the prose around them. The defect that
    /// prompted it was a sentence — "oakum reads a quoted bare name too", while
    /// `status`, `check` and `version` all refuse one (`okm-404.21`) — and no
    /// test can read that.
    #[test]
    fn every_bump_file_in_the_shipped_readme_parses() {
        let readme = include_str!("../cli/changeset-readme.md");
        let mut checked = 0;
        for block in readme.split("```markdown").skip(1) {
            let body = block.split("```").next().expect("a closing fence").trim();
            if !body.starts_with("---") {
                continue;
            }
            // The examples name illustrative packages, so the frontmatter
            // shape and the trailing note are all this can check.
            parse(&format!("{body}\n")).unwrap_or_else(|err| {
                panic!(
                    "the shipped README documents a bump file this parser rejects: {err}\n{body}"
                )
            });
            checked += 1;
        }
        assert!(checked >= 2, "found {checked} bump files in the README");
    }

    /// `docs/specs/bump-files.md` lists a quoted unscoped key under "Not
    /// permitted", and nothing pinned it.
    #[test]
    fn a_quoted_bare_name_is_refused_and_says_why() {
        let err = parse("---\n\"core\": minor\n---\n").expect_err("quoted bare name");
        assert_eq!(
            err.to_string(),
            "package `core` must not be quoted (only scoped npm names are quoted)"
        );
        let single = parse("---\n'core': minor\n---\n").expect_err("single-quoted too");
        assert_eq!(single.to_string(), err.to_string());
    }

    #[test]
    fn single_quoted_scoped_name_parses_like_double_quoted() {
        let single = parse("---\n'@oakum/core': minor\n---\n").expect("single");
        let double = parse("---\n\"@oakum/core\": minor\n---\n").expect("double");
        assert_eq!(single.entries(), double.entries());
        assert_eq!(
            single.entries(),
            &[("@oakum/core".to_string(), BumpLevel::Minor)]
        );
    }

    #[test]
    fn single_quoted_unscoped_name_is_still_rejected() {
        assert!(matches!(
            parse("---\n'core': patch\n---\n"),
            Err(ParseError::QuotedUnscopedName(name)) if name == "core"
        ));
        assert!(matches!(
            parse("---\n'@oakum/core\": patch\n---\n"),
            Err(ParseError::InvalidLine(_))
        ));
    }
}