markupwright 0.1.3

Template-driven workspace documentation generator
Documentation
use std::path::Path;

use serde::Deserialize;

#[derive(Clone, Copy, Debug, Default, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub(crate) enum Scope {
    Root,
    #[default]
    Directory,
}

impl Scope {
    pub(crate) fn base<'a>(self, context: &'a crate::RenderCtx<'_>) -> Option<&'a Path> {
        match self {
            Self::Root if context.is_root() => Some(context.root),
            Self::Root => None,
            Self::Directory => Some(context.dir),
        }
    }
}

pub(crate) fn matching_files<'a>(
    context: &'a crate::RenderCtx<'_>,
    base: &Path,
    patterns: &crate::config::Patterns,
) -> Vec<&'a Path> {
    context
        .workspace
        .files_below(base)
        .filter_map(|(path, _)| {
            let relative = path.strip_prefix(base).ok()?;
            let relative = relative.to_string_lossy().replace('\\', "/");

            crate::config::matches_any(patterns, &relative).then_some(path)
        })
        .collect()
}

pub(crate) fn pattern_matches(
    root: &Path,
    scope: Scope,
    patterns: &crate::config::Patterns,
    path: &Path,
) -> bool {
    match scope {
        Scope::Root => path
            .strip_prefix(root)
            .is_ok_and(|relative| patterns.matches(&relative.to_string_lossy().replace('\\', "/"))),

        Scope::Directory => path
            .ancestors()
            .skip(1)
            .take_while(|base| base.starts_with(root))
            .any(|base| {
                path.strip_prefix(base).is_ok_and(|relative| {
                    patterns.matches(&relative.to_string_lossy().replace('\\', "/"))
                })
            }),
    }
}

pub(crate) fn path_matches(root: &Path, scope: Scope, configured: &Path, path: &Path) -> bool {
    match scope {
        Scope::Root => path == root.join(configured),

        Scope::Directory => path
            .strip_prefix(root)
            .is_ok_and(|relative| relative.ends_with(configured)),
    }
}