Skip to main content

ostrya_core/
refname.rs

1//! The ref-name rule.
2//!
3//! `is_ref_name_component` checks one component of a ref name, `is_ref_name`
4//! checks a whole ref name, and `is_refspec` checks a refspec. A component of
5//! a ref name is not empty, does not start with `-` or `.`, and holds only
6//! ASCII letters, ASCII digits, `-`, `.`, `_`, and non-ASCII characters for
7//! which `char::is_alphanumeric` is `true`, less the characters that the
8//! `ostree` tool refuses. The remote part of a refspec follows the rule of a
9//! component. `is_ref_component` is a wider check for a part that is not a
10//! ref name. `is_checksum_shaped` marks a valid ref name that a revision
11//! reads as a checksum. `is_collection_id` checks a collection id.
12//!
13//! [`Ref`] is one ref of a repository: a local ref, a remote ref, or a
14//! collection ref. It reads and gives back the text forms `NAME`,
15//! `REMOTE:NAME`, and `@ID:NAME`.
16
17use std::fmt;
18use std::str::FromStr;
19
20use crate::Checksum;
21
22/// Characters for which `char::is_alphanumeric` is `true` and that the
23/// `ostree` tool refuses in a ref name, as inclusive ranges in ascending
24/// order. They are spacing combining marks, enclosed and circled letters, and
25/// letters of a Unicode version that the tool does not know. The table is the
26/// result of a probe of each alphanumeric character of Unicode 17.0.0 against
27/// the tool. Rust 1.97.1 gives this version in `char::UNICODE_VERSION`.
28const REFUSED_ALPHANUMERIC: &[(u32, u32)] = &[
29    (0x903, 0x903),
30    (0x93b, 0x93b),
31    (0x93e, 0x940),
32    (0x949, 0x94c),
33    (0x94e, 0x94f),
34    (0x982, 0x983),
35    (0x9be, 0x9c0),
36    (0x9c7, 0x9c8),
37    (0x9cb, 0x9cc),
38    (0x9d7, 0x9d7),
39    (0xa03, 0xa03),
40    (0xa3e, 0xa40),
41    (0xa83, 0xa83),
42    (0xabe, 0xac0),
43    (0xac9, 0xac9),
44    (0xacb, 0xacc),
45    (0xb02, 0xb03),
46    (0xb3e, 0xb3e),
47    (0xb40, 0xb40),
48    (0xb47, 0xb48),
49    (0xb4b, 0xb4c),
50    (0xb57, 0xb57),
51    (0xbbe, 0xbbf),
52    (0xbc1, 0xbc2),
53    (0xbc6, 0xbc8),
54    (0xbca, 0xbcc),
55    (0xbd7, 0xbd7),
56    (0xc01, 0xc03),
57    (0xc41, 0xc44),
58    (0xc82, 0xc83),
59    (0xcbe, 0xcbe),
60    (0xcc0, 0xcc4),
61    (0xcc7, 0xcc8),
62    (0xcca, 0xccb),
63    (0xcd5, 0xcd6),
64    (0xcf3, 0xcf3),
65    (0xd02, 0xd03),
66    (0xd3e, 0xd40),
67    (0xd46, 0xd48),
68    (0xd4a, 0xd4c),
69    (0xd57, 0xd57),
70    (0xd82, 0xd83),
71    (0xdcf, 0xdd1),
72    (0xdd8, 0xddf),
73    (0xdf2, 0xdf3),
74    (0xf7f, 0xf7f),
75    (0x102b, 0x102c),
76    (0x1031, 0x1031),
77    (0x1038, 0x1038),
78    (0x103b, 0x103c),
79    (0x1056, 0x1057),
80    (0x1062, 0x1064),
81    (0x1067, 0x106d),
82    (0x1083, 0x1084),
83    (0x1087, 0x108c),
84    (0x108f, 0x108f),
85    (0x109a, 0x109c),
86    (0x17b6, 0x17b6),
87    (0x17be, 0x17c5),
88    (0x17c7, 0x17c8),
89    (0x1923, 0x1926),
90    (0x1929, 0x192b),
91    (0x1930, 0x1931),
92    (0x1933, 0x1938),
93    (0x1a19, 0x1a1a),
94    (0x1a55, 0x1a55),
95    (0x1a57, 0x1a57),
96    (0x1a61, 0x1a61),
97    (0x1a63, 0x1a64),
98    (0x1a6d, 0x1a72),
99    (0x1b04, 0x1b04),
100    (0x1b35, 0x1b35),
101    (0x1b3b, 0x1b3b),
102    (0x1b3d, 0x1b41),
103    (0x1b43, 0x1b43),
104    (0x1b82, 0x1b82),
105    (0x1ba1, 0x1ba1),
106    (0x1ba6, 0x1ba7),
107    (0x1be7, 0x1be7),
108    (0x1bea, 0x1bec),
109    (0x1bee, 0x1bee),
110    (0x1c24, 0x1c2b),
111    (0x1c34, 0x1c35),
112    (0x24b6, 0x24e9),
113    (0xa823, 0xa824),
114    (0xa827, 0xa827),
115    (0xa880, 0xa881),
116    (0xa8b4, 0xa8c3),
117    (0xa952, 0xa952),
118    (0xa983, 0xa983),
119    (0xa9b4, 0xa9b5),
120    (0xa9ba, 0xa9bb),
121    (0xa9be, 0xa9bf),
122    (0xaa2f, 0xaa30),
123    (0xaa33, 0xaa34),
124    (0xaa4d, 0xaa4d),
125    (0xaa7b, 0xaa7b),
126    (0xaa7d, 0xaa7d),
127    (0xaaeb, 0xaaeb),
128    (0xaaee, 0xaaef),
129    (0xaaf5, 0xaaf5),
130    (0xabe3, 0xabe4),
131    (0xabe6, 0xabe7),
132    (0xabe9, 0xabea),
133    (0x11000, 0x11000),
134    (0x11002, 0x11002),
135    (0x11082, 0x11082),
136    (0x110b0, 0x110b2),
137    (0x110b7, 0x110b8),
138    (0x1112c, 0x1112c),
139    (0x11145, 0x11146),
140    (0x11182, 0x11182),
141    (0x111b3, 0x111b5),
142    (0x111bf, 0x111bf),
143    (0x111ce, 0x111ce),
144    (0x1122c, 0x1122e),
145    (0x11232, 0x11233),
146    (0x112e0, 0x112e2),
147    (0x11302, 0x11303),
148    (0x1133e, 0x1133f),
149    (0x11341, 0x11344),
150    (0x11347, 0x11348),
151    (0x1134b, 0x1134c),
152    (0x11357, 0x11357),
153    (0x11362, 0x11363),
154    (0x113b8, 0x113ba),
155    (0x113c2, 0x113c2),
156    (0x113c5, 0x113c5),
157    (0x113c7, 0x113ca),
158    (0x113cc, 0x113cd),
159    (0x11435, 0x11437),
160    (0x11440, 0x11441),
161    (0x11445, 0x11445),
162    (0x114b0, 0x114b2),
163    (0x114b9, 0x114b9),
164    (0x114bb, 0x114be),
165    (0x114c1, 0x114c1),
166    (0x115af, 0x115b1),
167    (0x115b8, 0x115bb),
168    (0x115be, 0x115be),
169    (0x11630, 0x11632),
170    (0x1163b, 0x1163c),
171    (0x1163e, 0x1163e),
172    (0x116ac, 0x116ac),
173    (0x116ae, 0x116af),
174    (0x1171e, 0x1171e),
175    (0x11720, 0x11721),
176    (0x11726, 0x11726),
177    (0x1182c, 0x1182e),
178    (0x11838, 0x11838),
179    (0x11930, 0x11935),
180    (0x11937, 0x11938),
181    (0x11940, 0x11940),
182    (0x11942, 0x11942),
183    (0x119d1, 0x119d3),
184    (0x119dc, 0x119df),
185    (0x119e4, 0x119e4),
186    (0x11a39, 0x11a39),
187    (0x11a57, 0x11a58),
188    (0x11a97, 0x11a97),
189    (0x11b61, 0x11b61),
190    (0x11b65, 0x11b65),
191    (0x11b67, 0x11b67),
192    (0x11c2f, 0x11c2f),
193    (0x11c3e, 0x11c3e),
194    (0x11ca9, 0x11ca9),
195    (0x11cb1, 0x11cb1),
196    (0x11cb4, 0x11cb4),
197    (0x11d8a, 0x11d8e),
198    (0x11d93, 0x11d94),
199    (0x11d96, 0x11d96),
200    (0x11ef5, 0x11ef6),
201    (0x11f03, 0x11f03),
202    (0x11f34, 0x11f35),
203    (0x11f3e, 0x11f3f),
204    (0x1612a, 0x1612c),
205    (0x16f51, 0x16f87),
206    (0x16ff0, 0x16ff1),
207    (0x1f130, 0x1f149),
208    (0x1f150, 0x1f169),
209    (0x1f170, 0x1f189),
210];
211
212/// Returns `true` if `c` is a non-ASCII character that a component of a ref
213/// name can hold.
214fn is_name_character(c: char) -> bool {
215    c.is_alphanumeric()
216        && !REFUSED_ALPHANUMERIC
217            .iter()
218            .any(|&(first, last)| (first..=last).contains(&u32::from(c)))
219}
220
221/// Returns `true` if `component` is one valid component of a ref name.
222///
223/// A component is not empty and does not start with `-` or `.`. Each of its
224/// characters is an ASCII letter, an ASCII digit, `-`, `.`, `_`, or a
225/// non-ASCII character for which `char::is_alphanumeric` is `true`. So `.`
226/// and `..` fail, and so does a component with `/`, `:`, a space, or NUL.
227///
228/// The tool also accepts a nonspacing combining mark (category Mn) and a
229/// connector punctuation character that is not ASCII (category Pc), and this
230/// function refuses them. The tool refuses the characters that
231/// `REFUSED_ALPHANUMERIC` lists, and this function refuses them too. So each
232/// name that this function accepts is a name that the tool accepts.
233pub fn is_ref_name_component(component: &str) -> bool {
234    !component.starts_with(['-', '.'])
235        && !component.is_empty()
236        && component.chars().all(|c| {
237            if c.is_ascii() {
238                c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')
239            } else {
240                is_name_character(c)
241            }
242        })
243}
244
245/// Returns `true` if `component` is one valid component of a part that is
246/// not a ref name.
247///
248/// A component is not empty, is not `.` or `..`, and holds no `/` and no NUL.
249/// A ref name uses the stricter [`is_ref_name_component`]. A collection id
250/// uses [`is_collection_id`].
251pub fn is_ref_component(component: &str) -> bool {
252    !(component.is_empty()
253        || component == "."
254        || component == ".."
255        || component.contains('/')
256        || component.contains('\0'))
257}
258
259/// Returns `true` if `name` is a valid ref name.
260///
261/// A ref name is a path below `refs/heads`. It is not empty, and each of its
262/// `/`-separated components passes [`is_ref_name_component`]. The rule keeps
263/// each name inside the `refs/` tree.
264pub fn is_ref_name(name: &str) -> bool {
265    !name.is_empty() && name.split('/').all(is_ref_name_component)
266}
267
268/// Returns `true` if `refspec` is a valid refspec.
269///
270/// A refspec is a ref name, or `REMOTE:NAME` split at the first `:`. In the
271/// second form, `REMOTE` must pass [`is_ref_name_component`] and `NAME` must
272/// pass [`is_ref_name`]. So `NAME` holds no `:`. Such a refspec names a path below
273/// `refs/remotes/REMOTE`, so it stays inside the `refs/` tree.
274pub fn is_refspec(refspec: &str) -> bool {
275    match refspec.split_once(':') {
276        Some((remote, name)) => is_ref_name_component(remote) && is_ref_name(name),
277        None => is_ref_name(refspec),
278    }
279}
280
281/// Returns `true` if `name` is 64 lowercase hex characters.
282///
283/// Such a name passes [`is_ref_name`]. A revision reads it as a commit
284/// checksum. A push refuses to write a commit to a ref of that name. A name
285/// with an uppercase hex character gives `false`.
286pub fn is_checksum_shaped(name: &str) -> bool {
287    Checksum::from_hex_lower(name).is_ok()
288}
289
290/// Returns `true` if `id` is a collection id.
291///
292/// A collection id has two or more elements, separated by `.`. Each element
293/// starts with an ASCII letter or `_` and continues with ASCII letters,
294/// digits, or `_`.
295///
296/// Recovered by observation: the `ostree` command writes `a.b`, `A.b`,
297/// `_a.b`, `a._b`, `a_b.c`, and `a.b.c.d`. It refuses `fresh`, `a..b`,
298/// `a.b.`, `1a.b`, `a.1b`, `a-b.c`, and `a.b-c` with
299/// `error: Invalid collection ID <id>`. Only the file system limits the
300/// length, because the id is one path component.
301pub fn is_collection_id(id: &str) -> bool {
302    id.split('.').count() >= 2
303        && id.split('.').all(|element| {
304            let mut chars = element.chars();
305            chars
306                .next()
307                .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
308                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
309        })
310}
311
312/// The longest collection id, in bytes, that [`Ref::validate`] accepts.
313///
314/// The id is one path component under `refs/mirrors/`, and a Linux file
315/// system takes a name of 255 bytes at most (`NAME_MAX`).
316pub const MAX_COLLECTION_ID_LEN: usize = 255;
317
318/// Returns `true` if `id` is a valid collection id for a ref: it passes
319/// [`is_collection_id`] and is at most [`MAX_COLLECTION_ID_LEN`] bytes.
320pub fn is_valid_collection_id(id: &str) -> bool {
321    id.len() <= MAX_COLLECTION_ID_LEN && is_collection_id(id)
322}
323
324/// Splits `@ID:REST` at the first `:` after the `@`.
325///
326/// Returns the id and the rest, or `None` if `text` does not start with `@`
327/// or has no `:` after it. The call does not check the id or the rest. Use
328/// [`is_valid_collection_id`] for the id.
329pub fn split_collection(text: &str) -> Option<(&str, &str)> {
330    text.strip_prefix('@')?.split_once(':')
331}
332
333/// One ref of a repository.
334///
335/// A ref has three cases, and each case has a text form:
336///
337/// - `NAME` is the local ref [`Ref::Local`], at `refs/heads/NAME`.
338/// - `REMOTE:NAME` is the remote ref [`Ref::Remote`], at
339///   `refs/remotes/REMOTE/NAME`.
340/// - `@ID:NAME` is the collection ref [`Ref::Collection`], at
341///   `refs/mirrors/ID/NAME`. A repository whose `[core] collection-id` is
342///   `ID` keeps the ref at `refs/heads/NAME`, so `@ID:NAME` and `NAME` name
343///   the same ref there. [`canonical`](Ref::canonical) gives the local form.
344///
345/// No valid ref name holds `@` or `:`, so the three forms do not overlap.
346///
347/// The constructors do not check the value. [`validate`](Ref::validate)
348/// checks it, and a ref store checks it before it reads or writes a file.
349/// [`FromStr`] reads the text and checks it. [`Display`](fmt::Display) gives
350/// the same text back.
351///
352/// # Examples
353///
354/// ```
355/// use ostrya_core::Ref;
356///
357/// let r: Ref = "@org.example.Os:os/x86_64".parse()?;
358/// assert_eq!(r, Ref::collection("org.example.Os", "os/x86_64"));
359/// assert_eq!(r.name(), "os/x86_64");
360/// assert_eq!(r.to_string(), "@org.example.Os:os/x86_64");
361/// assert_eq!("origin:main".parse::<Ref>()?, Ref::remote("origin", "main"));
362/// assert!("@org.example.Os:a:b".parse::<Ref>().is_err());
363/// # Ok::<(), ostrya_core::ParseRefError>(())
364/// ```
365#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
366pub enum Ref {
367    /// A local ref, at `refs/heads/<name>`.
368    Local {
369        /// The ref name, which can contain `/`.
370        name: String,
371    },
372    /// A remote ref, at `refs/remotes/<remote>/<name>`.
373    Remote {
374        /// The name of the remote.
375        remote: String,
376        /// The ref name, which can contain `/`.
377        name: String,
378    },
379    /// A collection ref, at `refs/mirrors/<id>/<name>`, or at
380    /// `refs/heads/<name>` when `id` is the `[core] collection-id` of the
381    /// repository.
382    Collection {
383        /// The collection id.
384        id: String,
385        /// The ref name, which can contain `/`.
386        name: String,
387    },
388}
389
390impl Ref {
391    /// Creates a local ref. The call does not check the name.
392    pub fn local(name: impl Into<String>) -> Ref {
393        Ref::Local { name: name.into() }
394    }
395
396    /// Creates a remote ref. The call does not check the values.
397    pub fn remote(remote: impl Into<String>, name: impl Into<String>) -> Ref {
398        Ref::Remote {
399            remote: remote.into(),
400            name: name.into(),
401        }
402    }
403
404    /// Creates a collection ref. The call does not check the values.
405    pub fn collection(id: impl Into<String>, name: impl Into<String>) -> Ref {
406        Ref::Collection {
407            id: id.into(),
408            name: name.into(),
409        }
410    }
411
412    /// Returns the ref name, without the remote or the collection id.
413    pub fn name(&self) -> &str {
414        match self {
415            Ref::Local { name } | Ref::Remote { name, .. } | Ref::Collection { name, .. } => name,
416        }
417    }
418
419    /// Returns the canonical form of the ref in a repository whose
420    /// `[core] collection-id` is `own`.
421    ///
422    /// A collection ref of `own` is the local ref of the same name, because
423    /// the repository keeps it at `refs/heads/<name>`. Each other ref is
424    /// returned unchanged, and so is each ref if `own` is `None`. The call
425    /// does not check the ref or `own`.
426    pub fn canonical(self, own: Option<&str>) -> Ref {
427        match self {
428            Ref::Collection { id, name } if Some(id.as_str()) == own => Ref::Local { name },
429            r => r,
430        }
431    }
432
433    /// Puts a local ref in the collection `id`.
434    ///
435    /// A local ref `NAME` becomes `@ID:NAME`. A collection ref of `id` stays,
436    /// and so does a remote ref. The call does not check the ref or `id`.
437    ///
438    /// # Errors
439    ///
440    /// Gives back the ref unchanged if it is a collection ref of another id.
441    pub fn in_collection(self, id: &str) -> Result<Ref, Ref> {
442        match self {
443            Ref::Local { name } => Ok(Ref::collection(id, name)),
444            Ref::Collection { id: ref other, .. } if other != id => Err(self),
445            r => Ok(r),
446        }
447    }
448
449    /// Returns the namespace of the ref: the local refs, the refs of one
450    /// remote, or the refs of one collection id.
451    ///
452    /// The call does not canonicalize the ref. A collection ref of the own
453    /// id of a repository is in the namespace of its local refs only after
454    /// [`canonical`](Ref::canonical).
455    pub fn namespace(&self) -> RefNamespace<'_> {
456        match self {
457            Ref::Local { .. } => RefNamespace::Local,
458            Ref::Remote { remote, .. } => RefNamespace::Remote(remote),
459            Ref::Collection { id, .. } => RefNamespace::Collection(id),
460        }
461    }
462
463    /// Returns `true` if the refs `self` and `other` are in one namespace:
464    /// both local, both of one remote, or both of one collection id.
465    pub fn same_namespace(&self, other: &Ref) -> bool {
466        self.namespace() == other.namespace()
467    }
468
469    /// Returns the first ref of `refs` that is in another collection than
470    /// an earlier ref of `refs`, with that earlier ref.
471    ///
472    /// The refs that are not collection refs are ignored. The call returns
473    /// `None` if the collection refs of `refs` hold one collection id.
474    pub fn collection_conflict<'a>(
475        refs: impl IntoIterator<Item = &'a Ref>,
476    ) -> Option<(&'a Ref, &'a Ref)> {
477        let mut first: Option<(&Ref, &str)> = None;
478        for r in refs {
479            let Ref::Collection { id, .. } = r else {
480                continue;
481            };
482            match first {
483                Some((other, other_id)) if other_id != id => return Some((other, r)),
484                Some(_) => {}
485                None => first = Some((r, id)),
486            }
487        }
488        None
489    }
490
491    /// Checks the ref against the ref-name rule.
492    ///
493    /// The ref name must pass [`is_ref_name`] in each case. The remote of
494    /// [`Ref::Remote`] must pass [`is_ref_name_component`]. The id of
495    /// [`Ref::Collection`] must pass [`is_collection_id`] and be at most
496    /// [`MAX_COLLECTION_ID_LEN`] bytes. So the path of a valid ref stays
497    /// inside the `refs/` tree.
498    ///
499    /// # Errors
500    ///
501    /// [`ParseRefError`] if a part fails its rule. The error holds the text
502    /// of the ref.
503    pub fn validate(&self) -> Result<(), ParseRefError> {
504        let valid = match self {
505            Ref::Local { name } => is_ref_name(name),
506            Ref::Remote { remote, name } => is_ref_name_component(remote) && is_ref_name(name),
507            Ref::Collection { id, name } => is_valid_collection_id(id) && is_ref_name(name),
508        };
509        if valid {
510            Ok(())
511        } else {
512            Err(ParseRefError {
513                text: self.to_string(),
514            })
515        }
516    }
517}
518
519impl FromStr for Ref {
520    type Err = ParseRefError;
521
522    /// Reads the text form of a ref and checks it with
523    /// [`validate`](Ref::validate).
524    ///
525    /// Text that starts with `@` is a collection ref, split at the first `:`
526    /// after the `@`. Other text with a `:` is a remote ref, split at the
527    /// first `:`. Text with no `:` is a local ref.
528    ///
529    /// # Errors
530    ///
531    /// [`ParseRefError`] if the text has no form or a part fails its rule.
532    /// The error holds the text as given.
533    fn from_str(text: &str) -> Result<Ref, ParseRefError> {
534        let parsed = if text.starts_with('@') {
535            split_collection(text).map(|(id, name)| Ref::collection(id, name))
536        } else {
537            Some(match text.split_once(':') {
538                Some((remote, name)) => Ref::remote(remote, name),
539                None => Ref::local(text),
540            })
541        };
542        match parsed {
543            Some(r) if r.validate().is_ok() => Ok(r),
544            _ => Err(ParseRefError {
545                text: text.to_owned(),
546            }),
547        }
548    }
549}
550
551impl fmt::Display for Ref {
552    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
553        match self {
554            Ref::Local { name } => f.write_str(name),
555            Ref::Remote { remote, name } => write!(f, "{remote}:{name}"),
556            Ref::Collection { id, name } => write!(f, "@{id}:{name}"),
557        }
558    }
559}
560
561/// The error of a ref that fails the rule of [`Ref::validate`], or text that
562/// [`Ref`] does not read.
563#[derive(Debug, Clone, PartialEq, Eq)]
564pub struct ParseRefError {
565    text: String,
566}
567
568impl ParseRefError {
569    /// Returns the text of the ref that failed.
570    pub fn as_str(&self) -> &str {
571        &self.text
572    }
573}
574
575/// The namespace of a [`Ref`], as [`Ref::namespace`] returns it.
576#[derive(Debug, Clone, Copy, PartialEq, Eq)]
577pub enum RefNamespace<'a> {
578    /// The local refs.
579    Local,
580    /// The refs of the remote with this name.
581    Remote(&'a str),
582    /// The refs of the collection with this id.
583    Collection(&'a str),
584}
585
586impl fmt::Display for ParseRefError {
587    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
588        write!(f, "invalid ref: {}", self.text)
589    }
590}
591
592impl std::error::Error for ParseRefError {}
593
594#[cfg(test)]
595mod tests {
596    use super::*;
597
598    #[test]
599    fn a_collection_ref_of_the_own_id_is_the_local_ref() {
600        let own = Some("org.example.Os");
601        assert_eq!(
602            Ref::collection("org.example.Os", "a/b").canonical(own),
603            Ref::local("a/b")
604        );
605        for r in [
606            Ref::collection("org.example.B", "a"),
607            Ref::local("a"),
608            Ref::remote("origin", "a"),
609        ] {
610            assert_eq!(r.clone().canonical(own), r);
611        }
612        let r = Ref::collection("org.example.Os", "a");
613        assert_eq!(r.clone().canonical(None), r);
614    }
615
616    #[test]
617    fn a_ref_in_a_collection_takes_its_id() {
618        let id = "org.example.Os";
619        assert_eq!(
620            Ref::local("a/b").in_collection(id),
621            Ok(Ref::collection(id, "a/b"))
622        );
623        for r in [Ref::collection(id, "a"), Ref::remote("origin", "a")] {
624            assert_eq!(r.clone().in_collection(id), Ok(r));
625        }
626        let other = Ref::collection("org.example.B", "a");
627        assert_eq!(other.clone().in_collection(id), Err(other));
628    }
629
630    #[test]
631    fn a_ref_gives_its_namespace() {
632        assert_eq!(Ref::local("a").namespace(), RefNamespace::Local);
633        assert_eq!(Ref::remote("o", "a").namespace(), RefNamespace::Remote("o"));
634        assert_eq!(
635            Ref::collection("org.example.A", "a").namespace(),
636            RefNamespace::Collection("org.example.A")
637        );
638    }
639
640    #[test]
641    fn same_namespace_compares_the_kind_and_the_owner() {
642        let local = Ref::local("a");
643        let remote = Ref::remote("o", "a");
644        let a = Ref::collection("org.example.A", "a");
645        let b = Ref::collection("org.example.B", "a");
646        assert!(local.same_namespace(&Ref::local("b")));
647        assert!(!remote.same_namespace(&local));
648        assert!(remote.same_namespace(&Ref::remote("o", "b")));
649        assert!(!remote.same_namespace(&Ref::remote("p", "a")));
650        assert!(a.same_namespace(&Ref::collection("org.example.A", "b")));
651        assert!(!a.same_namespace(&b));
652        assert!(!a.same_namespace(&local));
653        let own = Some("org.example.A");
654        assert!(a.clone().canonical(own).same_namespace(&local));
655        assert!(!b.canonical(own).same_namespace(&local));
656    }
657
658    #[test]
659    fn collection_conflict_returns_the_first_pair_of_two_ids() {
660        let a = Ref::collection("org.example.A", "a");
661        let a2 = Ref::collection("org.example.A", "b");
662        let b = Ref::collection("org.example.B", "a");
663        let c = Ref::collection("org.example.C", "a");
664        let local = Ref::local("x");
665        assert_eq!(Ref::collection_conflict([]), None);
666        assert_eq!(Ref::collection_conflict([&a]), None);
667        assert_eq!(Ref::collection_conflict([&local, &a, &local, &a2]), None);
668        assert_eq!(
669            Ref::collection_conflict([&a, &local, &b, &c]),
670            Some((&a, &b))
671        );
672        assert_eq!(Ref::collection_conflict([&a, &a2, &c, &b]), Some((&a, &c)));
673    }
674
675    #[test]
676    fn a_ref_name_holds_components_of_the_rule() {
677        for name in [
678            "main",
679            "a/b/c",
680            "x.y",
681            "a.",
682            "a..b",
683            "a.b",
684            "a/b.",
685            "_a",
686            "a_b",
687            "a/_b",
688            "a-b",
689            "1a",
690            "A",
691            "\u{e9}",
692            "a\u{e9}",
693            "\u{e9}a",
694            "a/\u{e9}b",
695            "\u{e9}/a",
696        ] {
697            assert!(is_ref_name(name), "{name}");
698        }
699        for name in [
700            "", "/", "/a", "a/", "a//b", ".", "..", "a/./b", "a/../b", "a\0b", "-dash", "a^",
701            "a:b", "..x", ".a", "a/.b", "a/-b", "a/..", "a*", "*", "a/*", "a/**", "!x", "x!",
702            "a/!b", "a?b", "a[b]", "a b", "a~b", "a^b", "a@b", "a+b", "a,b", "a%b", "a=b", "a#b",
703            "a\\b", "a'b", "a\"b", "a$b", "a&b", "a;b", "a|b", "a<b", "a(b", "a{b", "a`b", "-a",
704        ] {
705            assert!(!is_ref_name(name), "{name:?}");
706        }
707    }
708
709    #[test]
710    fn a_refspec_splits_at_the_first_colon() {
711        for spec in [
712            "main",
713            "a/b",
714            "origin:main",
715            "origin:a/b",
716            "o.:main",
717            "_o:main",
718            "o-:main",
719            "\u{e9}:main",
720        ] {
721            assert!(is_refspec(spec), "{spec}");
722        }
723        for spec in [
724            "",
725            ":",
726            ":main",
727            "origin:",
728            "a/b:main",
729            "..:main",
730            ".:main",
731            "o:..",
732            "o:a/../b",
733            "o\0:main",
734            "o:a:b",
735            "o:a b",
736            "o:-a",
737            "o r:main",
738            "o*:main",
739            "-o:main",
740            ".o:main",
741            "o~:main",
742            "o^:main",
743            "o@:main",
744            "o\u{a0}:main",
745        ] {
746            assert!(!is_refspec(spec), "{spec:?}");
747        }
748    }
749
750    #[test]
751    fn a_ref_name_component_follows_the_character_rule() {
752        for c in ["a", "a.b", "a.", "_a", "1a", "\u{e9}", "a\u{e9}"] {
753            assert!(is_ref_name_component(c), "{c:?}");
754        }
755        for c in ["", ".", "..", ".a", "-a", "a/b", "a:b", "a b", "a*", "a\0"] {
756            assert!(!is_ref_name_component(c), "{c:?}");
757        }
758    }
759
760    /// Each character is one that the `ostree` tool accepts or refuses in a
761    /// ref name, by a probe of the tool.
762    #[test]
763    fn a_non_ascii_character_is_valid_if_it_is_alphanumeric() {
764        for c in [
765            '\u{e9}', '\u{b5}', '\u{2d0}', '\u{4e2d}', '\u{b2}', '\u{2160}', '\u{660}', '\u{aa}',
766            '\u{ba}', '\u{bc}',
767        ] {
768            assert!(is_ref_name_component(&format!("a{c}b")), "{c:?}");
769            assert!(is_ref_name_component(&c.to_string()), "{c:?}");
770        }
771        for c in [
772            '\u{80}',
773            '\u{85}',
774            '\u{a0}',
775            '\u{ad}',
776            '\u{d7}',
777            '\u{2013}',
778            '\u{200b}',
779            '\u{20ac}',
780            '\u{feff}',
781            '\u{e000}',
782            '\u{1f600}',
783            '\u{fffd}',
784            '\u{2028}',
785            '\u{3000}',
786            '\u{ffff}',
787            '\u{10ffff}',
788        ] {
789            assert!(!is_ref_name_component(&format!("a{c}b")), "{c:?}");
790            assert!(!is_ref_name_component(&c.to_string()), "{c:?}");
791        }
792    }
793
794    /// The tool accepts these characters. The port refuses them, so it never
795    /// writes a name that the tool might skip.
796    #[test]
797    fn a_non_ascii_character_that_the_tool_accepts_but_is_not_alphanumeric_is_refused() {
798        for c in ['\u{301}', '\u{203f}', '\u{ff3f}'] {
799            assert!(!is_ref_name_component(&format!("a{c}b")), "{c:?}");
800        }
801    }
802
803    /// The tool refuses these alphanumeric characters: spacing combining
804    /// marks, circled letters, and enclosed letters.
805    #[test]
806    fn an_alphanumeric_character_that_the_tool_refuses_is_refused() {
807        for c in ['\u{903}', '\u{93e}', '\u{24b6}', '\u{1f130}', '\u{1f170}'] {
808            assert!(c.is_alphanumeric(), "{c:?}");
809            assert!(!is_ref_name_component(&format!("a{c}b")), "{c:?}");
810        }
811        for pair in REFUSED_ALPHANUMERIC.windows(2) {
812            assert!(pair[0].1 < pair[1].0, "{pair:?}");
813        }
814    }
815
816    #[test]
817    fn a_component_holds_no_slash_and_no_nul() {
818        assert!(is_ref_component("a.b"));
819        assert!(is_ref_component("a:b"));
820        for c in ["", ".", "..", "a/b", "a\0"] {
821            assert!(!is_ref_component(c), "{c:?}");
822        }
823    }
824
825    #[test]
826    fn a_checksum_shaped_name_is_64_lowercase_hex_characters() {
827        let hex = "0123456789abcdef".repeat(4);
828        assert!(is_checksum_shaped(&hex));
829        assert!(is_ref_name(&hex));
830        let mut one_off = hex.clone();
831        one_off.replace_range(10..11, "g");
832        for name in [
833            hex.to_uppercase(),
834            format!("A{}", &hex[1..]),
835            hex[..63].to_owned(),
836            format!("{hex}0"),
837            one_off,
838            format!("origin:{hex}"),
839            String::new(),
840        ] {
841            assert!(!is_checksum_shaped(&name), "{name}");
842        }
843    }
844
845    /// The ids that the `ostree` command writes are collection ids, and the
846    /// ids that it refuses are not.
847    #[test]
848    fn a_collection_id_has_two_or_more_elements_of_the_rule() {
849        for id in ["a.b", "A.b", "_a.b", "a._b", "a_b.c", "a.b.c.d"] {
850            assert!(is_collection_id(id), "{id}");
851        }
852        for id in [
853            "fresh", "a..b", "a.b.", "1a.b", "a.1b", "a-b.c", "a.b-c", "", ".", ".a.b", "a.b c",
854            "a.\u{e9}",
855        ] {
856            assert!(!is_collection_id(id), "{id:?}");
857        }
858    }
859
860    #[test]
861    fn split_collection_splits_at_the_first_colon_without_checking() {
862        assert_eq!(split_collection("@a.b:c:d"), Some(("a.b", "c:d")));
863        assert_eq!(split_collection("@a.b:"), Some(("a.b", "")));
864        assert_eq!(split_collection("@nodot:x"), Some(("nodot", "x")));
865        for text in ["a.b:c", "@a.b", "@", ""] {
866            assert_eq!(split_collection(text), None, "{text:?}");
867        }
868    }
869
870    #[test]
871    fn a_valid_collection_id_is_a_collection_id_of_at_most_the_limit() {
872        let longest = format!("a.{}", "b".repeat(MAX_COLLECTION_ID_LEN - 2));
873        assert!(is_valid_collection_id(&longest));
874        assert!(!is_valid_collection_id(&format!("{longest}b")));
875        assert!(is_valid_collection_id("org.example.Os"));
876        assert!(!is_valid_collection_id("nodot"));
877        assert!(!is_valid_collection_id(""));
878    }
879
880    #[test]
881    fn a_ref_reads_each_text_form_and_gives_the_text_back() {
882        for (text, expected) in [
883            ("main", Ref::local("main")),
884            ("a/b", Ref::local("a/b")),
885            ("origin:main", Ref::remote("origin", "main")),
886            (
887                "@org.example.Os:os/x86_64",
888                Ref::collection("org.example.Os", "os/x86_64"),
889            ),
890        ] {
891            let parsed: Ref = text.parse().unwrap();
892            assert_eq!(parsed, expected, "{text}");
893            assert_eq!(parsed.to_string(), text);
894            assert_eq!(parsed.to_string().parse::<Ref>().unwrap(), parsed);
895        }
896    }
897
898    #[test]
899    fn a_ref_refuses_text_that_has_no_form_or_fails_the_rule() {
900        let longest_id = format!("a.{}", "b".repeat(MAX_COLLECTION_ID_LEN - 2));
901        assert!(format!("@{longest_id}:x").parse::<Ref>().is_ok());
902        let too_long_id = format!("@{longest_id}b:x");
903        for text in [
904            "@",
905            "@org.example.Os",
906            "@org.example.Os:",
907            "@bad-id:x",
908            "@org.example.Os:a:b",
909            too_long_id.as_str(),
910            "",
911            "a:b:c",
912            ":a",
913        ] {
914            let err = text.parse::<Ref>().unwrap_err();
915            assert_eq!(err.as_str(), text);
916            assert_eq!(err.to_string(), format!("invalid ref: {text}"));
917        }
918    }
919
920    #[test]
921    fn a_ref_that_fails_the_rule_gives_its_text_in_the_error() {
922        for (r, text) in [
923            (Ref::local("a/../b"), "a/../b"),
924            (Ref::local("origin:main"), "origin:main"),
925            (Ref::remote("a/b", "main"), "a/b:main"),
926            (Ref::collection("a", "main"), "@a:main"),
927            (
928                Ref::collection("org.example.B", "-bad"),
929                "@org.example.B:-bad",
930            ),
931        ] {
932            assert_eq!(r.validate().unwrap_err().as_str(), text);
933        }
934        assert!(Ref::local("main").validate().is_ok());
935        assert_eq!(Ref::remote("origin", "a/b").name(), "a/b");
936    }
937}