// Copyright (c) Kim Altintop // Copyright (c) The Radicle Team //! Git refname validation. use std::fmt; /// Options controlling Git refname validation. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Options { /// Allows a refname without a slash. pub allow_onelevel: bool, /// Allows exactly one `*` pattern character. pub allow_pattern: bool, } /// A Git refname validation error. #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[non_exhaustive] pub enum Error { /// The refname is empty. Empty, /// The refname is the single character `@`. LoneAt, /// The refname contains consecutive slashes or a trailing slash. Slash, /// A component ends with `.lock`. DotLock, /// The refname contains consecutive dots. DotDot, /// The refname contains `@{`. AtOpenBrace, /// The refname contains an invalid character. InvalidChar(char), /// A component starts with dot. StartsDot, /// A component ends with dot. EndsDot, /// The refname contains an ASCII control character. Control, /// The refname contains a space. Space, /// The refname contains more than one `*`. Pattern, /// The refname must contain at least one slash. OneLevel, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Empty => f.write_str("empty input"), Self::LoneAt => f.write_str("lone '@' character"), Self::Slash => f.write_str("consecutive or trailing slash"), Self::DotLock => f.write_str("ends with '.lock'"), Self::DotDot => f.write_str("consecutive dots ('..')"), Self::AtOpenBrace => f.write_str("at-open-brace ('@{')"), Self::InvalidChar(c) => write!(f, "invalid character {c:?}"), Self::StartsDot => f.write_str("component starts with '.'"), Self::EndsDot => f.write_str("component ends with '.'"), Self::Control => f.write_str("control character"), Self::Space => f.write_str("whitespace"), Self::Pattern => f.write_str("must contain at most one '*'"), Self::OneLevel => f.write_str("must contain at least one '/'"), } } } impl std::error::Error for Error {} /// Validates that `name` is a Git refname. pub fn ref_format(opts: Options, name: &str) -> Result<(), Error> { match name { "" => return Err(Error::Empty), "@" => return Err(Error::LoneAt), "." => return Err(Error::StartsDot), _ => {} } let mut globs = 0usize; let mut parts = 0usize; for component in name.split('/') { if component.is_empty() { return Err(Error::Slash); } if component.ends_with(".lock") { return Err(Error::DotLock); } parts += 1; validate_component(component, &mut globs)?; } if parts < 2 && !opts.allow_onelevel { Err(Error::OneLevel) } else if globs > 1 && opts.allow_pattern { Err(Error::Pattern) } else if globs > 0 && !opts.allow_pattern { Err(Error::InvalidChar('*')) } else { Ok(()) } } /// Validates one Git refname component. fn validate_component(component: &str, globs: &mut usize) -> Result<(), Error> { let next_chars = component.chars().skip(1).map(Some).chain([None]); for (index, (current, next)) in component.chars().zip(next_chars).enumerate() { match (current, next) { ('.', Some('.')) => return Err(Error::DotDot), ('@', Some('{')) => return Err(Error::AtOpenBrace), ('\0' | '\\' | '~' | '^' | ':' | '?' | '[', _) => { return Err(Error::InvalidChar(current)); } ('*', _) => *globs += 1, ('.', _) if index == 0 => return Err(Error::StartsDot), ('.', None) => return Err(Error::EndsDot), (' ', _) => return Err(Error::Space), (c, _) if c.is_ascii_control() => return Err(Error::Control), _ => {} } } Ok(()) }