use ostrya_core::{Ref, RefNamespace, RefPattern};
use crate::error::{Error, Result};
use crate::refs::is_component;
#[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 {
text: String,
scope: Scope,
name: RefPattern,
kinds: Vec<Kind>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Scope {
Local,
AnyRemote,
Remote(String),
Collection(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Kind {
Many,
One,
Literal,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct Specificity<'a> {
literal_remote: bool,
kinds: &'a [Kind],
}
impl 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("ed).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,
})
}
pub fn as_str(&self) -> &str {
&self.text
}
#[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)
}
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."
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReceiveSelector {
positive: Vec<ReceivePattern>,
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."
)]
#[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 })
}
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)
}
pub(crate) fn has_positive(&self) -> bool {
!self.positive.is_empty()
}
}
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()
}
#[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}"
);
}
}
#[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}"
);
}
}
#[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"));
}
#[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"));
}
#[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)
}
#[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);
}
#[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}"
);
}
}
#[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));
}
}
#[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));
}
#[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"),
];
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:?}");
}
}
}
}
#[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}");
}
}
}