use ostrya_core::{Ref, RefPattern};
use crate::error::{Error, Result};
use crate::refs::is_component;
#[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
}
pub(crate) fn specificity(&self, r: &Ref, own: Option<&str>) -> Option<Specificity<'_>> {
let (literal_remote, name) = match (&self.scope, r) {
(Scope::Local, Ref::Local { name }) => (false, name),
(Scope::Collection(want), Ref::Local { name }) if Some(want.as_str()) == own => {
(false, name)
}
(Scope::AnyRemote, Ref::Remote { name, .. }) => (false, name),
(Scope::Remote(want), Ref::Remote { remote, name }) if want == remote => (true, name),
(Scope::Collection(want), Ref::Collection { id, name }) if want == id => (true, name),
_ => return None,
};
if !self.name.matches(name) {
return None;
}
Some(Specificity {
literal_remote,
kinds: &self.kinds,
})
}
}
#[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}");
}
}
}