// Copyright (c) Kim Altintop // Copyright (c) The Radicle Team //! Namespaced Git refnames. use super::*; /// A qualified refname under a Git namespace. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)] pub struct Namespaced<'a>(pub(crate) Cow<'a, RefStr>); impl<'a> Namespaced<'a> { /// Returns the namespace component. #[allow(clippy::panic)] pub fn namespace(&self) -> Component<'_> { let Some(namespace) = self.components().nth(2) else { panic!("Namespaced::namespace: missing namespace component"); }; namespace } /// Removes the outer namespace. pub fn strip_namespace<'b>(&self) -> Qualified<'b> { let mut components = self.components().skip(3).collect::(); if components.as_str().is_empty() { components = name::REFS.to_ref_string(); } Qualified(Cow::Owned(components)) } /// Removes all nested namespaces. pub fn strip_namespace_recursive<'b>(&self) -> Qualified<'b> { let mut stripped = self.strip_namespace(); while let Some(namespaced) = stripped.to_namespaced() { stripped = namespaced.strip_namespace(); } stripped } /// Returns an owned namespaced refname. #[inline] pub fn to_owned<'b>(&self) -> Namespaced<'b> { Namespaced(Cow::Owned(self.0.clone().into_owned())) } /// Converts this value into an owned namespaced refname. #[inline] pub fn into_owned<'b>(self) -> Namespaced<'b> { Namespaced(Cow::Owned(self.0.into_owned())) } /// Converts this value into a qualified refname. #[inline] pub fn into_qualified(self) -> Qualified<'a> { Qualified(self.0) } } impl Deref for Namespaced<'_> { type Target = RefStr; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl AsRef for Namespaced<'_> { #[inline] fn as_ref(&self) -> &RefStr { self } } impl AsRef for Namespaced<'_> { #[inline] fn as_ref(&self) -> &str { self.0.as_str() } } impl<'a> From> for Qualified<'a> { #[inline] fn from(namespaced: Namespaced<'a>) -> Self { Qualified(namespaced.0) } } impl<'a> From<&'a RefStr> for Option> { fn from(refname: &'a RefStr) -> Self { let mut components = refname.iter(); match ( components.next(), components.next(), components.next(), components.next(), ) { (Some("refs"), Some("namespaces"), Some(_), Some("refs")) => { Some(Namespaced(Cow::from(refname))) } _ => None, } } } impl<'a, T> From> for Namespaced<'static> where T: Into>, { #[inline] fn from((refs, namespaces, namespace, name): lit::RefsNamespaces<'_, T>) -> Self { Self(Cow::Owned( IntoIterator::into_iter([refs.into(), namespaces.into(), namespace.into()]) .collect::() .and(name), )) } } impl Display for Namespaced<'_> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } }