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
//! The `.changeset/` files oakum owns: `_schema.json`, `README.md`, and
//! `_config.toml` (ADR-0023).
//!
//! Three commands write them: `init` writes all three, `migrate` writes them
//! and puts back a schema or README that went missing, and `upgrade`
//! regenerates `_schema.json`, migrates `_config.toml`, and refreshes a README
//! an earlier release wrote. None of them writes
//! `tool-version`: the install pin is the version (ADR-0038).
//! One definition of "owned" here, so the probe, the writes, and the uninstall
//! line cannot disagree about what oakum may touch.

use std::io::{self, Read};
use std::path::Path;

use cap_std::fs::Dir;
use oakum::config;
use oakum::plan::Versioning;

use super::config::{resolve_sibling_write_target, CONFIG_PATH};
use super::deliver_out;
use super::fs::{
    open_read_only, resolve_capability_path, write_file_exclusive, write_file_via_rename,
};
use super::install_pin::Standing;
use super::repository::Repository;
use super::tag_shape::ReadableTemplate;
use super::CliError;

const SCHEMA_REL: &str = ".changeset/_schema.json";
pub(super) const README_REL: &str = ".changeset/README.md";
const README: &str = include_str!("changeset-readme.md");

/// The preferences `_config.toml` records. `init` resolves them from its
/// flags; `migrate` carries what the source tool set.
///
/// Both intent mechanisms false is a config the loader rejects; `init`'s
/// `refuse_both_intent_disabled` refuses it at the flag boundary, so the pair
/// arrives here pre-validated.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct ConfigSettings {
    pub(super) change_files: bool,
    pub(super) conventional_commits: bool,
    pub(super) versioning: Versioning,
    pub(super) private_packages: PrivatePackages,
    /// Set only when the repository's existing tags derive a shape that
    /// differs from the default `release` would otherwise apply.
    pub(super) tag_format: Option<ReadableTemplate>,
    /// Carried from a source tool's own setting when it differs from what
    /// `ci version-pr` writes anyway.
    pub(super) commit_message: Option<String>,
}

/// oakum's `private-packages` opt-in (ADR-0027) as the writer needs it:
/// [`oakum::config::PrivatePackages`] is what the parser produces and cannot
/// be built here.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct PrivatePackages {
    pub(super) version: bool,
    pub(super) tag: bool,
}

impl PrivatePackages {
    /// The axes this value opts in, so a report can name what one source file
    /// contributed rather than what the whole migration writes.
    pub(super) fn axis_names(self) -> Vec<&'static str> {
        [("version", self.version), ("tag", self.tag)]
            .into_iter()
            .filter_map(|(name, on)| on.then_some(name))
            .collect()
    }

    /// Whether the setting says anything an absent table does not.
    pub(super) const fn any(self) -> bool {
        self.version || self.tag
    }

    pub(super) const fn union(self, other: Self) -> Self {
        Self {
            version: self.version || other.version,
            tag: self.tag || other.tag,
        }
    }

    /// The line `_config.toml` carries. One value produces it, so the report
    /// and the file cannot describe the opt-in differently.
    pub(super) fn toml_line(self) -> String {
        format!(
            "private-packages = {{ version = {}, tag = {} }}",
            self.version, self.tag
        )
    }
}

/// What one `_schema.json` write did. `init`, `migrate`, and `upgrade`
/// share the currency test (byte equality with the bundled schema) and each
/// says the outcome in its own words.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SchemaOutcome {
    Created,
    Replaced,
    Unchanged,
}

/// How `_schema.json` stands against the bundled schema, by bytes. A file
/// that cannot be read counts as stale: the rename replaces it without
/// reading, and reports if it cannot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum SchemaState {
    Absent,
    Current,
    Stale,
}

pub(super) fn schema_state(dir: &Dir, path: &Path) -> SchemaState {
    read_schema_state(dir, path).unwrap_or(SchemaState::Stale)
}

/// [`schema_state`] with the unreadable case kept apart, for a reader that
/// replaces nothing and so must not call an unread file stale. The open is
/// non-blocking and the type checked on the handle, so a FIFO cannot stall it.
fn read_schema_state(dir: &Dir, path: &Path) -> io::Result<SchemaState> {
    let mut file = match open_read_only(dir, path) {
        Ok(file) => file,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(SchemaState::Absent),
        Err(err) => return Err(err),
    };
    if !file.metadata()?.is_file() {
        return Err(io::Error::other("not a regular file"));
    }
    let mut existing = Vec::new();
    file.read_to_end(&mut existing)?;
    Ok(if existing == config::schema_json().as_bytes() {
        SchemaState::Current
    } else {
        SchemaState::Stale
    })
}

/// What `check` says about the committed schema, or `None` when there is
/// nothing to say. The binary validates config on every run, so a stale or
/// missing schema costs editor hints only and never the exit code (ADR-0038).
/// An existing file is compared whatever the `#:schema` line says, since
/// `upgrade` keeps it either way; only a missing one needs the line to name
/// it before it is worth a word. Under pins that agree on another version this
/// binary's schema is not the expected one, so nothing is compared; under pins
/// `upgrade` would refuse, the remedy names settling them first.
pub(super) fn schema_note(
    repo: &Repository,
    names_committed_schema: bool,
    pins: &Standing<'_>,
) -> Option<String> {
    // Resolved as the config loader resolves it, so a `.changeset` it followed
    // is not one this look refuses.
    let state = resolve_capability_path(repo.dir(), repo.path(), Path::new(".changeset"))
        .and_then(|changeset| resolve_sibling_write_target(repo, &changeset, "_schema.json"))
        .map_err(|err| err.to_string())
        .and_then(|path| read_schema_state(repo.dir(), &path).map_err(|err| err.to_string()));
    let binary = env!("CARGO_PKG_VERSION");
    let remedy = |verb: &str| match pins {
        Standing::Unsettled => format!(
            "settle the install pins first (the install pin look says how), \
             then run `oakum upgrade` to {verb} it"
        ),
        Standing::Settled | Standing::Elsewhere(_) => format!("run `oakum upgrade` to {verb} it"),
    };
    match (state, pins) {
        (Ok(SchemaState::Absent), _) if !names_committed_schema => None,
        (Err(why), _) => Some(format!(
            "`{SCHEMA_REL}` could not be read, so whether it is current is unknown: {why}"
        )),
        (Ok(_), Standing::Elsewhere(pinned)) => Some(format!(
            "`{SCHEMA_REL}` was not compared: this binary is oakum {binary} and the install pin is {pinned}, so the pinned oakum's `check` decides whether it is current"
        )),
        (Ok(SchemaState::Current), _) => None,
        (Ok(SchemaState::Stale), _) => Some(format!(
            "`{SCHEMA_REL}` differs from what oakum {binary} generates, so editor hints may be out of date; {}",
            remedy("regenerate")
        )),
        (Ok(SchemaState::Absent), _) => Some(format!(
            "`{SCHEMA_REL}` is missing, though the `#:schema` line in `{CONFIG_PATH}` names it; {}",
            remedy("write")
        )),
    }
}

/// Write the bundled schema at `path` unless `state` says it already holds
/// it. Both are the caller's (`upgrade` resolves `path` through symlinks),
/// so the pending line, the write, and the report all rest on one look.
///
/// # Errors
///
/// A failed write.
pub(super) fn write_schema(
    dir: &Dir,
    path: &Path,
    state: SchemaState,
) -> Result<SchemaOutcome, Box<dyn std::error::Error>> {
    let outcome = match state {
        SchemaState::Current => return Ok(SchemaOutcome::Unchanged),
        SchemaState::Stale => SchemaOutcome::Replaced,
        SchemaState::Absent => SchemaOutcome::Created,
    };
    write_file_via_rename(dir, path, &config::schema_json())?;
    Ok(outcome)
}

/// Every README an earlier release's `init` wrote, byte for byte: v0.1.0
/// through v0.1.3 wrote a string inside `init.rs`, and each later file is
/// `changeset-readme.md` at the release that first shipped it. When that file
/// changes, the text it replaces joins this list, or `upgrade` leaves it in
/// repositories as a user's own README.
const SHIPPED_READMES: [&str; 6] = [
    include_str!("changeset-readme-shipped/v0.1.0.txt"),
    include_str!("changeset-readme-shipped/v0.1.4.txt"),
    include_str!("changeset-readme-shipped/v0.2.0.txt"),
    include_str!("changeset-readme-shipped/v0.3.0.txt"),
    include_str!("changeset-readme-shipped/v0.9.2.txt"),
    include_str!("changeset-readme-shipped/v0.10.0.txt"),
];

/// Whether the README present in `.changeset/` is oakum's. A copy
/// byte-identical to the bundled one is (a run that stopped before
/// `_config.toml` leaves exactly that), so the uninstall line names it; one
/// identical to an earlier release's is oakum's too, and out of date.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ReadmeState {
    Absent,
    Ours,
    Stale,
    Theirs,
}

/// # Errors
///
/// A README that is a directory or symlink, or one that cannot be read.
fn readme_state(dir: &Dir) -> Result<ReadmeState, Box<dyn std::error::Error>> {
    if !regular_file_exists(dir, README_REL)? {
        return Ok(ReadmeState::Absent);
    }
    Ok(classify_readme(&dir.read(README_REL)?))
}

/// A checkout that turned LF into CRLF (`core.autocrlf`) still holds oakum's text.
fn classify_readme(bytes: &[u8]) -> ReadmeState {
    let text = String::from_utf8_lossy(bytes).replace("\r\n", "\n");
    if text == README {
        ReadmeState::Ours
    } else if SHIPPED_READMES.contains(&text.as_str()) {
        ReadmeState::Stale
    } else {
        ReadmeState::Theirs
    }
}

/// Every failure to look is `false`: `upgrade` must not fail over a README it
/// cannot claim and so leaves alone.
fn holds_stale_readme(dir: &Dir, path: &Path) -> bool {
    let Ok(mut file) = open_read_only(dir, path) else {
        return false;
    };
    if !file.metadata().is_ok_and(|meta| meta.is_file()) {
        return false;
    }
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes).is_ok() && classify_readme(&bytes) == ReadmeState::Stale
}

/// `upgrade`'s README step: an earlier release's text is replaced with this
/// one's; a user's own README, or none, is left alone.
///
/// # Errors
///
/// A README that held an earlier release's text and could not be replaced.
pub(super) fn refresh_readme(dir: &Dir, path: &Path) -> Result<bool, Box<dyn std::error::Error>> {
    if !holds_stale_readme(dir, path) {
        return Ok(false);
    }
    write_file_via_rename(dir, path, README)?;
    Ok(true)
}

/// What `check` says about the README: only that an earlier release's text
/// can be refreshed, since a user's own README is theirs to keep.
pub(super) fn readme_note(repo: &Repository, pins: &Standing<'_>) -> Option<String> {
    if matches!(pins, Standing::Elsewhere(_)) {
        return None;
    }
    let path = resolve_capability_path(repo.dir(), repo.path(), Path::new(".changeset"))
        .and_then(|changeset| resolve_sibling_write_target(repo, &changeset, "README.md"))
        .ok()?;
    holds_stale_readme(repo.dir(), &path).then(|| {
        format!(
            "`{README_REL}` is the text an earlier oakum wrote; run `oakum upgrade` to refresh it"
        )
    })
}

/// The owned files as they stand before a write, probed once so the
/// pending line, the writes, and the uninstall line rest on one look.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct OwnedPlan {
    pub(super) schema: SchemaState,
    pub(super) readme: ReadmeState,
}

impl OwnedPlan {
    /// Refuses a README or schema that is a directory or symlink, so that
    /// surfaces before anything is printed or written.
    ///
    /// # Errors
    ///
    /// A path that exists but is not a regular file, or cannot be read.
    pub(super) fn probe(dir: &Dir) -> Result<Self, Box<dyn std::error::Error>> {
        let schema = if regular_file_exists(dir, SCHEMA_REL)? {
            schema_state(dir, Path::new(SCHEMA_REL))
        } else {
            SchemaState::Absent
        };
        Ok(Self {
            schema,
            readme: readme_state(dir)?,
        })
    }

    /// Every file oakum owns once the write lands: what the uninstall line
    /// names. A README that was already oakum's counts; a user's does not.
    pub(super) fn owned_after_write(self) -> Vec<&'static str> {
        let mut written = vec![SCHEMA_REL];
        if self.readme != ReadmeState::Theirs {
            written.push(README_REL);
        }
        written.push(CONFIG_PATH);
        written
    }
}

pub(super) fn write_owned_files(
    dir: &Dir,
    plan: OwnedPlan,
    settings: ConfigSettings,
    records: &mut Records,
) -> Result<OwnedWrites, Box<dyn std::error::Error>> {
    let schema = write_schema(dir, Path::new(SCHEMA_REL), plan.schema)?;
    records.record(&format!(
        "{} {SCHEMA_REL}",
        match schema {
            SchemaOutcome::Created => "created",
            SchemaOutcome::Replaced => "replaced",
            SchemaOutcome::Unchanged => "unchanged",
        }
    ));
    match plan.readme {
        ReadmeState::Absent => {
            write_file_exclusive(dir, Path::new(README_REL), README)?;
            records.record(&format!("created {README_REL}"));
        }
        ReadmeState::Stale => {
            write_file_via_rename(dir, Path::new(README_REL), README)?;
            records.record(&format!("replaced {README_REL}"));
        }
        ReadmeState::Ours | ReadmeState::Theirs => {}
    }
    write_file_exclusive(dir, Path::new(CONFIG_PATH), &config_body(settings))?;
    records.record(&format!("created {CONFIG_PATH}"));
    Ok(OwnedWrites {
        written: plan.owned_after_write(),
    })
}

/// The lines a write command hands over, delivered as each one is ready so a
/// failure part-way through leaves an accurate record. A refused delivery is
/// held rather than returned: a reader who went away is no reason to leave
/// the directory half-written, so the remaining writes still happen and the
/// refusal becomes the verdict at [`Records::finish`], naming every line that
/// never arrived. A write that fails after a refusal is the verdict, and
/// [`Records::abandon`] carries the refusal into it.
#[derive(Default)]
pub(super) struct Records {
    refused: Option<(String, std::io::Error)>,
    undelivered: Vec<String>,
}

impl Records {
    /// A `created`/`wrote` line, or a summary line: the record of a write
    /// that already landed.
    pub(super) fn record(&mut self, line: &str) {
        self.deliver(&format!("the record `{line}`"), line);
    }

    /// `what` names the text in the verdict; `text` is what stdout receives.
    pub(super) fn deliver(&mut self, what: &str, text: &str) {
        if self.refused.is_some() {
            self.undelivered.push(what.to_owned());
            return;
        }
        if let Err(err) = deliver_out(text) {
            self.refused = Some((what.to_owned(), err));
        }
    }

    /// A write failed after these records: its error is the verdict, and the
    /// refusal is named inside it so the lines that landed are not lost.
    pub(super) fn abandon(
        &mut self,
        err: impl Into<Box<dyn std::error::Error>>,
    ) -> Box<dyn std::error::Error> {
        let err = err.into();
        let Err(refusal) = std::mem::take(self).finish() else {
            return err;
        };
        Box::new(CliError::new(format!(
            "{}; before that, {}",
            CliError::from_boxed(err).detail(),
            refusal.detail()
        )))
    }

    pub(super) fn finish(self) -> Result<(), CliError> {
        let Some((mut what, err)) = self.refused else {
            return Ok(());
        };
        if !self.undelivered.is_empty() {
            what.push_str(" and, after it, ");
            what.push_str(&self.undelivered.join(", "));
        }
        Err(CliError::undelivered(what, &err))
    }
}

/// Every file oakum now owns after [`write_owned_files`], including a
/// `_schema.json` it replaced or found current: what the uninstall line
/// must name.
pub(super) struct OwnedWrites {
    pub(super) written: Vec<&'static str>,
}

/// An owned file `migrate` can put back after it went missing. `_config.toml`
/// carries user settings and is never replaced, so it is not one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum RestorableFile {
    Schema,
    Readme,
}

impl RestorableFile {
    const ALL: [Self; 2] = [Self::Schema, Self::Readme];

    pub(super) const fn rel(self) -> &'static str {
        match self {
            Self::Schema => SCHEMA_REL,
            Self::Readme => README_REL,
        }
    }

    fn body(self) -> String {
        match self {
            Self::Schema => config::schema_json(),
            Self::Readme => String::from(README),
        }
    }
}

/// The owned files a migrated repository no longer has.
pub(super) fn missing_owned_files(
    dir: &Dir,
) -> Result<Vec<RestorableFile>, Box<dyn std::error::Error>> {
    let mut missing = Vec::new();
    for file in RestorableFile::ALL {
        if !regular_file_exists(dir, file.rel())? {
            missing.push(file);
        }
    }
    Ok(missing)
}

/// Exclusive, so a file that appeared since the look is refused, not replaced.
pub(super) fn restore_owned_file(dir: &Dir, file: RestorableFile) -> io::Result<()> {
    write_file_exclusive(dir, Path::new(file.rel()), &file.body())
}

/// The `commit-message` line as the file receives it: a TOML basic string with
/// the two characters TOML gives meaning escaped. Shared with the report, so the
/// line `migrate` announces and the line it writes cannot differ — announcing
/// the decoded value printed `commit-message = "cut "the" packages"`, which was
/// neither.
///
/// A message reaching here has been refused for control characters upstream, so
/// no other escape applies.
pub(super) fn commit_message_line(message: &str) -> String {
    format!(
        "commit-message = \"{}\"",
        message.replace('\\', "\\\\").replace('"', "\\\"")
    )
}

/// `private-packages` is written as an inline table, the shape ADR-0027
/// documents. A `[private-packages]` header would have to follow every scalar
/// or swallow the ones after it (`okm-404.12`); an inline table has no such
/// ordering to get wrong.
fn config_body(settings: ConfigSettings) -> String {
    let ConfigSettings {
        change_files,
        conventional_commits,
        versioning,
        private_packages,
        tag_format,
        commit_message,
    } = settings;
    // `ReadableTemplate` can only hold one of the four shapes `tag_shape`
    // recognizes, none of which carries anything TOML would have to escape.
    let tag_format = tag_format.map_or_else(String::new, |template| {
        format!("tag-format = \"{}\"\n", template.as_str())
    });
    let private = if private_packages.any() {
        format!("{}\n", private_packages.toml_line())
    } else {
        String::new()
    };
    let commit_message = commit_message
        .as_deref()
        .map_or_else(String::new, |message| {
            format!("{}\n", commit_message_line(message))
        });
    format!(
        "#:schema ./_schema.json\n\
change-files = {change_files}\n\
conventional-commits = {conventional_commits}\n\
versioning = \"{versioning}\"\n\
{tag_format}{private}{commit_message}"
    )
}

fn regular_file_exists(dir: &Dir, path: &str) -> Result<bool, Box<dyn std::error::Error>> {
    match dir.symlink_metadata(path) {
        Ok(meta) if meta.is_file() => Ok(true),
        Ok(meta) if meta.file_type().is_symlink() => Err(Box::new(CliError::new(format!(
            "`{path}` is a symlink; replace it with a regular file or remove it so oakum can write its own"
        )))),
        Ok(_) => Err(Box::new(CliError::new(format!(
            "`{path}` exists and is not a regular file"
        )))),
        Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false),
        Err(err) => Err(Box::new(CliError::new(format!(
            "failed to inspect `{path}`: {err}"
        )))),
    }
}

#[cfg(test)]
mod records {
    use super::Records;

    fn refused(what: &str) -> Records {
        Records {
            refused: Some((
                what.to_owned(),
                std::io::Error::from(std::io::ErrorKind::BrokenPipe),
            )),
            undelivered: Vec::new(),
        }
    }

    #[test]
    fn a_lone_refusal_names_only_itself() {
        let verdict = refused("the record `created x`").finish().unwrap_err();
        assert_eq!(
            verdict.detail(),
            "the record `created x` could not be delivered to stdout: broken pipe"
        );
    }

    #[test]
    fn lines_after_a_refusal_are_named_in_order() {
        let mut records = refused("the record `created x`");
        records.deliver("the workflow", "workflow text");
        records.record("created y");
        let verdict = records.finish().unwrap_err();
        assert_eq!(
            verdict.detail(),
            "the record `created x` and, after it, the workflow, the record `created y` could not be delivered to stdout: broken pipe"
        );
    }

    #[test]
    fn a_write_error_after_a_refusal_names_both() {
        let mut records = refused("the record `wrote a`");
        records.record("created b");
        let err = records.abandon(std::io::Error::other("failed to create c"));
        assert_eq!(
            err.to_string(),
            "failed to create c; before that, the record `wrote a` and, after it, the record `created b` could not be delivered to stdout: broken pipe"
        );
    }

    #[test]
    fn a_write_error_with_nothing_refused_is_itself() {
        let err = Records::default().abandon(std::io::Error::other("failed to create c"));
        assert_eq!(err.to_string(), "failed to create c");
    }

    #[test]
    fn nothing_refused_is_ok() {
        let mut records = Records::default();
        records.record("created x");
        assert!(records.finish().is_ok());
    }
}

#[cfg(test)]
mod readme {
    use super::README;

    /// ADR-0031 puts its two lint settings in the README `init` writes.
    #[test]
    fn the_readme_names_both_lint_settings() {
        for setting in [
            "Turn MD041 off for `.changeset/*.md`",
            "MD024's `siblings_only`",
        ] {
            assert!(README.contains(setting), "{setting}");
        }
    }
}

#[cfg(test)]
mod written_config {
    use super::{config_body, ConfigSettings, PrivatePackages};
    use oakum::plan::Versioning;

    fn body(private_packages: PrivatePackages) -> String {
        config_body(ConfigSettings {
            change_files: true,
            conventional_commits: false,
            versioning: Versioning::Semver,
            private_packages,
            tag_format: None,
            commit_message: None,
        })
    }

    #[test]
    fn an_opted_in_axis_round_trips_through_the_config_loader() {
        for private_packages in [
            PrivatePackages {
                version: true,
                tag: true,
            },
            PrivatePackages {
                version: true,
                tag: false,
            },
            PrivatePackages {
                version: false,
                tag: true,
            },
        ] {
            let written = body(private_packages);
            let parsed = oakum::config::parse(&written).expect("written config parses");
            assert_eq!(
                parsed.private_packages().version(),
                private_packages.version,
                "{written}"
            );
            assert_eq!(
                parsed.private_packages().tag(),
                private_packages.tag,
                "{written}"
            );
            assert_eq!(parsed.versioning(), Versioning::Semver, "{written}");
            assert!(parsed.change_files(), "{written}");
            assert!(!parsed.conventional_commits(), "{written}");
        }
    }

    #[test]
    fn the_default_writes_no_private_packages_key() {
        let written = body(PrivatePackages::default());
        assert!(!written.contains("private-packages"), "{written}");
        let parsed = oakum::config::parse(&written).expect("written config parses");
        assert!(!parsed.private_packages().version());
        assert!(!parsed.private_packages().tag());
    }

    /// An inline table cannot swallow the scalars around it; a
    /// `[private-packages]` header placed before them would (`okm-404.12`).
    #[test]
    fn the_carried_setting_is_an_inline_table_on_one_line() {
        let written = body(PrivatePackages {
            version: true,
            tag: true,
        });
        assert!(
            written.contains("\nprivate-packages = { version = true, tag = true }\n"),
            "{written}"
        );
        assert!(!written.contains("[private-packages]"), "{written}");
    }
}

#[cfg(test)]
mod schema_seam {
    use super::{schema_state, write_schema, SchemaOutcome, SCHEMA_REL};
    use crate::test_fixture::Fixture;
    use cap_std::fs::Dir;
    use std::path::Path;

    fn scratch(label: &str) -> Fixture {
        let root = Fixture::new("schema-seam", label);
        std::fs::create_dir_all(root.join(".changeset")).expect("scratch");
        root
    }

    #[test]
    fn one_write_says_created_replaced_or_unchanged() {
        let root = scratch("outcomes");
        let dir = Dir::open_ambient_dir(&root, cap_std::ambient_authority()).expect("dir");
        let path = Path::new(SCHEMA_REL);
        assert_eq!(
            write_schema(&dir, path, schema_state(&dir, path)).expect("first"),
            SchemaOutcome::Created
        );
        assert_eq!(
            write_schema(&dir, path, schema_state(&dir, path)).expect("again"),
            SchemaOutcome::Unchanged
        );
        std::fs::write(root.join(SCHEMA_REL), "{\"stale\": true}\n").expect("stale");
        assert_eq!(
            write_schema(&dir, path, schema_state(&dir, path)).expect("stale"),
            SchemaOutcome::Replaced
        );
        assert_eq!(
            std::fs::read_to_string(root.join(SCHEMA_REL)).expect("read"),
            oakum::config::schema_json()
        );
    }
}