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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! Containment-safe filesystem primitives over a repository [`Dir`].
//!
//! Identity is the held capability, not the ambient path it was opened from.
//! Subprocess callers that still need a path must go through
//! [`super::repository::Repository::ambient_path`].

use std::collections::VecDeque;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};

use cap_std::fs::{Dir, File, OpenOptions};

use super::consume::{is_consume_leftover, CONSUME_CLAIM};
use super::say_out;
use super::CliError;

/// Repo-relative paths in CLI output use `/`, matching git. Replace the
/// platform separator, not a literal `\` in a Unix filename.
pub(super) fn repo_path_display(path: &Path) -> String {
    path.display()
        .to_string()
        .replace(std::path::MAIN_SEPARATOR, "/")
}

/// The mark every staging name carries (the writer below interpolates it); a
/// hard kill between `create_new` and the rename leaves one behind, and
/// nothing sweeps it, so the commands name it instead.
pub(super) const STAGING_MARK: &str = ".oakum-write.";

/// The mark a consume leaves instead: a bump file `version` set aside, or the
/// marker it holds while it writes and consumes. Its own mark because the
/// recovery differs — removing one can lose a bump the changelog lacks.
pub(super) const CONSUME_MARK: &str = ".oakum-consume.";

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum StagingKind {
    Write,
    Consume,
}

/// A staging name, `.<target><mark><pid>.<nanos>.<attempt>`, split at its mark.
#[derive(Debug)]
pub(super) struct StagingName<'a> {
    pub(super) target: &'a str,
    pub(super) kind: StagingKind,
    pub(super) tail: &'a str,
}

impl StagingName<'_> {
    fn pid(&self) -> Option<u32> {
        self.tail.split('.').next()?.parse().ok()
    }
}

/// The last mark decides, because the target's own name may carry either: a
/// write's staging copy of the consume marker is a write. A mark may start at
/// the leading `.`, which leaves the target empty.
pub(super) fn parse_staging_name(name: &str) -> Option<StagingName<'_>> {
    if !name.starts_with('.') {
        return None;
    }
    let write = name
        .rfind(STAGING_MARK)
        .map(|at| (at, STAGING_MARK, StagingKind::Write));
    let consume = name
        .rfind(CONSUME_MARK)
        .map(|at| (at, CONSUME_MARK, StagingKind::Consume));
    let (at, mark, kind) = write
        .into_iter()
        .chain(consume)
        .max_by_key(|(at, ..)| *at)?;
    Some(StagingName {
        target: name.get(1..at).unwrap_or_default(),
        kind,
        tail: &name[at + mark.len()..],
    })
}

pub(super) fn is_staging_name(name: &str) -> bool {
    parse_staging_name(name).is_some()
}

/// A staging name a consume left: a set-aside bump file or the consume marker.
pub(super) fn is_consume_staging_name(name: &str) -> bool {
    parse_staging_name(name).is_some_and(|staging| staging.kind == StagingKind::Consume)
}

/// Staging files left under `sub` by an interrupted write, as `sub/name`
/// (`name` alone for `.`).
///
/// # Errors
///
/// A listing that cannot be read; a missing `sub` is an empty list.
pub(super) fn stray_staging_files(
    dir: &Dir,
    sub: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let entries = match dir.read_dir(sub) {
        Ok(entries) => entries,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(err) => {
            return Err(Box::new(CliError::new(format!(
                "failed to read `{sub}`: {err}"
            ))));
        }
    };
    let mut strays = Vec::new();
    for entry in entries {
        let entry = entry.map_err(|err| CliError::new(format!("failed to read `{sub}`: {err}")))?;
        // The writer only ever creates regular files; a directory or symlink
        // with the name is not oakum's to speak for.
        let is_file = entry.metadata().is_ok_and(|meta| meta.is_file());
        if let Some(name) = entry.file_name().to_str() {
            if is_file && is_staging_name(name) {
                strays.push(if sub == "." {
                    name.to_owned()
                } else {
                    format!("{sub}/{name}")
                });
            }
        }
    }
    strays.sort();
    Ok(strays)
}

/// Staging files under `sub` that this process wrote. Telling someone to remove
/// a concurrent run's file is worse than staying quiet about it.
///
/// # Errors
///
/// A listing that cannot be read; a missing `sub` is an empty list.
pub(super) fn own_staging_files(
    dir: &Dir,
    sub: &str,
) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let pid = std::process::id();
    Ok(stray_staging_files(dir, sub)?
        .into_iter()
        .filter(|path| {
            parse_staging_name(path.rsplit('/').next().unwrap_or(path))
                .and_then(|staging| staging.pid())
                == Some(pid)
        })
        .collect())
}

/// The one line every command prints for a stray. An interrupted write and a
/// run still in progress leave the same file, so it states what was seen and
/// conditions the advice on no run being in progress. A consume's leftovers
/// are not removable on sight: `version` reads them to say how to recover.
pub(super) fn stray_staging_message(path: &str) -> String {
    let name = path.rsplit('/').next().unwrap_or(path);
    if is_consume_leftover(name) {
        format!("`{path}` is {CONSUME_CLAIM}")
    } else {
        format!("`{path}` is {STAGING_CLAIM}")
    }
}

/// The claim both wordings make, so a list entry and a standalone line cannot
/// drift into saying different things about the same file.
pub(super) const STAGING_CLAIM: &str =
    "an oakum staging file; if no oakum run is in progress, remove it";

/// Print one line per stray staging file under `.changeset/`. Runs before a
/// command decides whether it has anything else to do, so the
/// already-initialized and already-migrated paths report them too.
///
/// # Errors
///
/// A listing that cannot be read.
pub(super) fn report_stray_staging(dir: &Dir) -> Result<(), Box<dyn std::error::Error>> {
    for path in stray_staging_files(dir, ".changeset")? {
        say_out(&stray_staging_message(&path));
    }
    Ok(())
}

/// Replace `target` via a sibling temp file so rename stays on one filesystem
/// (no EXDEV across mounts). Staging uses `create_new` so a pre-existing
/// path cannot redirect the write. On collision, pick another name rather
/// than removing the entry; sweeping orphans would reintroduce that race.
///
/// The staged copy takes the replaced file's permissions; owner and inode do
/// not survive a rename, and a symlink at `target` is replaced by a regular
/// file. [`write_landing`] is the variant that follows one.
pub(super) fn write_file_via_rename(
    dir: &Dir,
    target: &Path,
    body: &str,
) -> Result<(), Box<dyn std::error::Error>> {
    stage_and_replace(dir, target, body).map_err(|failure| failure.into_error(target).into())
}

/// [`write_file_via_rename`] through a symlink, returning the file the text
/// landed in: the file the link names gets the text, staged beside it, and
/// the link stays. Where that cannot be done safely (a link into a `.git`,
/// one that cannot be followed, or a file that refuses the new text) the link
/// is replaced by a regular file, and stderr says so. A link whose file
/// another write of the same run also names (`shared`) is replaced too: the
/// writers each render from the text they read, so following both would keep
/// only the last one's edit.
pub(super) fn write_landing(
    dir: &Dir,
    target: &Path,
    body: &str,
    shared: bool,
) -> Result<Landing, Box<dyn std::error::Error>> {
    let unfollowed = match link_target(dir, target) {
        Ok(None) => None,
        Ok(Some(resolved)) if shared => Some(Unfollowed {
            names: Some(resolved),
            why: String::from("another file this run writes names the same file"),
        }),
        // Any failure leaves the named file as it was, so replacing the link
        // instead is what a run that never followed it would have done.
        Ok(Some(resolved)) => match stage_and_replace(dir, &resolved, body) {
            Ok(()) => return Ok(Landing::plain(resolved)),
            Err(failure) => Some(Unfollowed {
                why: failure.into_error(&resolved).to_string(),
                names: Some(resolved),
            }),
        },
        Err(unfollowed) => Some(unfollowed),
    };
    // Read while the link is still there: the replace below removes it.
    let replaced_link = unfollowed.as_ref().map(|_| ReplacedLink {
        target: dir.read_link_contents(target).ok(),
    });
    if let Err(failure) = stage_and_replace(dir, target, body) {
        let err = failure.into_error(target);
        return Err(Box::new(match unfollowed {
            Some(unfollowed) => CliError::new(format!(
                "{err}, after not following it as a link: {}",
                unfollowed.why
            )),
            None => err,
        }));
    }
    if let Some(Unfollowed { names, why }) = unfollowed {
        let shown = repo_path_display(target);
        super::say_err(&match names {
            Some(names) => {
                let names = repo_path_display(&names);
                format!(
                    "note: `{shown}` is a link to `{names}` that oakum did not follow ({why}), \
                     so `{shown}` was replaced by a regular file holding the new text and \
                     `{names}` did not get it"
                )
            }
            None => format!(
                "note: `{shown}` is a link oakum did not follow ({why}), so it was replaced by \
                 a regular file holding the new text"
            ),
        });
    }
    Ok(Landing {
        at: target.to_path_buf(),
        replaced_link,
    })
}

/// Where [`write_landing`] put the text, and the link it replaced to get there.
pub(super) struct Landing {
    pub(super) at: PathBuf,
    pub(super) replaced_link: Option<ReplacedLink>,
}

impl Landing {
    pub(super) const fn plain(at: PathBuf) -> Self {
        Self {
            at,
            replaced_link: None,
        }
    }
}

/// A link replaced by a regular file. `target` is the link's text, when it
/// could be read.
pub(super) struct ReplacedLink {
    pub(super) target: Option<PathBuf>,
}

/// Why a link is not followed, and the file it names when that is known.
pub(super) struct Unfollowed {
    names: Option<PathBuf>,
    why: String,
}

/// The file a symlink at `target` names, inside the repository. `Ok(None)` for
/// anything that is not a symlink.
pub(super) fn link_target(dir: &Dir, target: &Path) -> Result<Option<PathBuf>, Unfollowed> {
    match dir.symlink_metadata(target) {
        Ok(meta) if meta.file_type().is_symlink() => {}
        _ => return Ok(None),
    }
    let resolved = dir.canonicalize(target).map_err(|err| Unfollowed {
        names: None,
        why: format!("it could not be followed: {err}"),
    })?;
    // Any `.git`, nested or differently cased (macOS folds case), is git's.
    if resolved.components().any(
        |component| matches!(component, Component::Normal(name) if name.eq_ignore_ascii_case(".git")),
    ) {
        return Err(Unfollowed {
            names: Some(resolved),
            why: String::from("it names a file inside `.git`"),
        });
    }
    Ok(Some(resolved))
}

/// The directory a followed link's staging file lands in, for the looks that
/// sweep staging leftovers; `None` when `path` is not a link oakum follows.
pub(super) fn link_staging_dir(dir: &Dir, path: &Path) -> Option<String> {
    let resolved = link_target(dir, path).ok()??;
    Some(match resolved.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => repo_path_display(parent),
        _ => String::from("."),
    })
}

/// Which step of [`stage_and_replace`] failed.
enum Failure {
    Stage(io::Error),
    Write(io::Error),
    Replace(io::Error),
}

impl Failure {
    fn into_error(self, target: &Path) -> CliError {
        let (step, err) = match self {
            Self::Stage(err) | Self::Write(err) => ("stage", err),
            Self::Replace(err) => ("replace", err),
        };
        CliError::new(format!(
            "failed to {step} `{}`: {err}",
            repo_path_display(target)
        ))
    }
}

fn stage_and_replace(dir: &Dir, target: &Path, body: &str) -> Result<(), Failure> {
    let permissions = dir.metadata(target).ok().map(|meta| meta.permissions());
    let (parent, file_name) =
        staging_parts(target).map_err(|err| Failure::Stage(io::Error::other(err.to_string())))?;
    let mut attempt: u32 = 0;
    let (tmp, mut staged) = loop {
        let candidate = staging_candidate(&parent, file_name, STAGING_MARK, attempt);
        match dir.open_with(&candidate, OpenOptions::new().create_new(true).write(true)) {
            Ok(file) => break (candidate, file),
            Err(err) if err.kind() == io::ErrorKind::AlreadyExists && attempt < 16 => {
                attempt += 1;
            }
            Err(err) => return Err(Failure::Stage(err)),
        }
    };
    staged.write_all(body.as_bytes()).map_err(|err| {
        let _ = dir.remove_file(&tmp);
        Failure::Write(err)
    })?;
    // A filesystem without modes (vfat) refuses this; the text matters more.
    if let Some(Err(err)) = permissions.map(|permissions| staged.set_permissions(permissions)) {
        super::say_err(&format!(
            "warning: `{}` was written with default permissions, since its old ones could not be kept: {err}",
            repo_path_display(target)
        ));
    }
    drop(staged);
    dir.rename(&tmp, dir, target).map_err(|err| {
        let _ = dir.remove_file(&tmp);
        Failure::Replace(err)
    })
}

/// Move `target` to a fresh staging name beside it and return that name. The
/// bytes never exist only in memory: a run killed partway leaves a file the
/// staging looks name, recoverable by renaming it back.
///
/// The name is claimed with a hard link, which fails rather than replace an
/// existing file. Where links are unsupported it falls back to a free-name
/// check and a rename, two steps the pid and nanoseconds in the name guard.
pub(super) fn stage_aside(dir: &Dir, target: &Path) -> Result<PathBuf, CliError> {
    let (parent, file_name) = staging_parts(target)?;
    for attempt in 0..16 {
        let candidate = staging_candidate(&parent, file_name, CONSUME_MARK, attempt);
        match dir.hard_link(target, dir, &candidate) {
            Ok(()) => {
                return match dir.remove_file(target) {
                    Ok(()) => Ok(candidate),
                    Err(err) => {
                        let _ = dir.remove_file(&candidate);
                        Err(stage_aside_failed(target, &err))
                    }
                };
            }
            Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {}
            Err(_) => return stage_aside_by_rename(dir, target, &parent, file_name, attempt),
        }
    }
    Err(stage_names_taken(target))
}

fn stage_aside_by_rename(
    dir: &Dir,
    target: &Path,
    parent: &Path,
    file_name: &str,
    first: u32,
) -> Result<PathBuf, CliError> {
    for attempt in first..16 {
        let candidate = staging_candidate(parent, file_name, CONSUME_MARK, attempt);
        match dir.symlink_metadata(&candidate) {
            Ok(_) => continue,
            Err(err) if err.kind() == io::ErrorKind::NotFound => {}
            Err(err) => {
                return Err(CliError::new(format!(
                    "failed to check staging name `{}` for `{}`: {err}",
                    repo_path_display(&candidate),
                    repo_path_display(target)
                )));
            }
        }
        return dir
            .rename(target, dir, &candidate)
            .map(|()| candidate)
            .map_err(|err| stage_aside_failed(target, &err));
    }
    Err(stage_names_taken(target))
}

fn stage_names_taken(target: &Path) -> CliError {
    CliError::new(format!(
        "failed to move `{}` aside: every staging name was taken",
        repo_path_display(target)
    ))
}

fn stage_aside_failed(target: &Path, err: &io::Error) -> CliError {
    CliError::new(format!(
        "failed to move `{}` aside: {err}",
        repo_path_display(target)
    ))
}

fn staging_parts(target: &Path) -> Result<(PathBuf, &str), CliError> {
    let file_name = target
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| CliError::new("write target has no file name"))?;
    let parent = target.parent().map(Path::to_path_buf).unwrap_or_default();
    Ok((parent, file_name))
}

/// Longest stretch of the target's name a staging name carries, so the
/// staging suffix fits a 255-byte name limit for any target that fits it.
const STAGING_NAME_KEEP: usize = 200;

pub(super) fn staging_candidate(
    parent: &Path,
    file_name: &str,
    mark: &str,
    attempt: u32,
) -> PathBuf {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |elapsed| elapsed.subsec_nanos());
    let mut keep = file_name.len().min(STAGING_NAME_KEEP);
    while !file_name.is_char_boundary(keep) {
        keep -= 1;
    }
    parent.join(format!(
        ".{}{mark}{}.{nanos}.{attempt}",
        &file_name[..keep],
        std::process::id()
    ))
}

/// `create_new` so a file that appears between the check and the write is not replaced.
pub(super) fn write_file_exclusive(dir: &Dir, target: &Path, body: &str) -> io::Result<()> {
    let mut file = dir
        .open_with(target, OpenOptions::new().create_new(true).write(true))
        .map_err(|err| {
            let shown = repo_path_display(target);
            // A dangling symlink refuses `create_new` as "File exists", which
            // names neither the link nor what is wrong with it.
            let dangling = err.kind() == io::ErrorKind::AlreadyExists
                && dir
                    .symlink_metadata(target)
                    .is_ok_and(|meta| meta.file_type().is_symlink())
                && dir
                    .metadata(target)
                    .is_err_and(|err| err.kind() == io::ErrorKind::NotFound);
            let message = if dangling {
                format!("`{shown}` is a symlink whose target does not exist")
            } else {
                format!("failed to create `{shown}`: {err}")
            };
            io::Error::new(err.kind(), message)
        })?;
    file.write_all(body.as_bytes()).map_err(|err| {
        let _ = dir.remove_file(target);
        io::Error::new(
            err.kind(),
            format!("failed to write `{}`: {err}", repo_path_display(target)),
        )
    })?;
    Ok(())
}

pub(super) fn open_read_only(dir: &Dir, path: &Path) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use cap_std::fs::OpenOptionsExt;
        options.custom_flags(libc::O_NONBLOCK);
    }
    dir.open_with(path, &options)
}

/// Where [`read_regular`] stopped; each reader words it for its own command.
pub(super) enum ReadFailure {
    Open(io::Error),
    Inspect(io::Error),
    NotRegular,
    Read(io::Error),
}

/// The text at `path`, or `None` when nothing opens there: an absent file or a
/// dangling symlink, which each reader treats by its own policy. The open is
/// non-blocking and the file type is checked after it, so a FIFO swapped in
/// mid-look cannot stall the read.
pub(super) fn read_regular(dir: &Dir, path: &Path) -> Result<Option<String>, ReadFailure> {
    let mut file = match open_read_only(dir, path) {
        Ok(file) => file,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(err) => return Err(ReadFailure::Open(err)),
    };
    if !file.metadata().map_err(ReadFailure::Inspect)?.is_file() {
        return Err(ReadFailure::NotRegular);
    }
    let mut text = String::new();
    file.read_to_string(&mut text).map_err(ReadFailure::Read)?;
    Ok(Some(text))
}

/// The text at `path`, or `None` when it is absent.
///
/// # Errors
///
/// A path that is not a regular file, a dangling symlink, or one that cannot
/// be opened or read.
pub(super) fn read_text(
    dir: &Dir,
    path: &str,
) -> Result<Option<String>, Box<dyn std::error::Error>> {
    let failed =
        |message: String| -> Box<dyn std::error::Error> { Box::new(CliError::new(message)) };
    match read_regular(dir, Path::new(path)) {
        // A broken symlink opens as NotFound, as an absent file does, and
        // the two mean opposite things: one is a config that was never there,
        // the other is one oakum looked for and could not resolve.
        Ok(None) if dir.symlink_metadata(path).is_ok() => Err(failed(format!(
            "`{path}` is a symlink whose target does not exist"
        ))),
        Ok(text) => Ok(text),
        Err(ReadFailure::Open(err)) => Err(failed(format!("failed to open `{path}`: {err}"))),
        Err(ReadFailure::Inspect(err)) => Err(failed(format!("failed to inspect `{path}`: {err}"))),
        Err(ReadFailure::NotRegular) => Err(failed(format!("`{path}` is not a regular file"))),
        Err(ReadFailure::Read(err)) => Err(failed(format!("failed to read `{path}`: {err}"))),
    }
}

/// The text at `path`, or `None` when nothing resolves there. Unlike
/// [`read_text`], a dangling symlink reads as absent; a FIFO is still refused
/// rather than read. Every failure is `unverified`: the look did not happen.
pub(super) fn read_resolved_text(dir: &Dir, path: &Path) -> Result<Option<String>, CliError> {
    let unreadable = |err: io::Error| {
        CliError::unverified(format!(
            "unverified: failed to read `{}`: {err}",
            repo_path_display(path)
        ))
    };
    let not_regular = || {
        CliError::unverified(format!(
            "unverified: `{}` is not a regular file",
            repo_path_display(path)
        ))
    };
    read_regular(dir, path).map_err(|failure| match failure {
        // A socket, or a directory on Windows, fails to open as a file before
        // its type can be checked; name what is there, not the open error.
        ReadFailure::Open(err) => match dir.metadata(path) {
            Ok(meta) if !meta.is_file() => not_regular(),
            _ => unreadable(err),
        },
        ReadFailure::Inspect(err) | ReadFailure::Read(err) => unreadable(err),
        ReadFailure::NotRegular => not_regular(),
    })
}

/// `repo_path` is the discovery-time canonical prefix for absolute symlink
/// targets only; it is not reopened.
pub(super) fn resolve_capability_path(
    dir: &Dir,
    repo_path: &Path,
    path: &Path,
) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let mut pending = relative_components(path)?;
    let mut resolved = PathBuf::new();
    let mut followed = 0;
    while let Some(component) = pending.pop_front() {
        match component {
            PendingComponent::Parent => {
                if !resolved.pop() {
                    return Err(outside_repository(path));
                }
            }
            PendingComponent::Normal(component) => {
                let candidate = resolved.join(&component);
                let metadata = dir.symlink_metadata(&candidate).map_err(|err| {
                    path_error(format!(
                        "failed to resolve `{}` within the repository: {err}",
                        repo_path_display(path)
                    ))
                })?;
                if !metadata.file_type().is_symlink() {
                    resolved.push(component);
                    continue;
                }
                followed += 1;
                if followed > 40 {
                    return Err(path_error(format!(
                        "`{}` contains too many symbolic links",
                        repo_path_display(path)
                    )));
                }
                let target = match dir.read_link_contents(&candidate) {
                    Ok(target) => target,
                    Err(err) => {
                        #[cfg(not(windows))]
                        {
                            return Err(path_error(format!(
                                "failed to resolve `{}` within the repository: {err}",
                                repo_path_display(path)
                            )));
                        }
                        #[cfg(windows)]
                        {
                            let _ = err;
                            match read_symlink_via_ambient(repo_path, &candidate) {
                                Ok(target) => target,
                                Err(_) => return Err(outside_repository(path)),
                            }
                        }
                    }
                };
                #[cfg(windows)]
                let target = win32_from_nt_symlink_target(&target);
                let target = if target.is_absolute() {
                    resolved.clear();
                    contained_absolute_target(repo_path, &target)
                        .ok_or_else(|| outside_repository(path))?
                } else {
                    target
                };
                let mut target_components = relative_components(&target)?;
                while let Some(target_component) = target_components.pop_back() {
                    pending.push_front(target_component);
                }
            }
        }
    }
    if resolved.as_os_str().is_empty() {
        Ok(PathBuf::from("."))
    } else {
        Ok(resolved)
    }
}

enum PendingComponent {
    Parent,
    Normal(OsString),
}

fn relative_components(
    path: &Path,
) -> Result<VecDeque<PendingComponent>, Box<dyn std::error::Error>> {
    let mut components = VecDeque::new();
    for component in path.components() {
        match component {
            Component::Normal(component) => {
                components.push_back(PendingComponent::Normal(component.to_owned()));
            }
            Component::CurDir => {}
            Component::ParentDir => components.push_back(PendingComponent::Parent),
            Component::RootDir | Component::Prefix(_) => return Err(outside_repository(path)),
        }
    }
    Ok(components)
}

/// cap-std's Windows `read_link` strips `\??\` and leaves `UNC\host\share`.
/// That spelling is not a Win32 UNC path, so `Path::is_absolute` is false
/// and the walk looks for a `UNC` directory. Restore the `\\` form.
#[cfg(any(windows, test))]
fn win32_from_nt_symlink_target(target: &Path) -> PathBuf {
    let text = target.to_string_lossy().replace('/', "\\");
    let win32 = if let Some(rest) = text.strip_prefix(r"\??\UNC\") {
        format!(r"\\{rest}")
    } else if let Some(rest) = text.strip_prefix(r"\??\") {
        rest.to_owned()
    } else if let Some(rest) = text.strip_prefix(r"UNC\") {
        format!(r"\\{rest}")
    } else {
        text
    };
    PathBuf::from(win32)
}

/// cap-std's Windows `open` of a reparse point whose target is UNC fails with
/// `NotFound` (os error 2, GHA `windows-latest`). The link is still in the
/// repository; read its text via the ambient path so we can classify it.
#[cfg(windows)]
fn read_symlink_via_ambient(repo_path: &Path, candidate: &Path) -> io::Result<PathBuf> {
    std::fs::read_link(repo_path.join(candidate)).or_else(|_| {
        std::fs::read_link(PathBuf::from(normalized_windows_path(repo_path)).join(candidate))
    })
}

#[cfg(not(windows))]
fn contained_absolute_target(repo_path: &Path, target: &Path) -> Option<PathBuf> {
    fs::canonicalize(target)
        .ok()?
        .strip_prefix(repo_path)
        .ok()
        .map(Path::to_path_buf)
}

#[cfg(windows)]
fn contained_absolute_target(repo_path: &Path, target: &Path) -> Option<PathBuf> {
    let repo = normalized_windows_path(repo_path);
    let target = normalized_windows_path(&fs::canonicalize(target).ok()?);
    contained_windows_path(&repo, &target)
}

#[cfg(any(windows, test))]
fn contained_windows_path(repo: &str, target: &str) -> Option<PathBuf> {
    let prefix = target.get(..repo.len())?;
    if !prefix.eq_ignore_ascii_case(repo) {
        return None;
    }
    let remainder = target.get(repo.len()..)?;
    let repo_ends_with_separator = repo.ends_with('\\') || repo.ends_with('/');
    if !remainder.is_empty()
        && !repo_ends_with_separator
        && !remainder.starts_with('\\')
        && !remainder.starts_with('/')
    {
        return None;
    }
    Some(PathBuf::from(remainder.trim_start_matches(|character| {
        character == '\\' || character == '/'
    })))
}

/// Unix tests compile this so CI type-checks the Windows prefix strip.
#[cfg(any(windows, test))]
pub(super) fn normalized_windows_path(path: &Path) -> String {
    let path = path.to_string_lossy().replace('/', "\\");
    let path = if let Some(rest) = path.strip_prefix(r"\\?\UNC\") {
        format!(r"\\{rest}")
    } else if let Some(rest) = path.strip_prefix(r"\\?\") {
        rest.to_owned()
    } else {
        path
    };
    loopback_admin_share(&path).unwrap_or(path)
}

/// `\\localhost\C$\foo` is the same volume as `C:\foo`. A remote host's `C$`
/// is not: that would treat another machine's drive as this one.
#[cfg(any(windows, test))]
fn loopback_admin_share(path: &str) -> Option<String> {
    let rest = path.strip_prefix(r"\\")?;
    let mut parts = rest.splitn(3, '\\');
    let host = parts.next()?;
    let share = parts.next()?;
    let tail = parts.next();
    if !(host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1") {
        return None;
    }
    let bytes = share.as_bytes();
    if share.len() != 2 || bytes.get(1) != Some(&b'$') || !bytes[0].is_ascii_alphabetic() {
        return None;
    }
    let drive = bytes[0].to_ascii_uppercase() as char;
    Some(match tail {
        Some(tail) if !tail.is_empty() => format!(r"{drive}:\{tail}"),
        _ => format!(r"{drive}:\"),
    })
}

/// cap-std's refusal of a path that leaves the directory, worded for the
/// repository, or `None` for any other error.
pub(super) fn outside_repository_message(
    dir: &Dir,
    path: &Path,
    err: &io::Error,
) -> Option<String> {
    if err.kind() != io::ErrorKind::PermissionDenied
        || err.to_string() != "a path led outside of the filesystem"
    {
        return None;
    }
    let shown = repo_path_display(path);
    // cap-std refuses any absolute link on the path, even one naming a file
    // inside; only one at the leaf can be told apart from an escape.
    let absolute = dir
        .read_link_contents(path)
        .is_ok_and(|target| target.is_absolute());
    Some(if absolute {
        format!("`{shown}` is a symlink with an absolute target, which oakum does not follow")
    } else {
        format!(
            "`{shown}` is reached through a path that leaves the repository, or through a symlink with an absolute target, which oakum does not follow"
        )
    })
}

fn outside_repository(path: &Path) -> Box<dyn std::error::Error> {
    path_error(format!(
        "`{}` resolves outside the repository",
        repo_path_display(path)
    ))
}

fn path_error(message: impl Into<String>) -> Box<dyn std::error::Error> {
    Box::new(CliError::new(message))
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::{
        contained_windows_path, normalized_windows_path, repo_path_display,
        win32_from_nt_symlink_target,
    };

    fn open(root: &Path) -> cap_std::fs::Dir {
        cap_std::fs::Dir::open_ambient_dir(root, cap_std::ambient_authority()).unwrap()
    }

    /// Only a dangling link is named as one; a link to a file that exists
    /// keeps the plain refusal.
    #[cfg(unix)]
    #[test]
    fn an_exclusive_create_names_only_a_dangling_link() {
        let root = crate::test_fixture::Fixture::new("fs", "exclusive-link");
        std::fs::write(root.join("real.md"), "x").unwrap();
        std::os::unix::fs::symlink("real.md", root.join("live.md")).unwrap();
        std::os::unix::fs::symlink("gone.md", root.join("dangling.md")).unwrap();
        let dir = open(&root);

        let live = super::write_file_exclusive(&dir, Path::new("live.md"), "y")
            .unwrap_err()
            .to_string();
        assert!(live.starts_with("failed to create `live.md`"), "{live}");
        let dangling = super::write_file_exclusive(&dir, Path::new("dangling.md"), "y")
            .unwrap_err()
            .to_string();
        assert_eq!(
            dangling,
            "`dangling.md` is a symlink whose target does not exist"
        );
    }

    /// Only cap-std's escape refusal is reworded; any other permission error
    /// keeps its own text, and a path that is not a link gets the general wording.
    #[test]
    fn only_an_escape_is_worded_as_one() {
        let root = crate::test_fixture::Fixture::new("fs", "escape-wording");
        std::fs::write(root.join("plain.md"), "x").unwrap();
        let dir = open(&root);
        let escape = std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "a path led outside of the filesystem",
        );
        let denied = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");

        assert_eq!(
            super::outside_repository_message(&dir, Path::new("plain.md"), &denied),
            None
        );
        assert_eq!(
            super::outside_repository_message(&dir, Path::new("plain.md"), &escape).as_deref(),
            Some("`plain.md` is reached through a path that leaves the repository, or through a symlink with an absolute target, which oakum does not follow")
        );
    }

    /// Only `version`'s write set follows links: `migrate` copies a bump file
    /// out to a destination that may link back to its source, which must
    /// stay as it was.
    #[cfg(unix)]
    #[test]
    fn write_file_via_rename_replaces_a_link_without_following_it() {
        let root = crate::test_fixture::Fixture::new("fs", "replace-link");
        std::fs::write(root.join("source.md"), "old").unwrap();
        std::os::unix::fs::symlink("source.md", root.join("dest.md")).unwrap();
        let dir = cap_std::fs::Dir::open_ambient_dir(&root, cap_std::ambient_authority()).unwrap();

        super::write_file_via_rename(&dir, Path::new("dest.md"), "new").unwrap();

        assert!(!std::fs::symlink_metadata(root.join("dest.md"))
            .unwrap()
            .file_type()
            .is_symlink());
        assert_eq!(
            std::fs::read_to_string(root.join("dest.md")).unwrap(),
            "new"
        );
        assert_eq!(
            std::fs::read_to_string(root.join("source.md")).unwrap(),
            "old"
        );
    }

    /// Opening a socket fails before the type check on the opened file, so the
    /// refusal has to come from the failed open. Bound under the temp dir:
    /// a worktree's `target/` is too deep for macOS's 104-byte `sun_path`.
    #[cfg(unix)]
    #[test]
    fn a_socket_is_not_a_regular_file() {
        struct Removed(PathBuf);
        impl Drop for Removed {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
        let root =
            Removed(std::env::temp_dir().join(format!("oakum-socket-{}", std::process::id())));
        std::fs::create_dir_all(&root.0).expect("socket dir");
        let _listener =
            std::os::unix::net::UnixListener::bind(root.0.join("pin.toml")).expect("bind a socket");
        let dir =
            cap_std::fs::Dir::open_ambient_dir(&root.0, cap_std::ambient_authority()).expect("dir");
        let err = super::read_resolved_text(&dir, Path::new("pin.toml")).expect_err("refused");
        assert!(err.to_string().contains("is not a regular file"), "{err}");
    }

    #[test]
    fn repo_path_display_uses_forward_slashes() {
        assert_eq!(
            repo_path_display(&Path::new(".github/workflows").join("ci.yml")),
            ".github/workflows/ci.yml"
        );
    }

    #[cfg(windows)]
    #[test]
    fn repo_path_display_rewrites_a_backslash_separator() {
        assert_eq!(
            repo_path_display(Path::new(r".github\workflows\ci.yml")),
            ".github/workflows/ci.yml"
        );
    }

    #[test]
    fn windows_drive_root_contains_files() {
        assert_eq!(
            contained_windows_path(r"C:\", r"c:\config.toml"),
            Some(PathBuf::from("config.toml"))
        );
        assert_eq!(
            contained_windows_path(r"C:\repo", r"c:\repository\config.toml"),
            None
        );
    }

    #[test]
    fn path_component_case_is_ignored_for_windows_containment() {
        assert_eq!(
            contained_windows_path(r"C:\Users\repo", r"c:\users\REPO\.changeset\_config.toml"),
            Some(PathBuf::from(r".changeset\_config.toml"))
        );
        assert_eq!(
            contained_windows_path(r"C:\Users\repo", r"c:\users\repository\config.toml"),
            None
        );
    }

    #[test]
    fn verbatim_and_unc_prefixes_strip_to_the_drive_path() {
        assert_eq!(
            normalized_windows_path(Path::new(r"\\?\C:\repo\_config.toml")),
            r"C:\repo\_config.toml"
        );
        assert_eq!(
            normalized_windows_path(Path::new(r"\\?\UNC\localhost\C$\repo")),
            r"C:\repo"
        );
        assert_eq!(
            normalized_windows_path(Path::new(r"\\localhost\C$\repo\a")),
            r"C:\repo\a"
        );
        assert_eq!(
            normalized_windows_path(Path::new(r"\\127.0.0.1\c$\repo")),
            r"C:\repo"
        );
        assert_eq!(
            normalized_windows_path(Path::new(r"\\fileserver\C$\repo")),
            r"\\fileserver\C$\repo"
        );
        assert_eq!(
            normalized_windows_path(Path::new("C:/repo/a")),
            r"C:\repo\a"
        );
        assert_eq!(
            normalized_windows_path(Path::new("//localhost/C$/repo")),
            r"C:\repo"
        );
        assert_eq!(
            normalized_windows_path(Path::new("//?/C:/repo/a")),
            r"C:\repo\a"
        );
        assert_eq!(
            normalized_windows_path(Path::new(r"\\localhost\C$")),
            r"C:\"
        );
        assert_eq!(
            normalized_windows_path(Path::new(r"\\localhost\C$\")),
            r"C:\"
        );
    }

    #[test]
    fn nt_symlink_unc_becomes_win32_unc() {
        assert_eq!(
            win32_from_nt_symlink_target(Path::new(r"UNC\localhost\C$\repo")),
            PathBuf::from(r"\\localhost\C$\repo")
        );
        assert_eq!(
            win32_from_nt_symlink_target(Path::new(r"\??\UNC\localhost\C$\repo")),
            PathBuf::from(r"\\localhost\C$\repo")
        );
        assert_eq!(
            win32_from_nt_symlink_target(Path::new(r"\??\C:\repo")),
            PathBuf::from(r"C:\repo")
        );
        assert_eq!(
            win32_from_nt_symlink_target(Path::new(r"..\outside")),
            PathBuf::from(r"..\outside")
        );
    }

    #[test]
    fn a_loopback_unc_repo_contains_a_canonical_drive_target() {
        let repo = normalized_windows_path(Path::new(r"\\localhost\C$\repo"));
        assert_eq!(repo, r"C:\repo");
        assert_eq!(
            contained_windows_path(&repo, r"c:\repo\.changeset\_config.toml"),
            Some(PathBuf::from(r".changeset\_config.toml"))
        );
        assert_eq!(
            contained_windows_path(
                &repo,
                &normalized_windows_path(Path::new(r"\\?\C:\repo\.changeset\_config.toml"))
            ),
            Some(PathBuf::from(r".changeset\_config.toml"))
        );
        assert_eq!(
            contained_windows_path(&repo, r"D:\repo\.changeset\_config.toml"),
            None
        );
        assert_eq!(
            contained_windows_path(
                &normalized_windows_path(Path::new(r"\\fileserver\C$\repo")),
                r"C:\repo\.changeset\_config.toml"
            ),
            None
        );
    }

    #[test]
    fn staging_names_are_the_dot_prefixed_marked_ones() {
        use super::is_staging_name;
        assert!(is_staging_name(".one.md.oakum-write.123.456.0"));
        assert!(is_staging_name("._config.toml.oakum-write.1.2.3"));
        assert!(!is_staging_name("one.md"));
        assert!(!is_staging_name("oakum-write.md"));
        assert!(!is_staging_name("one.md.oakum-write.1.2.3"));
        assert!(!is_staging_name(".gitkeep"));
        assert!(is_staging_name(".one.md.oakum-consume.123.456.0"));
        assert!(is_staging_name(".oakum-write.1.2.3"));
    }

    #[test]
    fn consume_names_are_told_apart_from_write_names() {
        use super::{is_consume_staging_name, parse_staging_name, StagingKind};
        assert!(is_consume_staging_name(".one.md.oakum-consume.1.2.0"));
        assert!(!is_consume_staging_name("._config.toml.oakum-write.1.2.0"));
        let consume = parse_staging_name(".a.oakum-write.9.md.oakum-consume.42.1.0").unwrap();
        assert_eq!(
            (consume.target, consume.kind, consume.pid()),
            ("a.oakum-write.9.md", StagingKind::Consume, Some(42))
        );
        let write = parse_staging_name(".a.oakum-consume.9.md.oakum-write.43.1.0").unwrap();
        assert_eq!(
            (write.target, write.kind, write.pid()),
            ("a.oakum-consume.9.md", StagingKind::Write, Some(43))
        );
    }

    /// Removing a consume leftover on sight can lose a bump the changelog
    /// lacks, so `check` points at `version` instead.
    #[test]
    fn a_consume_leftover_is_not_advised_for_removal() {
        use super::{stray_staging_message, CONSUME_CLAIM, STAGING_CLAIM};
        let consume = stray_staging_message(".changeset/.a.md.oakum-consume.1.2.0");
        assert!(consume.ends_with(CONSUME_CLAIM), "{consume}");
        let write = stray_staging_message(".changeset/._config.toml.oakum-write.1.2.0");
        assert!(write.ends_with(STAGING_CLAIM), "{write}");
        // The marker's rewrite copy is a consume's evidence of a rollback;
        // removing it would turn `version`'s advice back to keeping writes.
        let rewrite =
            stray_staging_message(".changeset/..version.oakum-consume.1.2.0.oakum-write.9.8.0");
        assert!(rewrite.ends_with(CONSUME_CLAIM), "{rewrite}");
    }

    /// A write's staging copy of the marker carries both marks; the last one
    /// decides, so it is not counted as a set-aside bump file.
    #[test]
    fn the_last_mark_decides_a_staging_names_kind() {
        use super::is_consume_staging_name;
        assert!(is_consume_staging_name(".a.md.oakum-consume.1.2.0"));
        assert!(!is_consume_staging_name(
            "..version.oakum-consume.1.2.0.oakum-write.9.8.0"
        ));
        assert!(is_consume_staging_name(
            ".a.oakum-write.md.oakum-consume.1.2.0"
        ));
    }
}