ostrya 0.14.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
//! The patterns that select local refs, remote refs, and collection refs.

use ostrya_core::{Ref, RefNamespace, RefPattern};

use crate::error::{Error, Result};
use crate::refs::is_component;

/// A pattern that names the refs of one rule of a one-way stream.
///
/// A pattern has an optional remote part or collection part, and a name
/// part. The name part is a [`RefPattern`]: a path of parts, split at `/`.
/// Each part is a literal, `*`, or `**`. `*` selects exactly one part of a
/// name. `**` selects one or more parts. A pattern has one of these forms:
///
/// - `NAME` -- the plain refs that the name pattern `NAME` matches.
/// - `REMOTE:NAME` -- the remote refs of the remote `REMOTE` that `NAME`
///   matches.
/// - `*:NAME` -- the remote refs of every remote that `NAME` matches.
/// - `@ID:NAME` -- the refs of the collection `ID` that `NAME` matches. In a
///   repository whose collection id is `ID`, these are the plain refs, so
///   `@ID:NAME` matches the same refs as `NAME`.
///
/// For example, `apps/*` selects `apps/web` and does not select `apps` or
/// `apps/web/db`. `apps/**` selects `apps/web` and `apps/web/db`, and does not
/// select `apps`. `central:**` selects every ref of the remote `central`.
/// `@org.example.Os:**` selects every ref of the collection `org.example.Os`.
///
/// `REMOTE` is one component of a ref path, under the wider rule of
/// `is_ref_component`, and holds no `*`. `ID` is one literal collection id:
/// it passes [`is_collection_id`](crate::is_collection_id) and is at most
/// [`MAX_COLLECTION_ID_LEN`](ostrya_core::MAX_COLLECTION_ID_LEN) bytes.
/// [`ReceivePattern::parse`] refuses each other form:
///
/// - A `!` at the start of the pattern or in the name part. A receive pattern
///   has no negative form, and a `!` entry of a [`ReceiveSelector`] is an
///   exclusion. A `!` in a remote part follows the component rule of the
///   remote part.
/// - A `*` in a remote part other than the whole part `*`.
/// - An `@` with no `:`, or a collection part that is not a collection id.
/// - A `*` in a name part other than the whole part `*` or `**`.
/// - An empty pattern, an empty part, or a `:` in the name part.
/// - A control character.
/// - A literal part that fails the ref-name rule, for example one with a space
///   or one that starts with `-`.
///
#[cfg_attr(
    feature = "receive",
    doc = "If more than one pattern matches a ref, \
           [`StreamPolicy::rule_for`](crate::receive::StreamPolicy::rule_for) \
           states which rule applies."
)]
#[cfg_attr(
    not(feature = "receive"),
    doc = "If more than one pattern matches a ref, `StreamPolicy::rule_for` \
           states which rule applies."
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceivePattern {
    /// The pattern as written.
    text: String,
    /// The refs that the pattern can match, from the part before the name
    /// part.
    scope: Scope,
    /// The name part.
    name: RefPattern,
    /// The kind of each part of the name part, in order.
    kinds: Vec<Kind>,
}

/// The part of a pattern before its name part.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Scope {
    /// No part: the plain refs.
    Local,
    /// `*:`, every remote.
    AnyRemote,
    /// `REMOTE:`, one remote.
    Remote(String),
    /// `@ID:`, one collection.
    Collection(String),
}

/// The kind of one part of a name part. A larger value is more specific.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
    /// `**`.
    Many,
    /// `*`.
    One,
    /// A literal.
    Literal,
}

/// The strength of the match of a pattern on a ref. A larger value wins.
///
/// The fields compare in order. A literal remote part wins over `*:`. Then the
/// kinds of the parts of the name part compare from the left: a literal wins
/// over `*`, and `*` wins over `**`. If one list of kinds is the start of the
/// other, the longer one wins. Two patterns that match one collection ref
/// both have the literal collection part.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Specificity<'a> {
    literal_remote: bool,
    kinds: &'a [Kind],
}

impl ReceivePattern {
    /// Parses a ref pattern of a rule of a one-way stream.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] if `pattern` is empty, holds a control
    /// character, or has a form outside the syntax of [`ReceivePattern`].
    pub fn parse(pattern: &str) -> Result<ReceivePattern> {
        let malformed = |why: &str| {
            Error::InvalidFormat(format!("malformed receive pattern '{pattern}': {why}"))
        };
        if pattern.is_empty() {
            return Err(malformed("the pattern is empty"));
        }
        if pattern.chars().any(char::is_control) {
            return Err(malformed("the pattern holds a control character"));
        }
        if pattern.starts_with('!') {
            return Err(malformed("a receive pattern has no '!'"));
        }
        let (scope, name) = if pattern.starts_with('@') {
            let Some((id, name)) = ostrya_core::split_collection(pattern) else {
                return Err(malformed("a collection part '@ID' has no ':'"));
            };
            if !ostrya_core::is_valid_collection_id(id) {
                return Err(malformed("the collection part is not a collection id"));
            }
            (Scope::Collection(id.to_owned()), name)
        } else {
            match pattern.split_once(':') {
                None => (Scope::Local, pattern),
                Some(("*", name)) => (Scope::AnyRemote, name),
                Some((remote, _)) if remote.contains('*') => {
                    return Err(malformed("a remote part is one remote or '*'"));
                }
                Some((remote, _)) if !is_component(remote) => {
                    return Err(malformed("the remote part is not a remote name"));
                }
                Some((remote, name)) => (Scope::Remote(remote.to_owned()), name),
            }
        };
        let name_text = name;
        let name = RefPattern::parse(name_text).map_err(|err| match err {
            ostrya_core::Error::InvalidRefPattern(reason) => {
                let quoted = format!("{name_text:?}: ");
                malformed(reason.strip_prefix(&quoted).unwrap_or(&reason))
            }
            other => malformed(&other.to_string()),
        })?;
        let kinds = name
            .as_str()
            .split('/')
            .map(|part| match part {
                "**" => Kind::Many,
                "*" => Kind::One,
                _ => Kind::Literal,
            })
            .collect();
        Ok(ReceivePattern {
            text: pattern.to_owned(),
            scope,
            name,
            kinds,
        })
    }

    /// Returns the pattern as written.
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Returns the strength of the match of this pattern on the ref `r`, in
    /// a repository whose collection id is `own`.
    ///
    /// `r` is in its canonical form: `@OWN:NAME` is the local ref `NAME`.
    /// The result is `None` if the pattern does not match. A pattern with a
    /// remote part matches only remote refs, and a pattern with a collection
    /// part matches only the refs of its collection. A pattern with neither
    /// part, or with the collection part of `own`, matches only plain refs,
    /// with the strength of a pattern with neither part.
    #[cfg(any(test, feature = "receive"))]
    pub(crate) fn specificity(&self, r: &Ref, own: Option<&str>) -> Option<Specificity<'_>> {
        self.specificity_in(r.namespace(), r.name(), own)
    }

    /// Returns the strength of the match of this pattern on the ref `name` in
    /// the namespace `namespace`, in a repository whose collection id is
    /// `own`. The namespace is in its canonical form.
    fn specificity_in(
        &self,
        namespace: RefNamespace<'_>,
        name: &str,
        own: Option<&str>,
    ) -> Option<Specificity<'_>> {
        let literal_remote = match (&self.scope, namespace) {
            (Scope::Local, RefNamespace::Local) => false,
            (Scope::Collection(want), RefNamespace::Local) if Some(want.as_str()) == own => false,
            (Scope::AnyRemote, RefNamespace::Remote(_)) => false,
            (Scope::Remote(want), RefNamespace::Remote(remote)) if want == remote => true,
            (Scope::Collection(want), RefNamespace::Collection(id)) if want == id => true,
            _ => return None,
        };
        if !self.name.matches(name) {
            return None;
        }
        Some(Specificity {
            literal_remote,
            kinds: &self.kinds,
        })
    }
}

#[cfg_attr(
    feature = "receive",
    doc = "A list of [`ReceivePattern`] entries that selects refs of each kind."
)]
#[cfg_attr(
    not(feature = "receive"),
    doc = "A list of `ReceivePattern` entries that selects refs of each kind."
)]
///
/// An entry is a pattern with an optional first `!`. An entry with `!` is a
/// negative pattern, and each other entry is a positive pattern.
///
/// A ref is selected when the list has no positive pattern or a positive
/// pattern matches it, and no negative pattern matches it. The order of the
/// entries has no effect, and an empty list selects each ref.
///
/// # Examples
///
/// This selector selects each plain ref under `apps/`, except the refs under
/// `apps/web/`. It selects no remote ref.
///
/// ```
/// use ostrya::{ReceiveSelector, Ref};
///
/// let selector = ReceiveSelector::parse(["apps/**", "!apps/web/**"])?;
/// assert!(selector.matches(&Ref::local("apps/db"), None));
/// assert!(!selector.matches(&Ref::local("apps/web/main"), None));
/// assert!(!selector.matches(&Ref::remote("origin", "apps/db"), None));
/// # Ok::<(), ostrya::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceiveSelector {
    /// The patterns of the entries with no `!`, in their order.
    positive: Vec<ReceivePattern>,
    /// The patterns of the entries with `!`, in their order, with no `!`.
    negative: Vec<ReceivePattern>,
}

impl ReceiveSelector {
    #[cfg_attr(
        feature = "receive",
        doc = "Parses a list of entries. An entry is a [`ReceivePattern`] with an \
               optional first `!`. The selector keeps the entries in their order, \
               with repeats."
    )]
    #[cfg_attr(
        not(feature = "receive"),
        doc = "Parses a list of entries. An entry is a `ReceivePattern` with an \
               optional first `!`. The selector keeps the entries in their order, \
               with repeats."
    )]
    ///
    /// The call does not split an entry at `;`.
    ///
    /// # Errors
    ///
    #[cfg_attr(
        feature = "receive",
        doc = "[`Error::InvalidFormat`] if an entry, with no first `!`, is not a valid \
               [`ReceivePattern`]. The text names the entry with no first `!`. An \
               entry that starts with `!!` is not valid."
    )]
    #[cfg_attr(
        not(feature = "receive"),
        doc = "[`Error::InvalidFormat`] if an entry, with no first `!`, is not a valid \
               `ReceivePattern`. The text names the entry with no first `!`. An \
               entry that starts with `!!` is not valid."
    )]
    pub fn parse<'a>(entries: impl IntoIterator<Item = &'a str>) -> Result<ReceiveSelector> {
        let mut positive = Vec::new();
        let mut negative = Vec::new();
        for entry in entries {
            match entry.strip_prefix('!') {
                Some(rest) => negative.push(ReceivePattern::parse(rest)?),
                None => positive.push(ReceivePattern::parse(entry)?),
            }
        }
        Ok(ReceiveSelector { positive, negative })
    }

    /// Returns `true` if the selector selects the ref `r`, in a repository
    /// whose collection id is `own`.
    ///
    /// The patterns match the canonical form of `r`, from [`Ref::canonical`].
    /// Thus the pattern `@OWN:NAME` matches the local ref `NAME`, and the
    /// pattern `NAME` matches the collection ref `@OWN:NAME`. If `own` is
    /// `None`, a pattern with a collection part matches only collection refs.
    pub fn matches(&self, r: &Ref, own: Option<&str>) -> bool {
        let namespace = match r.namespace() {
            RefNamespace::Collection(id) if Some(id) == own => RefNamespace::Local,
            namespace => namespace,
        };
        let hit = |p: &ReceivePattern| p.specificity_in(namespace, r.name(), own).is_some();
        (self.positive.is_empty() || self.positive.iter().any(hit))
            && !self.negative.iter().any(hit)
    }

    /// Returns `true` if the list holds an entry with no `!`.
    pub(crate) fn has_positive(&self) -> bool {
        !self.positive.is_empty()
    }
}

/// The pattern types move freely across tasks and threads.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ReceivePattern>();
    assert_send_sync::<ReceiveSelector>();
};

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

    fn matches(pattern: &str, remote: Option<&str>, name: &str) -> bool {
        let r = match remote {
            Some(remote) => Ref::remote(remote, name),
            None => Ref::local(name),
        };
        matches_ref(pattern, &r)
    }

    fn matches_ref(pattern: &str, r: &Ref) -> bool {
        ReceivePattern::parse(pattern)
            .unwrap()
            .specificity(r, None)
            .is_some()
    }

    /// Each accepted form parses and keeps its text.
    #[test]
    fn the_accepted_forms_parse() {
        for pattern in [
            "main",
            "apps/x",
            "apps/*",
            "apps/**",
            "a/b/**",
            "a/*/b",
            "*/x",
            "a/**/b",
            "*",
            "**",
            "origin:main",
            "origin:apps/**",
            "origin:*",
            "origin:**",
            "*:main",
            "*:apps/*",
            "*:*",
            "*:**",
            "r!:a",
            "@org.example.Os:main",
            "@org.example.Os:**",
            "@org.example.Os:apps/*",
        ] {
            let parsed = ReceivePattern::parse(pattern).unwrap();
            assert_eq!(parsed.as_str(), pattern);
        }
    }

    #[test]
    fn a_collection_part_must_be_a_collection_id_within_the_limit() {
        let longest = format!("a.{}", "b".repeat(ostrya_core::MAX_COLLECTION_ID_LEN - 2));
        assert!(ReceivePattern::parse(&format!("@{longest}:**")).is_ok());
        for id in [format!("{longest}b"), "nodot".to_owned()] {
            let err = ReceivePattern::parse(&format!("@{id}:**")).unwrap_err();
            assert!(
                err.to_string()
                    .ends_with("the collection part is not a collection id"),
                "{err}"
            );
        }
    }

    /// The parser refuses each form outside the syntax as malformed.
    #[test]
    fn the_other_forms_are_refused() {
        for pattern in [
            "",
            "!a",
            "!*:x",
            "r:!a",
            "a*",
            "*a",
            "***",
            "*/",
            "a//**",
            "a/**x",
            "/*",
            "a//*",
            "a/",
            "/a",
            ":x",
            "r:",
            "r/x:y",
            "r*:x",
            "**:x",
            ".",
            "..",
            "a/./b",
            "a/../*",
            "r:.",
            "..:x",
            "a\tb",
            "a\nb",
            "r:a\u{7f}",
            "a/*b",
            "*:a*",
            "r:a:b",
            "a b/*",
            "a b",
            "-a",
            "a/.b/*",
            "@org.example.Os",
            "@:a",
            "@*:a",
            "@org.*:a",
            "@nodot:a",
            "@org.example.Os:",
            "@org.example.Os:a:b",
            "@org.example.Os:!a",
            "!@org.example.Os:a",
        ] {
            let err = ReceivePattern::parse(pattern).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m.contains("malformed receive pattern")),
                "{pattern:?}: {err}"
            );
        }
    }

    /// `*` selects one part and `**` selects one or more parts.
    #[test]
    fn the_wildcards_select_parts() {
        assert!(matches("a/*", None, "a/b"));
        assert!(!matches("a/*", None, "a/b/c"));
        assert!(!matches("a/*", None, "a"));
        assert!(matches("a/**", None, "a/b"));
        assert!(matches("a/**", None, "a/b/c"));
        assert!(!matches("a/**", None, "a"));
        assert!(!matches("a/**", None, "ab/c"));
        assert!(!matches("a/**", None, "b/a/c"));
        assert!(matches("a/*/c", None, "a/b/c"));
        assert!(!matches("a/*/c", None, "a/b/d/c"));
        assert!(matches("main", None, "main"));
        assert!(!matches("main", None, "main2"));
        assert!(matches("**", None, "a/b"));
        assert!(matches("*", None, "a"));
        assert!(!matches("*", None, "a/b"));
    }

    /// A plain pattern never matches a remote ref, and a remote pattern never
    /// matches a plain ref.
    #[test]
    fn the_remote_part_separates_the_two_kinds() {
        assert!(!matches("main", Some("origin"), "main"));
        assert!(!matches("a/**", Some("origin"), "a/b"));
        assert!(!matches("origin:main", None, "main"));
        assert!(!matches("*:**", None, "main"));
        assert!(matches("*:**", Some("origin"), "main"));
        assert!(matches("origin:**", Some("origin"), "a/b"));
        assert!(!matches("origin:**", Some("other"), "a/b"));
        assert!(!matches("origin:**", Some("origin2"), "a"));
        assert!(!matches("origin:*", Some("origin"), "a/b"));
    }

    /// A collection pattern matches only the refs of its collection, and no
    /// other pattern matches a collection ref.
    #[test]
    fn a_collection_pattern_matches_its_collection_alone() {
        let os = |name: &str| Ref::collection("org.example.Os", name);
        assert!(matches_ref("@org.example.Os:**", &os("a/b")));
        assert!(matches_ref("@org.example.Os:a", &os("a")));
        assert!(!matches_ref("@org.example.Os:a", &os("b")));
        assert!(!matches_ref(
            "@org.example.Os:**",
            &Ref::collection("org.example.Other", "a")
        ));
        assert!(!matches_ref("@org.example.Os:**", &Ref::local("a")));
        assert!(!matches_ref(
            "@org.example.Os:**",
            &Ref::remote("origin", "a")
        ));
        for pattern in ["**", "*:**", "origin:**"] {
            assert!(!matches_ref(pattern, &os("a")), "{pattern}");
        }
    }

    fn selects(entries: &[&str], r: &Ref, own: Option<&str>) -> bool {
        ReceiveSelector::parse(entries.iter().copied())
            .unwrap()
            .matches(r, own)
    }

    /// Each form of a pattern parses as an entry of a list, with and without
    /// a first `!`.
    #[test]
    fn a_selector_parses_each_form() {
        let forms = [
            "main",
            "apps/*",
            "apps/**",
            "origin:main",
            "origin:apps/*",
            "*:main",
            "*:**",
            "@org.example.Os:main",
            "@org.example.Os:**",
        ];
        let negative: Vec<String> = forms.iter().map(|f| format!("!{f}")).collect();
        let selector = ReceiveSelector::parse(forms.iter().copied()).unwrap();
        assert_eq!(selector.positive.len(), forms.len());
        assert!(selector.negative.is_empty());
        let selector = ReceiveSelector::parse(negative.iter().map(String::as_str)).unwrap();
        assert!(selector.positive.is_empty());
        let texts: Vec<&str> = selector.negative.iter().map(|p| p.as_str()).collect();
        assert_eq!(texts, forms);
    }

    /// A list with a bad entry is refused with the text of the pattern parse.
    #[test]
    fn a_selector_refuses_a_bad_entry() {
        for entries in [&["main", "a b"][..], &["!!a"], &["!"], &[""], &["r*:x"]] {
            let err = ReceiveSelector::parse(entries.iter().copied()).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m) if m.contains("malformed receive pattern")),
                "{entries:?}: {err}"
            );
        }
    }

    /// A negative pattern wins over a positive pattern, and a list of
    /// negative patterns alone selects each other ref.
    #[test]
    fn a_selector_applies_the_negative_patterns() {
        let main = Ref::local("main");
        let web = Ref::local("apps/web");
        let remote = Ref::remote("origin", "apps/web");
        assert!(selects(&["apps/**", "main"], &web, None));
        assert!(!selects(&["apps/**", "!apps/web"], &web, None));
        assert!(!selects(&["!apps/web", "apps/**"], &web, None));
        assert!(!selects(&["apps/**"], &main, None));
        assert!(selects(&["!apps/**"], &main, None));
        assert!(!selects(&["!apps/**"], &web, None));
        assert!(selects(&["!apps/**"], &remote, None));
        assert!(!selects(&["!*:**"], &remote, None));
        for r in [&main, &web, &remote] {
            assert!(selects(&[], r, None));
        }
    }

    /// The own collection id joins a collection pattern and a plain pattern.
    #[test]
    fn a_selector_matches_the_canonical_ref() {
        let own = Some("org.example.Os");
        let local = Ref::local("x");
        let in_own = Ref::collection("org.example.Os", "x");
        assert!(selects(&["@org.example.Os:x"], &local, own));
        assert!(selects(&["@org.example.Os:x"], &in_own, own));
        assert!(selects(&["x"], &in_own, own));
        assert!(!selects(&["!x"], &in_own, own));
        assert!(!selects(&["!@org.example.Os:x"], &local, own));
        assert!(!selects(&["@org.example.Other:x"], &local, own));
        assert!(!selects(&["@org.example.Os:x"], &local, None));
        assert!(!selects(&["x"], &in_own, None));
        assert!(selects(&["@org.example.Os:x"], &in_own, None));
    }

    /// Each pattern scope, with and without `!`, against each kind of ref,
    /// with and without an own collection id.
    #[test]
    fn a_selector_matches_each_scope_against_each_kind_of_ref() {
        const OWN: &str = "org.example.Os";
        let patterns = [
            "x",
            "origin:x",
            "*:x",
            "@org.example.Os:x",
            "@org.example.Other:x",
        ];
        let refs = [
            Ref::local("x"),
            Ref::remote("origin", "x"),
            Ref::collection(OWN, "x"),
            Ref::collection("org.example.Other", "x"),
            Ref::collection(OWN, "y"),
        ];
        // For each ref, the positive patterns that select it, by own id.
        let with_own: [&[&str]; 5] = [
            &["x", "@org.example.Os:x"],
            &["origin:x", "*:x"],
            &["x", "@org.example.Os:x"],
            &["@org.example.Other:x"],
            &[],
        ];
        let without_own: [&[&str]; 5] = [
            &["x"],
            &["origin:x", "*:x"],
            &["@org.example.Os:x"],
            &["@org.example.Other:x"],
            &[],
        ];
        for (own, expected) in [(Some(OWN), with_own), (None, without_own)] {
            for (r, hits) in refs.iter().zip(expected) {
                for pattern in patterns {
                    let hit = hits.contains(&pattern);
                    let negated = format!("!{pattern}");
                    assert_eq!(selects(&[pattern], r, own), hit, "{pattern} {r} {own:?}");
                    assert_eq!(selects(&[&negated], r, own), !hit, "{negated} {r} {own:?}");
                }
            }
        }
    }

    /// A remote pattern matches only a remote ref, and never the plain ref or
    /// the own collection ref of the same name.
    #[test]
    fn a_selector_remote_pattern_matches_only_remote_refs() {
        let own = Some("org.example.Os");
        let remote = Ref::remote("origin", "x");
        let local = Ref::local("x");
        let in_own = Ref::collection("org.example.Os", "x");
        for pattern in ["origin:x", "*:x"] {
            assert!(selects(&[pattern], &remote, own), "{pattern}");
            assert!(!selects(&[pattern], &local, own), "{pattern}");
            assert!(!selects(&[pattern], &in_own, own), "{pattern}");
        }
    }
}