ostrya-core 0.19.0

ostree object model, checksums, on-disk format primitives, and typed config
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
//! The ref-name rule.
//!
//! `is_ref_name_component` checks one component of a ref name, `is_ref_name`
//! checks a whole ref name, and `is_refspec` checks a refspec. A component of
//! a ref name is not empty, does not start with `-` or `.`, and holds only
//! ASCII letters, ASCII digits, `-`, `.`, `_`, and non-ASCII characters for
//! which `char::is_alphanumeric` is `true`, less the characters that the
//! `ostree` tool refuses. The remote part of a refspec follows the rule of a
//! component. `is_ref_component` is a wider check for a part that is not a
//! ref name. `is_checksum_shaped` marks a valid ref name that a revision
//! reads as a checksum. `is_collection_id` checks a collection id.
//!
//! [`Ref`] is one ref of a repository: a local ref, a remote ref, or a
//! collection ref. It reads and gives back the text forms `NAME`,
//! `REMOTE:NAME`, and `@ID:NAME`.

use std::fmt;
use std::str::FromStr;

use crate::Checksum;

/// Characters for which `char::is_alphanumeric` is `true` and that the
/// `ostree` tool refuses in a ref name, as inclusive ranges in ascending
/// order. They are spacing combining marks, enclosed and circled letters, and
/// letters of a Unicode version that the tool does not know. The table is the
/// result of a probe of each alphanumeric character of Unicode 17.0.0 against
/// the tool. Rust 1.97.1 gives this version in `char::UNICODE_VERSION`.
const REFUSED_ALPHANUMERIC: &[(u32, u32)] = &[
    (0x903, 0x903),
    (0x93b, 0x93b),
    (0x93e, 0x940),
    (0x949, 0x94c),
    (0x94e, 0x94f),
    (0x982, 0x983),
    (0x9be, 0x9c0),
    (0x9c7, 0x9c8),
    (0x9cb, 0x9cc),
    (0x9d7, 0x9d7),
    (0xa03, 0xa03),
    (0xa3e, 0xa40),
    (0xa83, 0xa83),
    (0xabe, 0xac0),
    (0xac9, 0xac9),
    (0xacb, 0xacc),
    (0xb02, 0xb03),
    (0xb3e, 0xb3e),
    (0xb40, 0xb40),
    (0xb47, 0xb48),
    (0xb4b, 0xb4c),
    (0xb57, 0xb57),
    (0xbbe, 0xbbf),
    (0xbc1, 0xbc2),
    (0xbc6, 0xbc8),
    (0xbca, 0xbcc),
    (0xbd7, 0xbd7),
    (0xc01, 0xc03),
    (0xc41, 0xc44),
    (0xc82, 0xc83),
    (0xcbe, 0xcbe),
    (0xcc0, 0xcc4),
    (0xcc7, 0xcc8),
    (0xcca, 0xccb),
    (0xcd5, 0xcd6),
    (0xcf3, 0xcf3),
    (0xd02, 0xd03),
    (0xd3e, 0xd40),
    (0xd46, 0xd48),
    (0xd4a, 0xd4c),
    (0xd57, 0xd57),
    (0xd82, 0xd83),
    (0xdcf, 0xdd1),
    (0xdd8, 0xddf),
    (0xdf2, 0xdf3),
    (0xf7f, 0xf7f),
    (0x102b, 0x102c),
    (0x1031, 0x1031),
    (0x1038, 0x1038),
    (0x103b, 0x103c),
    (0x1056, 0x1057),
    (0x1062, 0x1064),
    (0x1067, 0x106d),
    (0x1083, 0x1084),
    (0x1087, 0x108c),
    (0x108f, 0x108f),
    (0x109a, 0x109c),
    (0x17b6, 0x17b6),
    (0x17be, 0x17c5),
    (0x17c7, 0x17c8),
    (0x1923, 0x1926),
    (0x1929, 0x192b),
    (0x1930, 0x1931),
    (0x1933, 0x1938),
    (0x1a19, 0x1a1a),
    (0x1a55, 0x1a55),
    (0x1a57, 0x1a57),
    (0x1a61, 0x1a61),
    (0x1a63, 0x1a64),
    (0x1a6d, 0x1a72),
    (0x1b04, 0x1b04),
    (0x1b35, 0x1b35),
    (0x1b3b, 0x1b3b),
    (0x1b3d, 0x1b41),
    (0x1b43, 0x1b43),
    (0x1b82, 0x1b82),
    (0x1ba1, 0x1ba1),
    (0x1ba6, 0x1ba7),
    (0x1be7, 0x1be7),
    (0x1bea, 0x1bec),
    (0x1bee, 0x1bee),
    (0x1c24, 0x1c2b),
    (0x1c34, 0x1c35),
    (0x24b6, 0x24e9),
    (0xa823, 0xa824),
    (0xa827, 0xa827),
    (0xa880, 0xa881),
    (0xa8b4, 0xa8c3),
    (0xa952, 0xa952),
    (0xa983, 0xa983),
    (0xa9b4, 0xa9b5),
    (0xa9ba, 0xa9bb),
    (0xa9be, 0xa9bf),
    (0xaa2f, 0xaa30),
    (0xaa33, 0xaa34),
    (0xaa4d, 0xaa4d),
    (0xaa7b, 0xaa7b),
    (0xaa7d, 0xaa7d),
    (0xaaeb, 0xaaeb),
    (0xaaee, 0xaaef),
    (0xaaf5, 0xaaf5),
    (0xabe3, 0xabe4),
    (0xabe6, 0xabe7),
    (0xabe9, 0xabea),
    (0x11000, 0x11000),
    (0x11002, 0x11002),
    (0x11082, 0x11082),
    (0x110b0, 0x110b2),
    (0x110b7, 0x110b8),
    (0x1112c, 0x1112c),
    (0x11145, 0x11146),
    (0x11182, 0x11182),
    (0x111b3, 0x111b5),
    (0x111bf, 0x111bf),
    (0x111ce, 0x111ce),
    (0x1122c, 0x1122e),
    (0x11232, 0x11233),
    (0x112e0, 0x112e2),
    (0x11302, 0x11303),
    (0x1133e, 0x1133f),
    (0x11341, 0x11344),
    (0x11347, 0x11348),
    (0x1134b, 0x1134c),
    (0x11357, 0x11357),
    (0x11362, 0x11363),
    (0x113b8, 0x113ba),
    (0x113c2, 0x113c2),
    (0x113c5, 0x113c5),
    (0x113c7, 0x113ca),
    (0x113cc, 0x113cd),
    (0x11435, 0x11437),
    (0x11440, 0x11441),
    (0x11445, 0x11445),
    (0x114b0, 0x114b2),
    (0x114b9, 0x114b9),
    (0x114bb, 0x114be),
    (0x114c1, 0x114c1),
    (0x115af, 0x115b1),
    (0x115b8, 0x115bb),
    (0x115be, 0x115be),
    (0x11630, 0x11632),
    (0x1163b, 0x1163c),
    (0x1163e, 0x1163e),
    (0x116ac, 0x116ac),
    (0x116ae, 0x116af),
    (0x1171e, 0x1171e),
    (0x11720, 0x11721),
    (0x11726, 0x11726),
    (0x1182c, 0x1182e),
    (0x11838, 0x11838),
    (0x11930, 0x11935),
    (0x11937, 0x11938),
    (0x11940, 0x11940),
    (0x11942, 0x11942),
    (0x119d1, 0x119d3),
    (0x119dc, 0x119df),
    (0x119e4, 0x119e4),
    (0x11a39, 0x11a39),
    (0x11a57, 0x11a58),
    (0x11a97, 0x11a97),
    (0x11b61, 0x11b61),
    (0x11b65, 0x11b65),
    (0x11b67, 0x11b67),
    (0x11c2f, 0x11c2f),
    (0x11c3e, 0x11c3e),
    (0x11ca9, 0x11ca9),
    (0x11cb1, 0x11cb1),
    (0x11cb4, 0x11cb4),
    (0x11d8a, 0x11d8e),
    (0x11d93, 0x11d94),
    (0x11d96, 0x11d96),
    (0x11ef5, 0x11ef6),
    (0x11f03, 0x11f03),
    (0x11f34, 0x11f35),
    (0x11f3e, 0x11f3f),
    (0x1612a, 0x1612c),
    (0x16f51, 0x16f87),
    (0x16ff0, 0x16ff1),
    (0x1f130, 0x1f149),
    (0x1f150, 0x1f169),
    (0x1f170, 0x1f189),
];

/// Returns `true` if `c` is a non-ASCII character that a component of a ref
/// name can hold.
fn is_name_character(c: char) -> bool {
    c.is_alphanumeric()
        && !REFUSED_ALPHANUMERIC
            .iter()
            .any(|&(first, last)| (first..=last).contains(&u32::from(c)))
}

/// Returns `true` if `component` is one valid component of a ref name.
///
/// A component is not empty and does not start with `-` or `.`. Each of its
/// characters is an ASCII letter, an ASCII digit, `-`, `.`, `_`, or a
/// non-ASCII character for which `char::is_alphanumeric` is `true`. So `.`
/// and `..` fail, and so does a component with `/`, `:`, a space, or NUL.
///
/// The tool also accepts a nonspacing combining mark (category Mn) and a
/// connector punctuation character that is not ASCII (category Pc), and this
/// function refuses them. The tool refuses the characters that
/// `REFUSED_ALPHANUMERIC` lists, and this function refuses them too. So each
/// name that this function accepts is a name that the tool accepts.
pub fn is_ref_name_component(component: &str) -> bool {
    !component.starts_with(['-', '.'])
        && !component.is_empty()
        && component.chars().all(|c| {
            if c.is_ascii() {
                c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')
            } else {
                is_name_character(c)
            }
        })
}

/// Returns `true` if `component` is one valid component of a part that is
/// not a ref name.
///
/// A component is not empty, is not `.` or `..`, and holds no `/` and no NUL.
/// A ref name uses the stricter [`is_ref_name_component`]. A collection id
/// uses [`is_collection_id`].
pub fn is_ref_component(component: &str) -> bool {
    !(component.is_empty()
        || component == "."
        || component == ".."
        || component.contains('/')
        || component.contains('\0'))
}

/// Returns `true` if `name` is a valid ref name.
///
/// A ref name is a path below `refs/heads`. It is not empty, and each of its
/// `/`-separated components passes [`is_ref_name_component`]. The rule keeps
/// each name inside the `refs/` tree.
pub fn is_ref_name(name: &str) -> bool {
    !name.is_empty() && name.split('/').all(is_ref_name_component)
}

/// Returns `true` if `refspec` is a valid refspec.
///
/// A refspec is a ref name, or `REMOTE:NAME` split at the first `:`. In the
/// second form, `REMOTE` must pass [`is_ref_name_component`] and `NAME` must
/// pass [`is_ref_name`]. So `NAME` holds no `:`. Such a refspec names a path below
/// `refs/remotes/REMOTE`, so it stays inside the `refs/` tree.
pub fn is_refspec(refspec: &str) -> bool {
    match refspec.split_once(':') {
        Some((remote, name)) => is_ref_name_component(remote) && is_ref_name(name),
        None => is_ref_name(refspec),
    }
}

/// Returns `true` if `name` is 64 lowercase hex characters.
///
/// Such a name passes [`is_ref_name`]. A revision reads it as a commit
/// checksum. A push refuses to write a commit to a ref of that name. A name
/// with an uppercase hex character gives `false`.
pub fn is_checksum_shaped(name: &str) -> bool {
    Checksum::from_hex_lower(name).is_ok()
}

/// Returns `true` if `id` is a collection id.
///
/// A collection id has two or more elements, separated by `.`. Each element
/// starts with an ASCII letter or `_` and continues with ASCII letters,
/// digits, or `_`.
///
/// Recovered by observation: the `ostree` command writes `a.b`, `A.b`,
/// `_a.b`, `a._b`, `a_b.c`, and `a.b.c.d`. It refuses `fresh`, `a..b`,
/// `a.b.`, `1a.b`, `a.1b`, `a-b.c`, and `a.b-c` with
/// `error: Invalid collection ID <id>`. Only the file system limits the
/// length, because the id is one path component.
pub fn is_collection_id(id: &str) -> bool {
    id.split('.').count() >= 2
        && id.split('.').all(|element| {
            let mut chars = element.chars();
            chars
                .next()
                .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
        })
}

/// The longest collection id, in bytes, that [`Ref::validate`] accepts.
///
/// The id is one path component under `refs/mirrors/`, and a Linux file
/// system takes a name of 255 bytes at most (`NAME_MAX`).
pub const MAX_COLLECTION_ID_LEN: usize = 255;

/// Returns `true` if `id` is a valid collection id for a ref: it passes
/// [`is_collection_id`] and is at most [`MAX_COLLECTION_ID_LEN`] bytes.
pub fn is_valid_collection_id(id: &str) -> bool {
    id.len() <= MAX_COLLECTION_ID_LEN && is_collection_id(id)
}

/// Splits `@ID:REST` at the first `:` after the `@`.
///
/// Returns the id and the rest, or `None` if `text` does not start with `@`
/// or has no `:` after it. The call does not check the id or the rest. Use
/// [`is_valid_collection_id`] for the id.
pub fn split_collection(text: &str) -> Option<(&str, &str)> {
    text.strip_prefix('@')?.split_once(':')
}

/// One ref of a repository.
///
/// A ref has three cases, and each case has a text form:
///
/// - `NAME` is the local ref [`Ref::Local`], at `refs/heads/NAME`.
/// - `REMOTE:NAME` is the remote ref [`Ref::Remote`], at
///   `refs/remotes/REMOTE/NAME`.
/// - `@ID:NAME` is the collection ref [`Ref::Collection`], at
///   `refs/mirrors/ID/NAME`. A repository whose `[core] collection-id` is
///   `ID` keeps the ref at `refs/heads/NAME`, so `@ID:NAME` and `NAME` name
///   the same ref there. [`canonical`](Ref::canonical) gives the local form.
///
/// No valid ref name holds `@` or `:`, so the three forms do not overlap.
///
/// The constructors do not check the value. [`validate`](Ref::validate)
/// checks it, and a ref store checks it before it reads or writes a file.
/// [`FromStr`] reads the text and checks it. [`Display`](fmt::Display) gives
/// the same text back.
///
/// # Examples
///
/// ```
/// use ostrya_core::Ref;
///
/// let r: Ref = "@org.example.Os:os/x86_64".parse()?;
/// assert_eq!(r, Ref::collection("org.example.Os", "os/x86_64"));
/// assert_eq!(r.name(), "os/x86_64");
/// assert_eq!(r.to_string(), "@org.example.Os:os/x86_64");
/// assert_eq!("origin:main".parse::<Ref>()?, Ref::remote("origin", "main"));
/// assert!("@org.example.Os:a:b".parse::<Ref>().is_err());
/// # Ok::<(), ostrya_core::ParseRefError>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Ref {
    /// A local ref, at `refs/heads/<name>`.
    Local {
        /// The ref name, which can contain `/`.
        name: String,
    },
    /// A remote ref, at `refs/remotes/<remote>/<name>`.
    Remote {
        /// The name of the remote.
        remote: String,
        /// The ref name, which can contain `/`.
        name: String,
    },
    /// A collection ref, at `refs/mirrors/<id>/<name>`, or at
    /// `refs/heads/<name>` when `id` is the `[core] collection-id` of the
    /// repository.
    Collection {
        /// The collection id.
        id: String,
        /// The ref name, which can contain `/`.
        name: String,
    },
}

impl Ref {
    /// Creates a local ref. The call does not check the name.
    pub fn local(name: impl Into<String>) -> Ref {
        Ref::Local { name: name.into() }
    }

    /// Creates a remote ref. The call does not check the values.
    pub fn remote(remote: impl Into<String>, name: impl Into<String>) -> Ref {
        Ref::Remote {
            remote: remote.into(),
            name: name.into(),
        }
    }

    /// Creates a collection ref. The call does not check the values.
    pub fn collection(id: impl Into<String>, name: impl Into<String>) -> Ref {
        Ref::Collection {
            id: id.into(),
            name: name.into(),
        }
    }

    /// Returns the ref name, without the remote or the collection id.
    pub fn name(&self) -> &str {
        match self {
            Ref::Local { name } | Ref::Remote { name, .. } | Ref::Collection { name, .. } => name,
        }
    }

    /// Returns the canonical form of the ref in a repository whose
    /// `[core] collection-id` is `own`.
    ///
    /// A collection ref of `own` is the local ref of the same name, because
    /// the repository keeps it at `refs/heads/<name>`. Each other ref is
    /// returned unchanged, and so is each ref if `own` is `None`. The call
    /// does not check the ref or `own`.
    pub fn canonical(self, own: Option<&str>) -> Ref {
        match self {
            Ref::Collection { id, name } if Some(id.as_str()) == own => Ref::Local { name },
            r => r,
        }
    }

    /// Puts a local ref in the collection `id`.
    ///
    /// A local ref `NAME` becomes `@ID:NAME`. A collection ref of `id` stays,
    /// and so does a remote ref. The call does not check the ref or `id`.
    ///
    /// # Errors
    ///
    /// Gives back the ref unchanged if it is a collection ref of another id.
    pub fn in_collection(self, id: &str) -> Result<Ref, Ref> {
        match self {
            Ref::Local { name } => Ok(Ref::collection(id, name)),
            Ref::Collection { id: ref other, .. } if other != id => Err(self),
            r => Ok(r),
        }
    }

    /// Returns the namespace of the ref: the local refs, the refs of one
    /// remote, or the refs of one collection id.
    ///
    /// The call does not canonicalize the ref. A collection ref of the own
    /// id of a repository is in the namespace of its local refs only after
    /// [`canonical`](Ref::canonical).
    pub fn namespace(&self) -> RefNamespace<'_> {
        match self {
            Ref::Local { .. } => RefNamespace::Local,
            Ref::Remote { remote, .. } => RefNamespace::Remote(remote),
            Ref::Collection { id, .. } => RefNamespace::Collection(id),
        }
    }

    /// Returns `true` if the refs `self` and `other` are in one namespace:
    /// both local, both of one remote, or both of one collection id.
    pub fn same_namespace(&self, other: &Ref) -> bool {
        self.namespace() == other.namespace()
    }

    /// Returns the first ref of `refs` that is in another collection than
    /// an earlier ref of `refs`, with that earlier ref.
    ///
    /// The refs that are not collection refs are ignored. The call returns
    /// `None` if the collection refs of `refs` hold one collection id.
    pub fn collection_conflict<'a>(
        refs: impl IntoIterator<Item = &'a Ref>,
    ) -> Option<(&'a Ref, &'a Ref)> {
        let mut first: Option<(&Ref, &str)> = None;
        for r in refs {
            let Ref::Collection { id, .. } = r else {
                continue;
            };
            match first {
                Some((other, other_id)) if other_id != id => return Some((other, r)),
                Some(_) => {}
                None => first = Some((r, id)),
            }
        }
        None
    }

    /// Checks the ref against the ref-name rule.
    ///
    /// The ref name must pass [`is_ref_name`] in each case. The remote of
    /// [`Ref::Remote`] must pass [`is_ref_name_component`]. The id of
    /// [`Ref::Collection`] must pass [`is_collection_id`] and be at most
    /// [`MAX_COLLECTION_ID_LEN`] bytes. So the path of a valid ref stays
    /// inside the `refs/` tree.
    ///
    /// # Errors
    ///
    /// [`ParseRefError`] if a part fails its rule. The error holds the text
    /// of the ref.
    pub fn validate(&self) -> Result<(), ParseRefError> {
        let valid = match self {
            Ref::Local { name } => is_ref_name(name),
            Ref::Remote { remote, name } => is_ref_name_component(remote) && is_ref_name(name),
            Ref::Collection { id, name } => is_valid_collection_id(id) && is_ref_name(name),
        };
        if valid {
            Ok(())
        } else {
            Err(ParseRefError {
                text: self.to_string(),
            })
        }
    }
}

impl FromStr for Ref {
    type Err = ParseRefError;

    /// Reads the text form of a ref and checks it with
    /// [`validate`](Ref::validate).
    ///
    /// Text that starts with `@` is a collection ref, split at the first `:`
    /// after the `@`. Other text with a `:` is a remote ref, split at the
    /// first `:`. Text with no `:` is a local ref.
    ///
    /// # Errors
    ///
    /// [`ParseRefError`] if the text has no form or a part fails its rule.
    /// The error holds the text as given.
    fn from_str(text: &str) -> Result<Ref, ParseRefError> {
        let parsed = if text.starts_with('@') {
            split_collection(text).map(|(id, name)| Ref::collection(id, name))
        } else {
            Some(match text.split_once(':') {
                Some((remote, name)) => Ref::remote(remote, name),
                None => Ref::local(text),
            })
        };
        match parsed {
            Some(r) if r.validate().is_ok() => Ok(r),
            _ => Err(ParseRefError {
                text: text.to_owned(),
            }),
        }
    }
}

impl fmt::Display for Ref {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Ref::Local { name } => f.write_str(name),
            Ref::Remote { remote, name } => write!(f, "{remote}:{name}"),
            Ref::Collection { id, name } => write!(f, "@{id}:{name}"),
        }
    }
}

/// The error of a ref that fails the rule of [`Ref::validate`], or text that
/// [`Ref`] does not read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseRefError {
    text: String,
}

impl ParseRefError {
    /// Returns the text of the ref that failed.
    pub fn as_str(&self) -> &str {
        &self.text
    }
}

/// The namespace of a [`Ref`], as [`Ref::namespace`] returns it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RefNamespace<'a> {
    /// The local refs.
    Local,
    /// The refs of the remote with this name.
    Remote(&'a str),
    /// The refs of the collection with this id.
    Collection(&'a str),
}

impl fmt::Display for ParseRefError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid ref: {}", self.text)
    }
}

impl std::error::Error for ParseRefError {}

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

    #[test]
    fn a_collection_ref_of_the_own_id_is_the_local_ref() {
        let own = Some("org.example.Os");
        assert_eq!(
            Ref::collection("org.example.Os", "a/b").canonical(own),
            Ref::local("a/b")
        );
        for r in [
            Ref::collection("org.example.B", "a"),
            Ref::local("a"),
            Ref::remote("origin", "a"),
        ] {
            assert_eq!(r.clone().canonical(own), r);
        }
        let r = Ref::collection("org.example.Os", "a");
        assert_eq!(r.clone().canonical(None), r);
    }

    #[test]
    fn a_ref_in_a_collection_takes_its_id() {
        let id = "org.example.Os";
        assert_eq!(
            Ref::local("a/b").in_collection(id),
            Ok(Ref::collection(id, "a/b"))
        );
        for r in [Ref::collection(id, "a"), Ref::remote("origin", "a")] {
            assert_eq!(r.clone().in_collection(id), Ok(r));
        }
        let other = Ref::collection("org.example.B", "a");
        assert_eq!(other.clone().in_collection(id), Err(other));
    }

    #[test]
    fn a_ref_gives_its_namespace() {
        assert_eq!(Ref::local("a").namespace(), RefNamespace::Local);
        assert_eq!(Ref::remote("o", "a").namespace(), RefNamespace::Remote("o"));
        assert_eq!(
            Ref::collection("org.example.A", "a").namespace(),
            RefNamespace::Collection("org.example.A")
        );
    }

    #[test]
    fn same_namespace_compares_the_kind_and_the_owner() {
        let local = Ref::local("a");
        let remote = Ref::remote("o", "a");
        let a = Ref::collection("org.example.A", "a");
        let b = Ref::collection("org.example.B", "a");
        assert!(local.same_namespace(&Ref::local("b")));
        assert!(!remote.same_namespace(&local));
        assert!(remote.same_namespace(&Ref::remote("o", "b")));
        assert!(!remote.same_namespace(&Ref::remote("p", "a")));
        assert!(a.same_namespace(&Ref::collection("org.example.A", "b")));
        assert!(!a.same_namespace(&b));
        assert!(!a.same_namespace(&local));
        let own = Some("org.example.A");
        assert!(a.clone().canonical(own).same_namespace(&local));
        assert!(!b.canonical(own).same_namespace(&local));
    }

    #[test]
    fn collection_conflict_returns_the_first_pair_of_two_ids() {
        let a = Ref::collection("org.example.A", "a");
        let a2 = Ref::collection("org.example.A", "b");
        let b = Ref::collection("org.example.B", "a");
        let c = Ref::collection("org.example.C", "a");
        let local = Ref::local("x");
        assert_eq!(Ref::collection_conflict([]), None);
        assert_eq!(Ref::collection_conflict([&a]), None);
        assert_eq!(Ref::collection_conflict([&local, &a, &local, &a2]), None);
        assert_eq!(
            Ref::collection_conflict([&a, &local, &b, &c]),
            Some((&a, &b))
        );
        assert_eq!(Ref::collection_conflict([&a, &a2, &c, &b]), Some((&a, &c)));
    }

    #[test]
    fn a_ref_name_holds_components_of_the_rule() {
        for name in [
            "main",
            "a/b/c",
            "x.y",
            "a.",
            "a..b",
            "a.b",
            "a/b.",
            "_a",
            "a_b",
            "a/_b",
            "a-b",
            "1a",
            "A",
            "\u{e9}",
            "a\u{e9}",
            "\u{e9}a",
            "a/\u{e9}b",
            "\u{e9}/a",
        ] {
            assert!(is_ref_name(name), "{name}");
        }
        for name in [
            "", "/", "/a", "a/", "a//b", ".", "..", "a/./b", "a/../b", "a\0b", "-dash", "a^",
            "a:b", "..x", ".a", "a/.b", "a/-b", "a/..", "a*", "*", "a/*", "a/**", "!x", "x!",
            "a/!b", "a?b", "a[b]", "a b", "a~b", "a^b", "a@b", "a+b", "a,b", "a%b", "a=b", "a#b",
            "a\\b", "a'b", "a\"b", "a$b", "a&b", "a;b", "a|b", "a<b", "a(b", "a{b", "a`b", "-a",
        ] {
            assert!(!is_ref_name(name), "{name:?}");
        }
    }

    #[test]
    fn a_refspec_splits_at_the_first_colon() {
        for spec in [
            "main",
            "a/b",
            "origin:main",
            "origin:a/b",
            "o.:main",
            "_o:main",
            "o-:main",
            "\u{e9}:main",
        ] {
            assert!(is_refspec(spec), "{spec}");
        }
        for spec in [
            "",
            ":",
            ":main",
            "origin:",
            "a/b:main",
            "..:main",
            ".:main",
            "o:..",
            "o:a/../b",
            "o\0:main",
            "o:a:b",
            "o:a b",
            "o:-a",
            "o r:main",
            "o*:main",
            "-o:main",
            ".o:main",
            "o~:main",
            "o^:main",
            "o@:main",
            "o\u{a0}:main",
        ] {
            assert!(!is_refspec(spec), "{spec:?}");
        }
    }

    #[test]
    fn a_ref_name_component_follows_the_character_rule() {
        for c in ["a", "a.b", "a.", "_a", "1a", "\u{e9}", "a\u{e9}"] {
            assert!(is_ref_name_component(c), "{c:?}");
        }
        for c in ["", ".", "..", ".a", "-a", "a/b", "a:b", "a b", "a*", "a\0"] {
            assert!(!is_ref_name_component(c), "{c:?}");
        }
    }

    /// Each character is one that the `ostree` tool accepts or refuses in a
    /// ref name, by a probe of the tool.
    #[test]
    fn a_non_ascii_character_is_valid_if_it_is_alphanumeric() {
        for c in [
            '\u{e9}', '\u{b5}', '\u{2d0}', '\u{4e2d}', '\u{b2}', '\u{2160}', '\u{660}', '\u{aa}',
            '\u{ba}', '\u{bc}',
        ] {
            assert!(is_ref_name_component(&format!("a{c}b")), "{c:?}");
            assert!(is_ref_name_component(&c.to_string()), "{c:?}");
        }
        for c in [
            '\u{80}',
            '\u{85}',
            '\u{a0}',
            '\u{ad}',
            '\u{d7}',
            '\u{2013}',
            '\u{200b}',
            '\u{20ac}',
            '\u{feff}',
            '\u{e000}',
            '\u{1f600}',
            '\u{fffd}',
            '\u{2028}',
            '\u{3000}',
            '\u{ffff}',
            '\u{10ffff}',
        ] {
            assert!(!is_ref_name_component(&format!("a{c}b")), "{c:?}");
            assert!(!is_ref_name_component(&c.to_string()), "{c:?}");
        }
    }

    /// The tool accepts these characters. The port refuses them, so it never
    /// writes a name that the tool might skip.
    #[test]
    fn a_non_ascii_character_that_the_tool_accepts_but_is_not_alphanumeric_is_refused() {
        for c in ['\u{301}', '\u{203f}', '\u{ff3f}'] {
            assert!(!is_ref_name_component(&format!("a{c}b")), "{c:?}");
        }
    }

    /// The tool refuses these alphanumeric characters: spacing combining
    /// marks, circled letters, and enclosed letters.
    #[test]
    fn an_alphanumeric_character_that_the_tool_refuses_is_refused() {
        for c in ['\u{903}', '\u{93e}', '\u{24b6}', '\u{1f130}', '\u{1f170}'] {
            assert!(c.is_alphanumeric(), "{c:?}");
            assert!(!is_ref_name_component(&format!("a{c}b")), "{c:?}");
        }
        for pair in REFUSED_ALPHANUMERIC.windows(2) {
            assert!(pair[0].1 < pair[1].0, "{pair:?}");
        }
    }

    #[test]
    fn a_component_holds_no_slash_and_no_nul() {
        assert!(is_ref_component("a.b"));
        assert!(is_ref_component("a:b"));
        for c in ["", ".", "..", "a/b", "a\0"] {
            assert!(!is_ref_component(c), "{c:?}");
        }
    }

    #[test]
    fn a_checksum_shaped_name_is_64_lowercase_hex_characters() {
        let hex = "0123456789abcdef".repeat(4);
        assert!(is_checksum_shaped(&hex));
        assert!(is_ref_name(&hex));
        let mut one_off = hex.clone();
        one_off.replace_range(10..11, "g");
        for name in [
            hex.to_uppercase(),
            format!("A{}", &hex[1..]),
            hex[..63].to_owned(),
            format!("{hex}0"),
            one_off,
            format!("origin:{hex}"),
            String::new(),
        ] {
            assert!(!is_checksum_shaped(&name), "{name}");
        }
    }

    /// The ids that the `ostree` command writes are collection ids, and the
    /// ids that it refuses are not.
    #[test]
    fn a_collection_id_has_two_or_more_elements_of_the_rule() {
        for id in ["a.b", "A.b", "_a.b", "a._b", "a_b.c", "a.b.c.d"] {
            assert!(is_collection_id(id), "{id}");
        }
        for id in [
            "fresh", "a..b", "a.b.", "1a.b", "a.1b", "a-b.c", "a.b-c", "", ".", ".a.b", "a.b c",
            "a.\u{e9}",
        ] {
            assert!(!is_collection_id(id), "{id:?}");
        }
    }

    #[test]
    fn split_collection_splits_at_the_first_colon_without_checking() {
        assert_eq!(split_collection("@a.b:c:d"), Some(("a.b", "c:d")));
        assert_eq!(split_collection("@a.b:"), Some(("a.b", "")));
        assert_eq!(split_collection("@nodot:x"), Some(("nodot", "x")));
        for text in ["a.b:c", "@a.b", "@", ""] {
            assert_eq!(split_collection(text), None, "{text:?}");
        }
    }

    #[test]
    fn a_valid_collection_id_is_a_collection_id_of_at_most_the_limit() {
        let longest = format!("a.{}", "b".repeat(MAX_COLLECTION_ID_LEN - 2));
        assert!(is_valid_collection_id(&longest));
        assert!(!is_valid_collection_id(&format!("{longest}b")));
        assert!(is_valid_collection_id("org.example.Os"));
        assert!(!is_valid_collection_id("nodot"));
        assert!(!is_valid_collection_id(""));
    }

    #[test]
    fn a_ref_reads_each_text_form_and_gives_the_text_back() {
        for (text, expected) in [
            ("main", Ref::local("main")),
            ("a/b", Ref::local("a/b")),
            ("origin:main", Ref::remote("origin", "main")),
            (
                "@org.example.Os:os/x86_64",
                Ref::collection("org.example.Os", "os/x86_64"),
            ),
        ] {
            let parsed: Ref = text.parse().unwrap();
            assert_eq!(parsed, expected, "{text}");
            assert_eq!(parsed.to_string(), text);
            assert_eq!(parsed.to_string().parse::<Ref>().unwrap(), parsed);
        }
    }

    #[test]
    fn a_ref_refuses_text_that_has_no_form_or_fails_the_rule() {
        let longest_id = format!("a.{}", "b".repeat(MAX_COLLECTION_ID_LEN - 2));
        assert!(format!("@{longest_id}:x").parse::<Ref>().is_ok());
        let too_long_id = format!("@{longest_id}b:x");
        for text in [
            "@",
            "@org.example.Os",
            "@org.example.Os:",
            "@bad-id:x",
            "@org.example.Os:a:b",
            too_long_id.as_str(),
            "",
            "a:b:c",
            ":a",
        ] {
            let err = text.parse::<Ref>().unwrap_err();
            assert_eq!(err.as_str(), text);
            assert_eq!(err.to_string(), format!("invalid ref: {text}"));
        }
    }

    #[test]
    fn a_ref_that_fails_the_rule_gives_its_text_in_the_error() {
        for (r, text) in [
            (Ref::local("a/../b"), "a/../b"),
            (Ref::local("origin:main"), "origin:main"),
            (Ref::remote("a/b", "main"), "a/b:main"),
            (Ref::collection("a", "main"), "@a:main"),
            (
                Ref::collection("org.example.B", "-bad"),
                "@org.example.B:-bad",
            ),
        ] {
            assert_eq!(r.validate().unwrap_err().as_str(), text);
        }
        assert!(Ref::local("main").validate().is_ok());
        assert_eq!(Ref::remote("origin", "a/b").name(), "a/b");
    }
}