ostrya 0.15.0

Pure-Rust async reimplementation of the ostree repository library
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
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
//! The error type of this crate.
//!
//! [`Error`](enum@Error) is the error of each fallible operation of the
//! crate. [`Result`] is the result type with that error.

use ostrya_core::{Checksum, ObjectType};
use thiserror::Error;

/// The result type of this crate, with [`Error`](enum@Error) as the error.
pub type Result<T> = std::result::Result<T, Error>;

/// The error of each fallible operation of this crate.
///
/// The enum is `#[non_exhaustive]`, so a release can add a variant without a
/// breaking change. The signing engines and the fetcher have their own error
/// types, [`ostrya_sign::Error`] and [`fetch::Error`](crate::fetch::Error).
/// Each of the two converts into this type.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// An I/O error.
    #[error("i/o error: {0}")]
    Io(#[from] std::io::Error),
    /// An error from the format primitives: checksums, key files, and objects.
    #[error(transparent)]
    Core(#[from] ostrya_core::Error),
    /// An object that is not in the object store.
    #[error("object not found: {ty:?} {checksum}")]
    ObjectNotFound {
        /// The checksum of the object that the lookup asked for.
        checksum: Checksum,
        /// The type of the object that the lookup asked for.
        ty: ObjectType,
    },
    /// A refspec that does not resolve to a commit.
    ///
    /// The payload is the ref as text: `<name>`, `<remote>:<name>`, or
    /// `@<collection-id>:<name>` for a collection ref.
    #[error("ref not found: {0}")]
    RefNotFound(String),
    /// A remote with no `[remote "<name>"]` group in the configuration.
    ///
    /// The payload is the name of the remote.
    #[error("remote not found: {0}")]
    RemoteNotFound(String),
    /// A remote that already has a `[remote "<name>"]` group in the
    /// configuration.
    ///
    /// The payload is the name of the remote.
    #[error("remote already exists: {0}")]
    RemoteExists(String),
    /// A path where [`Repo::create`](crate::Repo::create) must create a
    /// repository, and that holds an entry `config` of any type.
    ///
    /// The payload is the path as the caller gave it.
    #[error("repository exists: {}", .0.display())]
    RepoExists(std::path::PathBuf),
    /// A refspec that does not name a path in the `refs/` tree.
    ///
    /// The causes are:
    ///
    /// - an empty name
    /// - an empty, `.`, or `..` component
    /// - a remote element or a collection element that holds a `/`
    /// - an interior NUL
    ///
    /// The payload is the refspec as the caller gave it. A [`Ref`] value
    /// gives its text: `<name>`, `<remote>:<name>`, or
    /// `@<collection-id>:<name>` for a collection ref.
    ///
    /// [`Ref`]: crate::Ref
    #[error("invalid refspec: {0}")]
    InvalidRefspec(String),
    /// An abbreviated checksum that is the prefix of two or more commit
    /// objects.
    ///
    /// Such a checksum names no single commit. The payload is the revision as
    /// the caller gave it.
    #[error("refspec not unique: {0}")]
    AmbiguousRefspec(String),
    /// A ref write or a ref removal that the ref store cannot take.
    ///
    /// [`Transaction::commit`](crate::Transaction::commit) gives this error
    /// when it checks the queued refs under the update lock. The cause is a
    /// ref path that names an alias, names a directory, passes through a
    /// file or an alias, or names a special file, or two queued refs where
    /// the path of one names a directory of the other and one of the two is
    /// a write. The published objects stay, and the commit writes no
    /// detached metadata and no ref.
    ///
    /// [`Repo::set_ref_immediate`](crate::Repo::set_ref_immediate) and
    /// [`UpdateGuard::set_ref`](crate::UpdateGuard::set_ref) give this error
    /// for a ref path that names an alias or passes through an alias.
    /// [`Repo::set_ref_alias_immediate`](crate::Repo::set_ref_alias_immediate)
    /// and [`UpdateGuard::set_ref_alias`](crate::UpdateGuard::set_ref_alias)
    /// give it for a path that passes through an alias.
    /// [`Repo::remove_ref_alias_immediate`](crate::Repo::remove_ref_alias_immediate)
    /// and [`UpdateGuard::remove_ref_alias`](crate::UpdateGuard::remove_ref_alias)
    /// give it for a path that names a ref file, names a directory, passes
    /// through a file or an alias, or names a special file.
    /// [`Repo::prune`](crate::Repo::prune) gives it for a weak ref to delete
    /// whose path passes through an alias.
    #[error("ref not writable: {name}: {reason}")]
    RefNotWritable {
        /// The ref as text: `<name>`, `<remote>:<name>`, or
        /// `@<collection-id>:<name>` for a collection ref.
        name: String,
        /// The cause, for example `names a directory`.
        reason: String,
    },
    /// A ref path that names an entry that is not a regular file, such as a
    /// directory, a FIFO, or a socket.
    #[error("not a ref: {name}: {reason}")]
    NotARef {
        /// The ref as text: `<name>`, `<remote>:<name>`, or
        /// `@<collection-id>:<name>` for a collection ref.
        name: String,
        /// The cause, for example `is not a regular file`.
        reason: String,
    },
    /// A conditional ref write whose ref does not have the expected state.
    ///
    /// [`Transaction::commit`](crate::Transaction::commit) gives this error
    /// when it compares a write of
    /// [`Transaction::set_ref_expecting`](crate::Transaction::set_ref_expecting)
    /// with the ref store under the update lock. The message shows an absent
    /// ref as `absent`. The published objects stay, and the commit writes no
    /// detached metadata and no ref.
    #[error(
        "ref mismatch: {name}: expected {}, found {}",
        .expected.map_or_else(|| "absent".to_owned(), |c| c.to_string()),
        .current.map_or_else(|| "absent".to_owned(), |c| c.to_string())
    )]
    RefMismatch {
        /// The ref as text: `<name>`, `<remote>:<name>`, or
        /// `@<collection-id>:<name>` for a collection ref.
        name: String,
        /// The commit that the caller expected, or `None` for an absent ref.
        expected: Option<Checksum>,
        /// The commit of the ref file, or `None` for an absent ref.
        current: Option<Checksum>,
    },
    /// A `^` suffix of a revision that asks for the parent of a root commit.
    ///
    /// The payload is the checksum of the root commit.
    #[error("commit {0} has no parent")]
    NoParentCommit(Checksum),
    /// Data that does not match its expected format.
    #[error("invalid format: {0}")]
    InvalidFormat(String),
    /// An operation or a repository feature that this crate does not support.
    ///
    /// A [`fetch::Error::Unsupported`](crate::fetch::Error::Unsupported)
    /// converts to this variant.
    #[error("unsupported: {0}")]
    Unsupported(String),
    /// An argument outside the values that the operation accepts.
    ///
    /// An example is a pull depth less than `-1`.
    #[error("invalid input: {0}")]
    InvalidInput(String),
    /// A wait for the repository lock or the update lock that passed its
    /// limit.
    ///
    /// The limit of the wait is the value of `[core] lock-timeout-secs`. With
    /// the value `-1`, a wait has no limit and does not give this error. The
    /// message names the repository lock for both locks.
    /// [`LockKind`](crate::LockKind) states the rules of the repository lock,
    /// and [`UpdateGuard`](crate::UpdateGuard) states the rules of the update
    /// lock.
    #[error("timed out acquiring repository lock after {secs}s")]
    LockTimeout {
        /// The limit of the wait, in seconds.
        secs: i64,
    },
    /// Data whose computed checksum is not the expected checksum.
    ///
    /// The expected checksum is the checksum that the caller of a write gives
    /// for the object. In a pull, it is also the advertised checksum of a
    /// static-delta superblock.
    #[error("checksum mismatch: expected {expected}, computed {actual}")]
    ChecksumMismatch {
        /// The checksum that the caller or the advertisement gave.
        expected: Checksum,
        /// The checksum that this crate computed.
        actual: Checksum,
    },
    /// A staged object that makes the free space less than the reserve.
    ///
    /// The keys `min-free-space-percent` and `min-free-space-size` of
    /// `[core]` set the reserve.
    #[error("insufficient free space: short by {shortfall} bytes")]
    InsufficientFreeSpace {
        /// The number of bytes of free space that the write needed in
        /// addition.
        shortfall: u64,
    },
    /// A failure to build or serialize an in-memory tree.
    ///
    /// The causes are:
    ///
    /// - an invalid entry name
    /// - a file name and a directory name that are the same
    /// - a directory with no dirmeta checksum
    /// - the removal of an absent entry
    /// - a committed subdirectory that is not loaded, with no repository to
    ///   read it from
    #[error("mutable tree: {0}")]
    MutableTree(String),
    /// An overlayfs feature in an upper directory that the merge cannot carry.
    ///
    /// An entry with `overlay.metacopy` or `overlay.redirect` is not
    /// self-contained. The merge needs an overlay that has the feature off:
    /// `metacopy=off` and `redirect_dir=off`.
    #[error("unsupported overlay feature: {0}")]
    UnsupportedOverlayFeature(String),
    /// A path with a component that is not present.
    #[error("path not found: {path}")]
    PathNotFound {
        /// The path of the absent component.
        ///
        /// If a caller has one name and no path, the field holds the bare
        /// entry name. [`MutableTree::subtree`](crate::MutableTree::subtree)
        /// is such a caller.
        path: String,
    },
    /// A path component that must be a directory and is a file.
    ///
    /// A symlink that resolves to a file also gives this error.
    #[error("not a directory: {path}")]
    NotADirectory {
        /// The path of the component that is not a directory.
        ///
        /// If a caller has one name and no path, the field holds the bare
        /// entry name. [`MutableTree::subtree`](crate::MutableTree::subtree)
        /// is such a caller.
        path: String,
    },
    /// A symlink whose target does not resolve.
    #[error("dangling symlink: {path} -> {target}")]
    DanglingSymlink {
        /// The path of the symlink.
        path: String,
        /// The target that the symlink names.
        target: String,
    },
    /// A path resolution that followed more symlinks than the depth cap.
    ///
    /// The cap is 40 symlinks.
    #[error("symlink chain too deep (possible loop): {path}")]
    SymlinkLoop {
        /// The path of the symlink where the resolution stopped.
        path: String,
    },
    /// An entry at a path where an operation must create a new entry.
    #[error("entry already exists: {path}")]
    EntryExists {
        /// The path of the entry.
        path: String,
    },
    /// A failure of a staging-tree operation that no other variant names.
    ///
    /// The causes are:
    ///
    /// - an outstanding file writer that blocks the operation, for example
    ///   [`StagingTree::close`](crate::StagingTree::close)
    /// - a read of a file at a path that holds a directory
    /// - a hardlink whose source resolves to a directory
    /// - a directory that a concurrent operation removed while the operation
    ///   held its path
    /// - a path with no final component, or a path that ends in `..`
    /// - a path component or a symlink target that is not valid UTF-8
    /// - a rename whose destination is under the moved entry
    /// - a load of a committed directory with no repository handle to read it
    #[error("staging tree: {0}")]
    Staging(String),
    /// A conflict of a staging-tree merge that the merge options do not permit.
    ///
    /// The conflicts are differing files, a file and a directory at one path,
    /// and differing directory metadata. Each one is a conflict only if
    /// [`allow_overwrite`](crate::MergeOptions::allow_overwrite) of the
    /// [`MergeOptions`](crate::MergeOptions) is off.
    #[error("merge conflict: {0}")]
    MergeConflict(String),
    /// A checkout that cannot proceed.
    ///
    /// The causes are:
    ///
    /// - a collision under [`OverwriteMode::None`](crate::OverwriteMode::None)
    /// - a mismatch under
    ///   [`UnionIdentical`](crate::OverwriteMode::UnionIdentical)
    /// - a combination of options that a checkout does not accept
    /// - a partial commit
    /// - a whiteout that names no entry
    /// - a destination name that is not valid UTF-8
    /// - a failure to set an extended attribute
    #[error("checkout: {0}")]
    Checkout(String),
    /// A checkout [`subpath`](crate::CheckoutOptions::subpath) that names no
    /// entry in the commit tree.
    ///
    /// The payload is the value as the caller wrote it.
    #[error("checkout: subpath not found: {}", .0.display())]
    SubpathNotFound(std::path::PathBuf),
    /// A checkout [`subpath`](crate::CheckoutOptions::subpath) that passes
    /// through an entry that is not a directory.
    ///
    /// The payload is the value as the caller wrote it.
    #[error("checkout: subpath is not a directory: {}", .0.display())]
    SubpathNotADirectory(std::path::PathBuf),
    /// An entry that a checkout under
    /// [`require_hardlinks`](crate::CheckoutOptions::require_hardlinks) must
    /// copy.
    ///
    /// The repository mode and the checkout mode give a copy of the entry.
    /// The payload is the name of the entry.
    #[error(
        "checkout: {0}: require-hardlinks is set and this repository mode and \
         checkout mode give a copy of this entry"
    )]
    RequireHardlinks(String),
    /// A hardlink checkout into a directory on another file system.
    ///
    /// A checkout under
    /// [`require_hardlinks`](crate::CheckoutOptions::require_hardlinks) cannot
    /// hardlink an entry into a directory on a file system other than the file
    /// system of the repository. The destination root gives this error, and
    /// so does each directory under it. A checkout of a
    /// single file or symlink does no such directory check. It gives this
    /// error if the link of that entry crosses a file system.
    ///
    /// The fields hold the device number of each side.
    #[error(
        "checkout: require-hardlinks: the destination is on another filesystem \
         than the repository (repository={src} destination={dst})"
    )]
    HardlinkAcrossDevices {
        /// The device number of the object store of the repository.
        src: u64,
        /// The device number of the destination.
        dst: u64,
    },
    /// A tar import or export that cannot proceed.
    ///
    /// The causes are:
    ///
    /// - an entry type that a repository cannot store: a device node or a
    ///   FIFO
    /// - an empty path, or a path with a `..` component
    /// - a hardlink with no target in the archive
    /// - an xattr name that is not valid UTF-8
    /// - an export subpath that is absent or is not a directory
    #[error("tar: {0}")]
    Tar(String),
    /// A failure to remove an entry of the source under
    /// [`CONSUME`](crate::CommitModifierFlags::CONSUME).
    ///
    /// The fields hold the name of the entry and the reason of the failure.
    #[error("unlinkat({name}): {reason}")]
    ConsumeUnlink {
        /// The name of the entry.
        name: String,
        /// The reason of the failure, as the text of the OS error.
        reason: String,
    },
    /// A file from a tree source at a path where an earlier source put a
    /// directory.
    ///
    /// The payload is the name of the entry.
    #[error("Can't replace directory with file: {0}")]
    ReplaceDirWithFile(String),
    /// A directory from a tree source at a path where an earlier source put a
    /// file.
    ///
    /// The payload is the name of the entry.
    #[error("Can't replace file with directory: {0}")]
    ReplaceFileWithDir(String),
    /// A tar member whose parent directory is not in the tree.
    ///
    /// A tar import gives this error if
    /// [`TarImportOptions::autocreate_parents`](crate::TarImportOptions::autocreate_parents)
    /// is off. The payload is the name of the first absent ancestor.
    #[error("No such file or directory: {0}")]
    TarMissingParent(String),
    /// A failure of a signing engine, a key source, or a signature
    /// verification.
    ///
    /// A signing engine gives this error for these inputs:
    ///
    /// - a key of the wrong length
    /// - a public key that is not a valid curve point
    /// - a malformed secret key
    /// - a signature blob that the engine refuses
    ///
    /// An [`ostrya_sign::Error::Signature`] converts to this variant with the
    /// same message. Each variant of `ostrya_sign::Error` that the conversion
    /// does not name also converts to this variant.
    ///
    /// This crate also builds this variant in these places:
    ///
    /// - the verification policy of a pull
    /// - the readers of keyrings and key files
    /// - the GPG key import and the `gpg` program that it runs
    /// - the signature verification of a static delta
    #[error("signature: {0}")]
    Signature(String),
    /// A pull that cannot proceed, or that refuses an object or a commit.
    ///
    /// The causes are:
    ///
    /// - a remote that is not in the configuration, or that has no `url` and
    ///   no `pull-url`
    /// - a pull of all refs with no configured branches, or in mirror mode
    ///   with no summary on the remote
    /// - a pull of the refs of the remote key `pull-branches` with no summary
    ///   on the remote, or with no ref of the summary that the key selects
    ///   and no ref in the remote key `branches`
    /// - a commit whose `ostree.ref-binding` does not name the ref of the pull
    /// - a commit that is older than the commit that its ref holds
    /// - a content object whose mode the destination repository cannot store
    /// - a required static delta that is absent, or a delta whose superblock
    ///   does not produce its target
    /// - a list of static deltas whose superblocks and detached metadata pass
    ///   the 1 GiB limit of one discovery from a remote
    /// - a subpath that is not an absolute path, or too many subpaths
    /// - a signature verification with no remote to take the keys from
    /// - a client certificate with no client key, or a client key with no
    ///   client certificate
    #[error("pull: {0}")]
    Pull(String),
    /// A failure to set up or to carry out a fetch.
    ///
    /// The causes include a mirror URL, a header, or a TLS configuration that
    /// the fetcher cannot use. They also include a transport failure that
    /// outlived the retries.
    ///
    /// A [`fetch::Error::Fetch`](crate::fetch::Error::Fetch) converts to this
    /// variant with the same message. Each variant of `fetch::Error` that the
    /// conversion does not name also converts to this variant. A pull also
    /// builds this variant.
    #[error("fetch: {0}")]
    Fetch(String),
    /// An unsuccessful HTTP status that ended a fetch.
    ///
    /// A 404 means that the remote does not hold the object. A pull accepts a
    /// 404 as a normal answer for an optional object.
    ///
    /// A fetch with mirrors and rounds reports the first definitive failure
    /// that it received. If it received no definitive failure, it reports the
    /// first retryable failure. If the reported failure is a status, it is
    /// this variant.
    ///
    /// A [`fetch::Error::HttpStatus`](crate::fetch::Error::HttpStatus) converts
    /// to this variant. The conversion drops the headers and the body of the
    /// response that the fetch error can carry.
    #[error("http status {status} for {url}")]
    HttpStatus {
        /// The status of the response.
        status: u16,
        /// The URL of the hop that answered with the status.
        url: String,
    },
    /// A redirect chain that reached the limit of
    /// [`max_redirects`](crate::FetcherOptions::max_redirects).
    ///
    /// The response at the end of the chain named another URL to follow. Each
    /// attempt against one destination counts its own hops, so a repeated
    /// round counts again from the destination that the route named.
    ///
    /// A [`fetch::Error::RedirectLimit`](crate::fetch::Error::RedirectLimit)
    /// converts to this variant.
    #[error("redirect from {url} exceeds the {hops}-redirect limit")]
    RedirectLimit {
        /// The URL of the last hop, whose `Location` the limit did not follow.
        url: String,
        /// The number of redirects that the attempt followed, which is the
        /// limit.
        hops: u32,
    },
    /// A response that declared more bytes than the cap of the caller.
    ///
    /// If a body grows past the cap while it streams, the read fails with the
    /// same [`FileTooLarge`](std::io::ErrorKind::FileTooLarge) kind. The
    /// payload of that I/O error is a message, and it does not downcast to an
    /// error of this crate.
    ///
    /// A [`fetch::Error::FetchTooLarge`](crate::fetch::Error::FetchTooLarge)
    /// converts to this variant.
    #[error("fetched object exceeds the {limit}-byte cap")]
    FetchTooLarge {
        /// The cap that the caller set on the request.
        limit: u64,
    },
    /// A response that declared a coding in `Content-Encoding` or
    /// `Transfer-Encoding`.
    ///
    /// The body of such a response holds bytes other than the bytes that the
    /// remote stores.
    ///
    /// A [`fetch::Error::ContentEncoded`](crate::fetch::Error::ContentEncoded)
    /// converts to this variant.
    #[error("response for {url} carries the coding {encoding}")]
    ContentEncoded {
        /// The URL that answered.
        url: String,
        /// The coding that the response declared.
        encoding: String,
    },
    /// An upload that failed after the fetcher gave its request to the
    /// connection.
    ///
    /// The server can have received the whole request and acted on it, so the
    /// outcome is unknown. The fetcher does not send the request again.
    ///
    /// A
    /// [`fetch::Error::UploadInterrupted`](crate::fetch::Error::UploadInterrupted)
    /// converts to this variant.
    #[error("upload to {url} interrupted: {message}")]
    UploadInterrupted {
        /// The URL that the request was sent to.
        url: String,
        /// The text that names what ended the upload.
        message: String,
    },
    /// A defective list of related commits, or attachments that are not
    /// complete.
    ///
    /// These calls give this error:
    ///
    /// - [`Transaction::write_commit`](crate::Transaction::write_commit) and
    ///   [`Transaction::check_attachments`](crate::Transaction::check_attachments),
    ///   for an entry of
    ///   [`CommitOptions::attachments`](crate::CommitOptions::attachments) with an
    ///   empty name, for two entries with the same name, and for an attachment
    ///   that is absent or partial. The calls check before the commit has a
    ///   checksum, so `commit` is `None`.
    /// - [`Repo::commit_add_composefs_metadata`](crate::Repo::commit_add_composefs_metadata),
    ///   for a defective field 2 of the source commit: an entry with an empty
    ///   name or with a checksum that is not 32 bytes, entries that are not
    ///   sorted by name, two entries with the same name, and an attachment
    ///   that is absent or partial. `commit` is the source commit.
    /// - [`Repo::read_commit_relations`](crate::Repo::read_commit_relations), for
    ///   an entry with an empty name or with a checksum that is not 32 bytes,
    ///   and for an `ostrya.related` value that is not a variant of type
    ///   `a(say)`. `commit` is the commit that the call reads.
    /// - [`Repo::write_commit_detached_metadata`](crate::Repo::write_commit_detached_metadata),
    ///   and [`Transaction::commit`](crate::Transaction::commit) for a dict
    ///   that
    ///   [`Transaction::set_commit_detached_metadata`](crate::Transaction::set_commit_detached_metadata)
    ///   queued, for an `ostrya.related` entry of the dict with one of these
    ///   defects. `commit` is the commit of the dict.
    /// - [`Repo::add_supplement`](crate::Repo::add_supplement) and
    ///   [`Transaction::add_supplement`](crate::Transaction::add_supplement),
    ///   for an empty name. `commit` is the commit that gets the supplement.
    /// - [`Repo::add_supplement`](crate::Repo::add_supplement),
    ///   and [`Transaction::commit`](crate::Transaction::commit) for an add
    ///   that
    ///   [`Transaction::add_supplement`](crate::Transaction::add_supplement)
    ///   queued, for a stored `ostrya.related` value with one of these
    ///   defects. `commit` is the commit that gets the supplement.
    /// - [`Repo::pull`](crate::Repo::pull),
    ///   [`Repo::pull_with_session`](crate::Repo::pull_with_session), and
    ///   [`Repo::pull_collection`](crate::Repo::pull_collection) from a
    ///   remote, for an entry of field 2 with an empty name or with a
    ///   checksum that is not 32 bytes. Also for an attachment, at each level,
    ///   that neither the remote, a localcache repository, nor the repository
    ///   holds. `commit` is the commit that holds the entry. For an
    ///   attachment, it is a commit of the lowest level that names the
    ///   attachment, the commit with the lowest checksum of that level, as
    ///   [`Repo::pull`](crate::Repo::pull) states in `# Attachments`.
    /// - [`Repo::pull_local`](crate::Repo::pull_local), and
    ///   [`Repo::pull_collection`](crate::Repo::pull_collection) from a local
    ///   repository, for an entry of field 2 with an empty name or with a
    ///   checksum that is not 32 bytes. Also for an attachment, at each level,
    ///   that neither a source nor the repository holds, that the first
    ///   source that holds it marks partial, or that the repository held
    ///   complete and no longer holds complete when the transaction opens.
    ///   `commit` is the commit that holds the entry. For an attachment, it
    ///   is the commit that first names the attachment.
    /// - `Repo::push`, `Repo::push_over_stream`, `Repo::push_to_bucket`, and
    ///   `Repo::export_stream`, for an entry of field 2 with an empty name or
    ///   with a checksum that is not 32 bytes, in a commit that the push or
    ///   the export reads: a source commit, a commit of the parent chain that
    ///   the push walks, a new commit of the export, or an attachment at each
    ///   level. Also for an attachment, at each level, that the local
    ///   repository does not hold or marks partial. `commit` is the commit
    ///   that holds the entry. For an absent or a partial attachment, it is
    ///   the commit that first names the attachment.
    /// - `Repo::receive`, `Repo::receive_selected`, `Repo::receive_stream`,
    ///   `Repo::receive_stream_to_commit`, and `ReceiveService::commit`, for
    ///   an entry of field 2 with an empty name or with a checksum that is not
    ///   32 bytes, in an attachment or a new commit that the repository holds
    ///   complete. `commit` is that held commit.
    /// - [`Repo::apply_static_delta`](crate::Repo::apply_static_delta) and
    ///   [`Repo::apply_static_delta_offline`](crate::Repo::apply_static_delta_offline),
    ///   for an entry of field 2 of the target commit with an empty name or
    ///   with a checksum that is not 32 bytes, and for an attachment that is
    ///   absent or partial. `commit` is the target commit.
    ///
    /// [`Repo::prune`](crate::Repo::prune) gives a
    /// [`RelationWarning`](crate::RelationWarning) with the same text in place
    /// of this error, and continues.
    #[error(
        "related commits in {field}{}: {reason}",
        .commit.map(|c| format!(" of commit {c}")).unwrap_or_default()
    )]
    InvalidRelations {
        /// The commit that holds the entries, or `None` for a commit that is
        /// not written yet.
        commit: Option<Checksum>,
        /// The field that holds the entries.
        field: crate::RelationField,
        /// The text that names the defect.
        reason: String,
    },
    /// A failure of a session of the wire protocol of
    /// [`ostrya-remote`](crate::remote).
    ///
    /// The push, the receive side, and the pull over ssh use this protocol.
    ///
    /// The causes are:
    ///
    /// - an error that the server side sent to the peer with its wire code
    /// - an `Abort` from the client ([`Aborted`](crate::remote::Error::Aborted))
    /// - an error of the session stream
    /// - on the client side, a push request that the client refuses
    ///   ([`InvalidInput`](crate::remote::Error::InvalidInput))
    /// - with the `s3` feature, an error response of an S3 server to a read
    ///   of the bucket client in a pull
    ///
    /// The variant is in every build.
    #[error(transparent)]
    Remote(#[from] crate::remote::Error),
    /// A static delta from `from` to `to` that the repository does not hold.
    ///
    /// No file resolves at its `deltas/<fanout>/<rest>` path. The message
    /// names the delta as the `ostree` command names it.
    #[error("Can't find delta {}", crate::delta::delta_hex_name(.from.as_ref(), .to))]
    StaticDeltaNotFound {
        /// The source commit, or `None` for a delta from scratch.
        from: Option<Checksum>,
        /// The target commit.
        to: Checksum,
    },
    /// A composefs image whose fs-verity digest is not the value of the
    /// `ostree.composefs.digest.v0` key of its commit.
    ///
    /// [`Repo::add_composefs_supplement`](crate::Repo::add_composefs_supplement)
    /// gives this error and writes nothing. The build of an image for a mount
    /// under [`VerityPolicy::Computed`](crate::VerityPolicy::Computed) also
    /// gives it, after it writes the image.
    #[error(
        "composefs image of commit {commit}: the commit records the digest {}, the image has {}",
        crate::composefs::digest_hex(.expected),
        crate::composefs::digest_hex(.actual)
    )]
    ComposefsDigestMismatch {
        /// The commit of the image.
        commit: Checksum,
        /// The digest that the commit records.
        expected: [u8; 32],
        /// The fs-verity digest of the image.
        actual: [u8; 32],
    },
    /// A composefs image commit that a commit names, with a defect of the
    /// image commit or of the way that the commit names it.
    ///
    /// [`Repo::open_composefs_image`](crate::Repo::open_composefs_image)
    /// gives this error. It does not try the next source.
    /// [`Repo::add_composefs_supplement`](crate::Repo::add_composefs_supplement)
    /// gives it with
    /// [`ComposefsImageDefect::NotSealed`](crate::ComposefsImageDefect::NotSealed).
    #[error(
        "composefs image of commit {commit}: {relation} {} names commit {image}, {defect}",
        crate::COMPOSEFS_RELATION
    )]
    InvalidComposefsImage {
        /// The commit that names the image commit.
        commit: Checksum,
        /// The field of `commit` that names the image commit.
        relation: crate::ComposefsImageSource,
        /// The checksum of the image commit.
        image: Checksum,
        /// The defect of the image commit. The box keeps the size of
        /// `Error` small.
        defect: Box<crate::ComposefsImageDefect>,
    },
    /// No media repository on the mounted volumes, or in the directory that
    /// the caller gave in place of the mount table.
    ///
    /// [`Repo::import_media`](crate::Repo::import_media) gives this error.
    #[error("no media repository found")]
    MediaNotFound {
        /// Each candidate that exists and that the media finder skipped, with
        /// the reason, in probe order.
        skipped: Vec<(std::path::PathBuf, crate::media::MediaSkip)>,
    },
    /// More than one media repository on the mounted volumes.
    ///
    /// [`Repo::import_media`](crate::Repo::import_media) gives this error.
    #[error(
        "more than one media repository: {}",
        .paths.iter().map(|path| path.display().to_string()).collect::<Vec<_>>().join(", ")
    )]
    AmbiguousMedia {
        /// The path of each media repository, in the order of the mount
        /// table.
        paths: Vec<std::path::PathBuf>,
    },
    /// The writer lock of a bucket repository that another writer holds.
    ///
    /// The take of the lock found a lock. A take with no break of the lock
    /// wrote only the probe key. After a break of the lock, the lock that
    /// the break deleted stays deleted. [`bucket`](crate::bucket) states the
    /// writer lock.
    #[cfg(feature = "s3")]
    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
    #[error(
        "the bucket repository {address} is locked: {}",
        crate::bucket::describe_locked(.holder.as_deref())
    )]
    BucketLocked {
        /// The address of the repository, `s3://BUCKET[/PREFIX]`.
        address: String,
        /// The holder that the lock names, or `None` if the lock was gone
        /// at the read after the take. A new run can then take the lock.
        holder: Option<Box<crate::bucket::LockHolder>>,
    },
    /// A writer lock of a bucket repository that another writer broke.
    ///
    /// A check or a release of the lock found a lock with another id, a
    /// lock that names no id, or no lock. A writer that gets this error
    /// stops before its next change.
    ///
    /// A release whose delete removed the lock, but whose answer did not
    /// arrive, sends the delete again. If another writer took the lock
    /// between the two requests, the release gives this error with the
    /// holder of the new lock, although the release removed the lock of this
    /// writer before the other writer took its own.
    #[cfg(feature = "s3")]
    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
    #[error(
        "the writer lock of {address} was broken: {}",
        crate::bucket::describe_lost(.holder.as_deref())
    )]
    BucketLockLost {
        /// The address of the repository, `s3://BUCKET[/PREFIX]`.
        address: String,
        /// The holder of the lock that the key holds, or `None` if the key
        /// holds no lock.
        holder: Option<Box<crate::bucket::LockHolder>>,
    },
    /// An S3 server that writes over an object in spite of
    /// `If-None-Match: *`.
    ///
    /// The writer lock gives no exclusion on such a server, so no writer
    /// runs on it. The probe of the take finds this before a request to the
    /// lock key, so the call wrote no lock, and a lock that the key holds
    /// does not change.
    #[cfg(feature = "s3")]
    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
    #[error(
        "the S3 server of {address} does not honor If-None-Match, so the writer lock gives no \
         exclusion and no writer can run on it; the run wrote no lock"
    )]
    BucketNoExclusion {
        /// The address of the repository, `s3://BUCKET[/PREFIX]`.
        address: String,
    },
    /// A repair of a bucket repository that failed after its first change.
    ///
    /// [`BucketRepo::fsck`](crate::bucket::BucketRepo::fsck) with
    /// [`delete`](crate::bucket::BucketFsckOptions::delete) gives this error
    /// if a step of the repair fails after the check of the lock before its
    /// first write. The repair is incomplete: the bucket can hold a
    /// partial-commit marker of a commit whose bad objects are still in the
    /// bucket. A push of such a commit then uploads no object for them and
    /// deletes the marker. Run the fsck with `delete` again before a push.
    #[cfg(feature = "s3")]
    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
    #[error(
        "the repair of the bucket repository {address} is incomplete: {error}; run the fsck \
         with delete again before a push"
    )]
    BucketRepairIncomplete {
        /// The address of the repository, `s3://BUCKET[/PREFIX]`.
        address: String,
        /// The report of the run: the findings, and each marker write and
        /// each delete that completed before the failure.
        report: Box<crate::bucket::BucketFsckReport>,
        /// The failure of the repair.
        #[source]
        error: Box<Error>,
    },
    /// A signed summary update of a bucket repository whose `summary` and
    /// `summary.sig` can fail to match.
    ///
    /// [`BucketRepo::update_summary`](crate::bucket::BucketRepo::update_summary)
    /// with a summary signer gives this error if the write of `summary.sig`
    /// fails after the write of `summary`, or if the write of `summary` fails
    /// with an unknown outcome. The bucket can then hold a `summary.sig`
    /// that does not cover its `summary`, or no `summary.sig`, and a pull
    /// that verifies the summary then refuses it. A summary update again
    /// with the same signers writes a matching pair. Before it gives this
    /// error, the update tries to release its lock, and drops an error of
    /// that release.
    #[cfg(feature = "s3")]
    #[cfg_attr(docsrs, doc(cfg(feature = "s3")))]
    #[error(
        "the summary update of the bucket repository {address} {}",
        crate::bucket::describe_summary_incomplete(*.summary_written, .error)
    )]
    BucketSummaryIncomplete {
        /// The address of the repository, `s3://BUCKET[/PREFIX]`.
        address: String,
        /// `true` if the server accepted the write of `summary` and the
        /// write of `summary.sig` failed. `false` if the write of `summary`
        /// failed with an unknown outcome: the HTTP client failed, or the
        /// last answer was 408, 429, or 5xx.
        summary_written: bool,
        /// The report of the update, as a success gives it, with the holder
        /// of a broken lock.
        report: Box<crate::bucket::BucketSummaryReport>,
        /// The failure of the write.
        #[source]
        error: Box<Error>,
    },
}

impl From<rustix::io::Errno> for Error {
    fn from(errno: rustix::io::Errno) -> Error {
        Error::Io(errno.into())
    }
}

impl From<ostrya_core::ParseRefError> for Error {
    /// Maps a ref that fails the ref-name rule to [`Error::InvalidRefspec`]
    /// with the text of the ref.
    fn from(err: ostrya_core::ParseRefError) -> Error {
        Error::InvalidRefspec(err.as_str().to_owned())
    }
}

impl From<ostrya_sign::Error> for Error {
    /// Maps a signing-engine error to the variant of the same name.
    ///
    /// A variant that this conversion does not name maps to
    /// [`Error::Signature`] with the message of the error.
    fn from(err: ostrya_sign::Error) -> Error {
        match err {
            ostrya_sign::Error::Signature(message) => Error::Signature(message),
            ostrya_sign::Error::InvalidFormat(message) => Error::InvalidFormat(message),
            ostrya_sign::Error::Core(e) => Error::Core(e),
            other => Error::Signature(other.to_string()),
        }
    }
}

impl From<crate::fetch::Error> for Error {
    /// Maps a fetcher error to the variant of the same name.
    ///
    /// The variant gets the same fields, so the message stays the same. A
    /// variant that this conversion does not name maps to [`Error::Fetch`]
    /// with the message of the error.
    fn from(err: crate::fetch::Error) -> Error {
        use crate::fetch::Error as F;

        match err {
            F::Fetch(message) => Error::Fetch(message),
            F::HttpStatus { status, url, .. } => Error::HttpStatus { status, url },
            F::RedirectLimit { url, hops } => Error::RedirectLimit { url, hops },
            F::FetchTooLarge { limit } => Error::FetchTooLarge { limit },
            F::ContentEncoded { url, encoding } => Error::ContentEncoded { url, encoding },
            F::Unsupported(message) => Error::Unsupported(message),
            F::UploadInterrupted { url, message } => Error::UploadInterrupted { url, message },
            other => Error::Fetch(other.to_string()),
        }
    }
}

impl From<Error> for std::io::Error {
    /// Maps an error of this crate to the closest [`std::io::ErrorKind`].
    ///
    /// The I/O error holds the error as its payload, so its `Display` and its
    /// source chain stay. An [`Error::Io`] comes back unchanged.
    ///
    /// A variant gets a specific kind only if the standard set names the
    /// condition. A symlink loop maps to [`Other`](std::io::ErrorKind::Other),
    /// because `ErrorKind::FilesystemLoop` is unstable.
    ///
    /// Three fetch failures get their own kind:
    ///
    /// - An [`Error::HttpStatus`] of 404 maps to
    ///   [`NotFound`](std::io::ErrorKind::NotFound). A remote uses a 404 to
    ///   state that an object is absent.
    /// - A 401 and a 403 map to
    ///   [`PermissionDenied`](std::io::ErrorKind::PermissionDenied). Each
    ///   other status maps to [`Other`](std::io::ErrorKind::Other).
    /// - An [`Error::FetchTooLarge`] maps to
    ///   [`FileTooLarge`](std::io::ErrorKind::FileTooLarge).
    ///
    /// If a body grows past the cap while it streams, its read fails with the
    /// same `FileTooLarge` kind. The payload of that error is a message, so
    /// only the converted error downcasts to an error of this crate.
    fn from(err: Error) -> std::io::Error {
        use std::io::ErrorKind;

        let err = match err {
            Error::Io(e) => return e,
            other => other,
        };
        let kind = match &err {
            Error::PathNotFound { .. }
            | Error::DanglingSymlink { .. }
            | Error::ObjectNotFound { .. }
            | Error::MediaNotFound { .. }
            | Error::RefNotFound(_)
            | Error::RemoteNotFound(_)
            | Error::StaticDeltaNotFound { .. }
            | Error::HttpStatus { status: 404, .. } => ErrorKind::NotFound,
            Error::HttpStatus {
                status: 401 | 403, ..
            } => ErrorKind::PermissionDenied,
            Error::FetchTooLarge { .. } => ErrorKind::FileTooLarge,
            Error::NotADirectory { .. } | Error::ReplaceFileWithDir(_) => ErrorKind::NotADirectory,
            Error::EntryExists { .. }
            | Error::MergeConflict(_)
            | Error::ReplaceDirWithFile(_)
            | Error::RemoteExists(_)
            | Error::RepoExists(_) => ErrorKind::AlreadyExists,
            Error::MutableTree(_) | Error::InvalidInput(_) => ErrorKind::InvalidInput,
            _ => ErrorKind::Other,
        };
        std::io::Error::new(kind, err)
    }
}

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

    #[test]
    fn io_error_converts_displays_and_chains() {
        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "missing");
        let err: Error = io.into();
        assert!(matches!(err, Error::Io(_)));
        assert!(err.to_string().contains("i/o error"));
        assert!(std::error::Error::source(&err).is_some());
    }

    #[test]
    fn errors_convert_to_the_documented_io_kinds() {
        use std::io::ErrorKind;

        let path = || "usr/lib/modules".to_owned();
        let url = || "https://example.invalid/objects/ab.commit".to_owned();
        let cases: Vec<(Error, ErrorKind)> = vec![
            (Error::PathNotFound { path: path() }, ErrorKind::NotFound),
            (
                Error::DanglingSymlink {
                    path: path(),
                    target: "nowhere".into(),
                },
                ErrorKind::NotFound,
            ),
            (
                Error::ObjectNotFound {
                    checksum: Checksum::from_hex(&"ab".repeat(32)).unwrap(),
                    ty: ObjectType::Commit,
                },
                ErrorKind::NotFound,
            ),
            (
                Error::MediaNotFound {
                    skipped: Vec::new(),
                },
                ErrorKind::NotFound,
            ),
            (Error::RefNotFound("x/y".into()), ErrorKind::NotFound),
            (Error::RemoteNotFound("origin".into()), ErrorKind::NotFound),
            (
                Error::StaticDeltaNotFound {
                    from: None,
                    to: Checksum::from_hex(&"ab".repeat(32)).unwrap(),
                },
                ErrorKind::NotFound,
            ),
            (
                Error::NotADirectory { path: path() },
                ErrorKind::NotADirectory,
            ),
            (
                Error::ReplaceFileWithDir("etc".into()),
                ErrorKind::NotADirectory,
            ),
            (
                Error::EntryExists { path: path() },
                ErrorKind::AlreadyExists,
            ),
            (
                Error::MergeConflict("file differs at a".into()),
                ErrorKind::AlreadyExists,
            ),
            (
                Error::ReplaceDirWithFile("etc".into()),
                ErrorKind::AlreadyExists,
            ),
            (
                Error::RemoteExists("origin".into()),
                ErrorKind::AlreadyExists,
            ),
            (Error::RepoExists("repo".into()), ErrorKind::AlreadyExists),
            (
                Error::MutableTree("bad name".into()),
                ErrorKind::InvalidInput,
            ),
            (
                Error::InvalidInput("depth -2 is below -1".into()),
                ErrorKind::InvalidInput,
            ),
            (Error::SymlinkLoop { path: path() }, ErrorKind::Other),
            (
                Error::NotARef {
                    name: "origin:main".into(),
                    reason: "is not a regular file".into(),
                },
                ErrorKind::Other,
            ),
            (Error::Staging("directory is gone".into()), ErrorKind::Other),
            (
                Error::HttpStatus {
                    status: 404,
                    url: url(),
                },
                ErrorKind::NotFound,
            ),
            (
                Error::HttpStatus {
                    status: 401,
                    url: url(),
                },
                ErrorKind::PermissionDenied,
            ),
            (
                Error::HttpStatus {
                    status: 403,
                    url: url(),
                },
                ErrorKind::PermissionDenied,
            ),
            (
                Error::HttpStatus {
                    status: 400,
                    url: url(),
                },
                ErrorKind::Other,
            ),
            (
                Error::HttpStatus {
                    status: 429,
                    url: url(),
                },
                ErrorKind::Other,
            ),
            (
                Error::HttpStatus {
                    status: 500,
                    url: url(),
                },
                ErrorKind::Other,
            ),
            (
                Error::HttpStatus {
                    status: 502,
                    url: url(),
                },
                ErrorKind::Other,
            ),
            (
                Error::FetchTooLarge { limit: 4096 },
                ErrorKind::FileTooLarge,
            ),
            (
                Error::ContentEncoded {
                    url: url(),
                    encoding: "gzip".into(),
                },
                ErrorKind::Other,
            ),
        ];

        for (err, expected) in cases {
            let rendered = err.to_string();
            let io: std::io::Error = err.into();
            assert_eq!(io.kind(), expected, "kind for {rendered}");
            assert_eq!(io.to_string(), rendered, "the message survives");
        }
    }

    #[test]
    fn an_io_error_converts_back_unchanged() {
        use std::io::ErrorKind;

        let err = Error::Io(std::io::Error::new(ErrorKind::PermissionDenied, "nope"));
        let io: std::io::Error = err.into();
        assert_eq!(io.kind(), ErrorKind::PermissionDenied);
        assert_eq!(io.to_string(), "nope");
    }

    #[test]
    fn a_signing_error_maps_to_its_namesake() {
        let err = Error::from(ostrya_sign::Error::Signature("refused".into()));
        assert!(
            matches!(&err, Error::Signature(m) if m == "refused"),
            "{err}"
        );
        assert_eq!(
            err.to_string(),
            ostrya_sign::Error::Signature("refused".into()).to_string()
        );

        let err = Error::from(ostrya_sign::Error::InvalidFormat("not a dict".into()));
        assert!(
            matches!(&err, Error::InvalidFormat(m) if m == "not a dict"),
            "{err}"
        );
        assert_eq!(
            err.to_string(),
            ostrya_sign::Error::InvalidFormat("not a dict".into()).to_string()
        );

        let core = ostrya_core::Error::InvalidBase64("truncated group");
        let err = Error::from(ostrya_sign::Error::Core(core.clone()));
        assert!(matches!(&err, Error::Core(e) if *e == core), "{err}");
        assert_eq!(err.to_string(), ostrya_sign::Error::Core(core).to_string());
    }

    #[test]
    fn a_fetch_error_maps_to_its_namesake() {
        use crate::fetch::Error as F;
        use std::io::ErrorKind;

        let url = || "https://example.invalid/objects/ab.commit".to_owned();
        let cases: Vec<(F, ErrorKind)> = vec![
            (F::Fetch("connection reset".into()), ErrorKind::Other),
            (
                F::HttpStatus {
                    status: 404,
                    url: url(),
                    response: None,
                },
                ErrorKind::NotFound,
            ),
            (
                F::HttpStatus {
                    status: 401,
                    url: url(),
                    response: None,
                },
                ErrorKind::PermissionDenied,
            ),
            (
                F::HttpStatus {
                    status: 403,
                    url: url(),
                    response: None,
                },
                ErrorKind::PermissionDenied,
            ),
            (
                F::HttpStatus {
                    status: 500,
                    url: url(),
                    response: None,
                },
                ErrorKind::Other,
            ),
            (
                F::RedirectLimit {
                    url: url(),
                    hops: 10,
                },
                ErrorKind::Other,
            ),
            (F::FetchTooLarge { limit: 4096 }, ErrorKind::FileTooLarge),
            (
                F::ContentEncoded {
                    url: url(),
                    encoding: "gzip".into(),
                },
                ErrorKind::Other,
            ),
            (F::Unsupported("proxy url".into()), ErrorKind::Other),
            (
                F::UploadInterrupted {
                    url: url(),
                    message: "connection reset".into(),
                },
                ErrorKind::Other,
            ),
        ];

        for (fetch, expected) in cases {
            let rendered = fetch.to_string();
            let namesake = match &fetch {
                F::Fetch(m) => Error::Fetch(m.clone()),
                F::HttpStatus { status, url, .. } => Error::HttpStatus {
                    status: *status,
                    url: url.clone(),
                },
                F::RedirectLimit { url, hops } => Error::RedirectLimit {
                    url: url.clone(),
                    hops: *hops,
                },
                F::FetchTooLarge { limit } => Error::FetchTooLarge { limit: *limit },
                F::ContentEncoded { url, encoding } => Error::ContentEncoded {
                    url: url.clone(),
                    encoding: encoding.clone(),
                },
                F::Unsupported(m) => Error::Unsupported(m.clone()),
                F::UploadInterrupted { url, message } => Error::UploadInterrupted {
                    url: url.clone(),
                    message: message.clone(),
                },
                other => panic!("no namesake for {other:?}"),
            };
            let err = Error::from(fetch);
            assert_eq!(format!("{err:?}"), format!("{namesake:?}"));
            assert_eq!(err.to_string(), rendered);
            let io = std::io::Error::from(err);
            assert_eq!(io.kind(), expected, "kind for {rendered}");
            assert_eq!(io.to_string(), rendered);
        }
    }

    #[test]
    fn not_a_ref_shows_the_name_and_the_reason() {
        let err = Error::NotARef {
            name: "@org.example.Os:main".into(),
            reason: "is not a regular file".into(),
        };
        assert_eq!(
            err.to_string(),
            "not a ref: @org.example.Os:main: is not a regular file"
        );
        assert!(std::error::Error::source(&err).is_none());
    }

    #[test]
    fn format_and_unsupported_have_no_source() {
        let err = Error::InvalidFormat("bad header".into());
        assert!(err.to_string().contains("invalid format"));
        assert!(std::error::Error::source(&err).is_none());

        let err = Error::Unsupported("mode".into());
        assert!(err.to_string().contains("unsupported"));
        assert!(std::error::Error::source(&err).is_none());
    }
}