// Copyright (c) Kim Altintop // Copyright (c) The Radicle Team //! Git refspec patterns. use super::*; /// Iterator over slash-separated refspec pattern components. pub type Iter<'a> = std::str::Split<'a, char>; /// The `*` refspec pattern. pub const STAR: &PatternStr = PatternStr::from_str("*"); /// Validation options for refspec patterns. const CHECK_OPTS: check::Options = check::Options { allow_onelevel: true, allow_pattern: true, }; /// A borrowed valid Git refspec pattern. #[repr(transparent)] #[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] pub struct PatternStr(str); impl PatternStr { /// Validates `s` and returns it as a borrowed pattern. #[inline] pub fn try_from_str(s: &str) -> Result<&Self, check::Error> { TryFrom::try_from(s) } /// Returns the pattern as a string slice. #[inline] pub fn as_str(&self) -> &str { self } /// Joins another refname suffix to this pattern. pub fn join(&self, other: R) -> PatternString where R: AsRef, { let mut buf = self.to_owned(); buf.push(other); buf } /// Returns this pattern as qualified if it starts with `refs/`. #[inline] pub fn qualified(&self) -> Option> { QualifiedPattern::from_patternstr(self) } /// Returns this pattern as namespaced if it has a namespace prefix. #[inline] pub fn to_namespaced(&self) -> Option> { self.into() } /// Returns slash-separated string components. #[inline] pub fn iter(&self) -> Iter<'_> { self.0.split('/') } /// Returns slash-separated pattern components. #[inline] pub fn components(&self) -> Components<'_> { Components::from(self) } /// Converts a known-valid string slice to a pattern. pub(crate) const fn from_str(s: &str) -> &PatternStr { // SAFETY: `PatternStr` is a transparent wrapper around `str`. unsafe { &*(s as *const str as *const PatternStr) } } } impl Deref for PatternStr { type Target = str; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef for PatternStr { #[inline] fn as_ref(&self) -> &str { self } } impl AsRef for PatternStr { #[inline] fn as_ref(&self) -> &Self { self } } impl<'a> TryFrom<&'a str> for &'a PatternStr { type Error = check::Error; #[inline] fn try_from(s: &'a str) -> Result { check::ref_format(CHECK_OPTS, s).map(|()| PatternStr::from_str(s)) } } impl<'a> From<&'a RefStr> for &'a PatternStr { #[inline] fn from(refname: &'a RefStr) -> Self { PatternStr::from_str(refname.as_str()) } } impl<'a> From<&'a PatternStr> for Cow<'a, PatternStr> { #[inline] fn from(pattern: &'a PatternStr) -> Cow<'a, PatternStr> { Cow::Borrowed(pattern) } } impl Display for PatternStr { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self) } } /// An owned valid Git refspec pattern. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] pub struct PatternString(pub(crate) String); impl PatternString { /// Returns the pattern as a string slice. #[inline] pub fn as_str(&self) -> &str { self.as_ref() } /// Returns this owned pattern as a borrowed pattern. #[inline] pub fn as_pattern_str(&self) -> &PatternStr { self.as_ref() } /// Builds a pattern from slash-separated pattern components. #[inline] pub fn from_components<'a, T>(iter: T) -> Result where T: IntoIterator>, { iter.into_iter().collect() } /// Joins another refname suffix to this pattern. #[inline] pub fn and(mut self, other: R) -> Self where R: AsRef, { self.push(other); self } /// Pushes another refname suffix onto this pattern. #[inline] pub fn push(&mut self, other: R) where R: AsRef, { self.0.push('/'); self.0.push_str(other.as_ref().as_str()); } /// Removes the final slash-separated component. pub fn pop(&mut self) -> bool { match self.0.rfind('/') { Some(index) => { self.0.truncate(index); true } None => false, } } } impl Deref for PatternString { type Target = PatternStr; #[inline] fn deref(&self) -> &Self::Target { self.borrow() } } impl AsRef for PatternString { #[inline] fn as_ref(&self) -> &PatternStr { self } } impl AsRef for PatternString { #[inline] fn as_ref(&self) -> &str { self.0.as_str() } } impl Borrow for PatternString { #[inline] fn borrow(&self) -> &PatternStr { PatternStr::from_str(self.0.as_str()) } } impl ToOwned for PatternStr { type Owned = PatternString; #[inline] fn to_owned(&self) -> Self::Owned { PatternString(self.0.to_owned()) } } impl From for PatternString { #[inline] fn from(refname: RefString) -> Self { Self(refname.into()) } } impl<'a> From<&'a PatternString> for Cow<'a, PatternStr> { #[inline] fn from(pattern: &'a PatternString) -> Cow<'a, PatternStr> { Cow::Borrowed(pattern.as_ref()) } } impl From for String { #[inline] fn from(pattern: PatternString) -> Self { pattern.0 } } impl TryFrom<&str> for PatternString { type Error = check::Error; #[inline] fn try_from(s: &str) -> Result { PatternStr::try_from_str(s).map(ToOwned::to_owned) } } impl TryFrom for PatternString { type Error = check::Error; #[inline] fn try_from(s: String) -> Result { check::ref_format(CHECK_OPTS, s.as_str()).map(|()| PatternString(s)) } } /// Error returned when a refspec pattern has multiple glob components. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct DuplicateGlob; impl Display for DuplicateGlob { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("more than one '*' encountered") } } impl std::error::Error for DuplicateGlob {} impl<'a> FromIterator> for Result { fn from_iter(iter: T) -> Self where T: IntoIterator>, { let mut buf = String::new(); let mut seen_glob = false; for component in iter { if matches!(component, Component::Glob(_)) { if seen_glob { return Err(DuplicateGlob); } seen_glob = true; } if !buf.is_empty() { buf.push('/'); } buf.push_str(component.as_str()); } assert!(!buf.is_empty(), "PatternString::from_iter: empty iterator"); Ok(PatternString(buf)) } } impl Display for PatternString { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0) } } /// A component of a refspec pattern. pub enum Component<'a> { /// A `*` glob or a component containing `*`. Glob(Option<&'a PatternStr>), /// A normal refname component. Normal(&'a RefStr), } impl Component<'_> { /// Returns this component as a string slice. #[inline] pub fn as_str(&self) -> &str { self.as_ref() } } impl AsRef for Component<'_> { #[inline] fn as_ref(&self) -> &str { match self { Self::Glob(None) => "*", Self::Glob(Some(pattern)) => pattern.as_str(), Self::Normal(refname) => refname.as_str(), } } } impl Display for Component<'_> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.as_str()) } } impl From for Component<'static> { #[inline] fn from(_: T) -> Self { Self::Normal(T::NAME) } } /// Iterator over refspec pattern components. #[must_use = "iterators are lazy and do nothing unless consumed"] #[derive(Clone)] pub struct Components<'a> { /// Inner string splitter. inner: Iter<'a>, } impl<'a> Iterator for Components<'a> { type Item = Component<'a>; #[inline] fn next(&mut self) -> Option { self.inner.next().map(pattern_component) } } impl<'a> DoubleEndedIterator for Components<'a> { #[inline] fn next_back(&mut self) -> Option { self.inner.next_back().map(pattern_component) } } impl<'a> From<&'a PatternStr> for Components<'a> { #[inline] fn from(pattern: &'a PatternStr) -> Self { Self { inner: pattern.as_str().split('/'), } } } /// Converts a string component to a pattern component. fn pattern_component(component: &str) -> Component<'_> { match component { "*" => Component::Glob(None), value if value.contains('*') => Component::Glob(Some(PatternStr::from_str(value))), value => Component::Normal(RefStr::from_str(value)), } } /// Common refspec pattern components. pub mod component { use super::{Component, PatternStr}; use crate::git::refs::name; /// The `*` component. pub const STAR: Component<'static> = Component::Glob(None); /// The `heads` component. pub const HEADS: Component<'static> = Component::Normal(name::HEADS); /// The `main` component. pub const MAIN: Component<'static> = Component::Normal(name::MAIN); /// The `master` component. pub const MASTER: Component<'static> = Component::Normal(name::MASTER); /// The `namespaces` component. pub const NAMESPACES: Component<'static> = Component::Normal(name::NAMESPACES); /// The `notes` component. pub const NOTES: Component<'static> = Component::Normal(name::NOTES); /// The `origin` component. pub const ORIGIN: Component<'static> = Component::Normal(name::ORIGIN); /// The `refs` component. pub const REFS: Component<'static> = Component::Normal(name::REFS); /// The `remotes` component. pub const REMOTES: Component<'static> = Component::Normal(name::REMOTES); /// The `tags` component. pub const TAGS: Component<'static> = Component::Normal(name::TAGS); /// A typed reference to the `*` pattern. pub const STAR_PATTERN: &PatternStr = super::STAR; } /// A fully qualified refspec pattern. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] pub struct QualifiedPattern<'a>(pub(crate) Cow<'a, PatternStr>); impl<'a> QualifiedPattern<'a> { /// Returns `pattern` as qualified if it starts with `refs/` and has a category and name. pub fn from_patternstr(pattern: impl Into>) -> Option { let pattern = pattern.into(); let mut iter = pattern.iter(); match (iter.next(), iter.next(), iter.next()) { (Some("refs"), Some(_), Some(_)) => Some(Self(pattern)), _ => None, } } /// Returns the qualified pattern as a string. #[inline] pub fn as_str(&self) -> &str { self.as_ref() } /// Joins another refname suffix. #[inline] pub fn join<'b, R>(&self, other: R) -> QualifiedPattern<'b> where R: AsRef, { QualifiedPattern(Cow::Owned(self.0.join(other))) } /// Returns this pattern as namespaced if it has a namespace prefix. #[inline] pub fn to_namespaced(&self) -> Option> { self.0.as_ref().into() } /// Adds `refs/namespaces//` before this pattern. pub fn with_namespace<'b>( &self, namespace: crate::git::refs::Component<'b>, ) -> Result, DuplicateGlob> { let prefix = [ Component::Normal(name::REFS), Component::Normal(name::NAMESPACES), Component::Normal(namespace.as_ref()), ]; PatternString::from_components(IntoIterator::into_iter(prefix).chain(self.components())) .map(|pattern| NamespacedPattern(Cow::Owned(pattern))) } /// Returns the first three string components and the remaining iterator. #[allow(clippy::panic)] pub fn non_empty_iter(&self) -> (&str, &str, &str, Iter<'_>) { let mut iter = self.iter(); let (Some(first), Some(second), Some(third)) = (iter.next(), iter.next(), iter.next()) else { panic!("QualifiedPattern::non_empty_iter: missing component"); }; (first, second, third, iter) } /// Returns the first three components and the remaining iterator. #[allow(clippy::panic)] pub fn non_empty_components( &self, ) -> (Component<'_>, Component<'_>, Component<'_>, Components<'_>) { let mut components = self.components(); let (Some(first), Some(second), Some(third)) = (components.next(), components.next(), components.next()) else { panic!("QualifiedPattern::non_empty_components: missing component"); }; (first, second, third, components) } /// Returns an owned qualified pattern. #[inline] pub fn to_owned<'b>(&self) -> QualifiedPattern<'b> { QualifiedPattern(Cow::Owned(self.0.clone().into_owned())) } /// Converts this value into an owned qualified pattern. #[inline] pub fn into_owned<'b>(self) -> QualifiedPattern<'b> { QualifiedPattern(Cow::Owned(self.0.into_owned())) } /// Converts this qualified pattern into an owned pattern. #[inline] pub fn into_patternstring(self) -> PatternString { self.into() } } impl Deref for QualifiedPattern<'_> { type Target = PatternStr; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef for QualifiedPattern<'_> { #[inline] fn as_ref(&self) -> &PatternStr { self } } impl AsRef for QualifiedPattern<'_> { #[inline] fn as_ref(&self) -> &str { self.0.as_str() } } impl AsRef for QualifiedPattern<'_> { #[inline] fn as_ref(&self) -> &Self { self } } impl<'a> From> for Cow<'a, PatternStr> { #[inline] fn from(pattern: QualifiedPattern<'a>) -> Self { pattern.0 } } impl From> for PatternString { #[inline] fn from(pattern: QualifiedPattern<'_>) -> Self { pattern.0.into_owned() } } /// A qualified refspec pattern under a Git namespace. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] pub struct NamespacedPattern<'a>(Cow<'a, PatternStr>); impl<'a> NamespacedPattern<'a> { /// Returns the namespace component. #[allow(clippy::panic)] pub fn namespace(&self) -> Component<'_> { let Some(namespace) = self.components().nth(2) else { panic!("NamespacedPattern::namespace: missing namespace component"); }; namespace } /// Removes the outer namespace. #[allow(clippy::panic)] pub fn strip_namespace(&self) -> PatternString { match PatternString::from_components(self.components().skip(3)) { Ok(pattern) => pattern, Err(_) => panic!("NamespacedPattern::strip_namespace: duplicate glob"), } } /// Removes all nested namespaces. pub fn strip_namespace_recursive(&self) -> PatternString { let mut stripped = self.strip_namespace(); while let Some(namespaced) = stripped.to_namespaced() { stripped = namespaced.strip_namespace(); } stripped } /// Returns an owned namespaced pattern. #[inline] pub fn to_owned<'b>(&self) -> NamespacedPattern<'b> { NamespacedPattern(Cow::Owned(self.0.clone().into_owned())) } /// Converts this value into an owned namespaced pattern. #[inline] pub fn into_owned<'b>(self) -> NamespacedPattern<'b> { NamespacedPattern(Cow::Owned(self.0.into_owned())) } /// Converts this value into a qualified pattern. #[inline] pub fn into_qualified(self) -> QualifiedPattern<'a> { QualifiedPattern(self.0) } } impl Deref for NamespacedPattern<'_> { type Target = PatternStr; #[inline] fn deref(&self) -> &Self::Target { self.borrow() } } impl AsRef for NamespacedPattern<'_> { #[inline] fn as_ref(&self) -> &PatternStr { self.0.as_ref() } } impl AsRef for NamespacedPattern<'_> { #[inline] fn as_ref(&self) -> &str { self.0.as_str() } } impl Borrow for NamespacedPattern<'_> { #[inline] fn borrow(&self) -> &PatternStr { PatternStr::from_str(self.0.as_str()) } } impl<'a> From> for QualifiedPattern<'a> { #[inline] fn from(pattern: NamespacedPattern<'a>) -> Self { Self(pattern.0) } } impl<'a> From<&'a PatternStr> for Option> { fn from(pattern: &'a PatternStr) -> Self { let mut components = pattern.iter(); match ( components.next(), components.next(), components.next(), components.next(), ) { (Some("refs"), Some("namespaces"), Some(_), Some("refs")) => { Some(NamespacedPattern(Cow::from(pattern))) } _ => None, } } } impl Display for NamespacedPattern<'_> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } /// A Git refspec with source, destination, and force flag. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Refspec { /// Source refspec side. pub src: T, /// Destination refspec side. pub dst: U, /// Whether this is a forced refspec. pub force: bool, } impl Display for Refspec where T: Display, U: Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.force { f.write_char('+')?; } write!(f, "{}:{}", self.src, self.dst) } }