use std::{ops::Deref, path::Path};
use serde::{Deserialize, Deserializer, de::Error as _};
#[derive(Clone, Copy, Debug, thiserror::Error)]
pub(crate) enum ValidationError {
#[error("must not be empty")]
Empty,
#[error("must be a portable repository-relative path using forward slashes")]
NotPortable,
#[error("must stay inside the repository and contain no empty path components")]
InvalidComponent,
#[error("must be an exact path without glob metacharacters")]
Glob,
#[error("must be a filename without directory components")]
NotFilename,
#[error("patterns must be portable repository-relative paths using forward slashes")]
PatternNotPortable,
#[error("patterns must stay inside the repository and contain no empty components")]
PatternInvalidComponent,
}
#[derive(Clone, Debug)]
pub(crate) struct Patterns(Box<[Box<str>]>);
impl Patterns {
#[must_use]
pub(crate) fn matches(&self, relative: &str) -> bool {
self.0
.iter()
.any(|pattern| glob_match::glob_match(pattern.as_ref(), relative))
}
}
impl Deref for Patterns {
type Target = [Box<str>];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<'de> Deserialize<'de> for Patterns {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let patterns = Box::<[Box<str>]>::deserialize(deserializer)?;
if patterns.is_empty() {
return Err(D::Error::custom("must contain at least one pattern"));
}
for pattern in &patterns {
validate_pattern(pattern).map_err(D::Error::custom)?;
}
Ok(Self(patterns))
}
}
#[derive(Clone, Debug)]
pub(crate) struct RepositoryPath(Box<str>);
impl RepositoryPath {
#[must_use]
pub(crate) fn as_path(&self) -> &Path {
Path::new(self.0.as_ref())
}
}
impl<'de> Deserialize<'de> for RepositoryPath {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Box::<str>::deserialize(deserializer)?;
validate_path(&value).map_err(D::Error::custom)?;
Ok(Self(value))
}
}
pub(crate) fn validate_filename(value: &str) -> Result<(), ValidationError> {
validate_path(value)?;
if value.contains('/') {
return Err(ValidationError::NotFilename);
}
Ok(())
}
pub(crate) fn validate_path(value: &str) -> Result<(), ValidationError> {
if value.is_empty() {
return Err(ValidationError::Empty);
}
if value.starts_with(['/', '\\']) || value.contains(['\\', '\0', ':']) {
return Err(ValidationError::NotPortable);
}
if value
.split('/')
.any(|component| component.is_empty() || matches!(component, "." | ".."))
{
return Err(ValidationError::InvalidComponent);
}
if value.contains(['*', '?', '[', ']', '{', '}']) {
return Err(ValidationError::Glob);
}
Ok(())
}
fn validate_pattern(value: &str) -> Result<(), ValidationError> {
if value.is_empty() || value.starts_with(['/', '\\']) || value.contains(['\\', '\0', ':']) {
return Err(ValidationError::PatternNotPortable);
}
if value
.split('/')
.any(|component| component.is_empty() || matches!(component, "." | ".."))
{
return Err(ValidationError::PatternInvalidComponent);
}
Ok(())
}
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
#[gtest]
fn paths_are_portable_and_repository_relative() -> Result<()> {
for invalid in ["", ".", "..", "../outside", "/root", "C:/root", "a\\b"] {
verify_true!(validate_path(invalid).is_err())?;
}
verify_true!(validate_path(".cargo/config.toml").is_ok())
}
#[gtest]
fn patterns_allow_globs_but_not_traversal() -> Result<()> {
verify_true!(validate_pattern("crates/*/Cargo.toml").is_ok())?;
verify_true!(validate_pattern("../*/Cargo.toml").is_err())?;
verify_true!(validate_pattern("C:/**/Cargo.toml").is_err())
}
#[gtest]
fn navigation_is_a_portable_filename() -> Result<()> {
for invalid in ["", ".", "..", "/", "docs/README.md", "docs\\README.md"] {
verify_true!(validate_filename(invalid).is_err())?;
}
verify_true!(validate_filename("README.md").is_ok())
}
}