markupwright 0.1.3

Template-driven workspace documentation generator
Documentation
use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};

use std::path::{Component, Path, PathBuf};

use crate::{
    config::Config,
    domain::{self, Metadata},
};

type Projects = BTreeMap<PathBuf, Vec<(usize, PathBuf)>>;

pub(crate) mod load;

#[derive(Debug)]
pub(crate) struct WorkspaceFile {
    pub(crate) path: PathBuf,
    pub(crate) contents: Option<Box<str>>,
}

#[derive(Clone, Debug)]
pub(crate) struct WorkspaceIndex {
    root: PathBuf,
    config: Arc<Config>,
    files: Arc<domain::IndexedFiles>,
    directories: Arc<BTreeSet<PathBuf>>,
    metadata: Arc<BTreeMap<PathBuf, Metadata>>,
    manifests: Arc<BTreeSet<PathBuf>>,
    domains: Arc<[domain::registry::Runtime]>,
}

impl WorkspaceIndex {
    #[must_use]
    #[cfg(test)]
    pub(crate) fn new(root: PathBuf, entries: Vec<WorkspaceFile>) -> Self {
        Self::try_new(root, entries, Config::test()).expect("test workspace metadata must be valid")
    }

    #[must_use]
    #[cfg(test)]
    pub(crate) fn new_domain(
        root: PathBuf,
        entries: Vec<WorkspaceFile>,
        name: &str,
        domain_config: toml::Value,
    ) -> Self {
        Self::try_new(root, entries, Config::test_domain(name, domain_config))
            .expect("test project metadata must be valid")
    }

    pub(crate) fn try_new(
        root: PathBuf,
        entries: Vec<WorkspaceFile>,
        config: Config,
    ) -> Result<Self, domain::Error> {
        let mut files = BTreeMap::new();
        let mut directories = BTreeSet::from([root.clone()]);

        for entry in entries {
            if let Some(parent) = entry.path.parent() {
                let mut current = Some(parent);

                while let Some(dir) = current {
                    if !dir.starts_with(&root) {
                        break;
                    }

                    directories.insert(dir.to_path_buf());
                    current = dir.parent();
                }
            }

            files.insert(entry.path, entry.contents);
        }

        let domains = config
            .domains()
            .map(|configured| domain::registry::Runtime::initialize(configured, &root, &files))
            .collect::<Result<Vec<_>, _>>()?;
        let projects = collect_projects(&root, &files, &domains)?;

        let manifests = projects
            .values()
            .flatten()
            .map(|(_, path)| path.clone())
            .collect::<BTreeSet<_>>();

        let metadata = directories
            .iter()
            .map(|dir| {
                let projects = projects
                    .get(dir)
                    .into_iter()
                    .flatten()
                    .map(|(domain_index, path)| {
                        let source = files
                            .get(path)
                            .and_then(|source| source.as_deref())
                            .ok_or_else(|| {
                                domain::Error::message(
                                    path,
                                    domains[*domain_index].name(),
                                    "configured manifest is not UTF-8 text",
                                )
                            })?;

                        Ok(domain::ProjectContext {
                            runtime: &domains[*domain_index],
                            manifest_path: path,
                            manifest_source: source,
                        })
                    })
                    .collect::<Result<Vec<_>, domain::Error>>()?;

                Ok((
                    dir.clone(),
                    domain::resolve(&root, dir, &directories, &config, &projects)?,
                ))
            })
            .collect::<Result<_, domain::Error>>()?;

        Ok(Self {
            root,
            config: Arc::new(config),
            files: Arc::new(files),
            directories: Arc::new(directories),
            metadata: Arc::new(metadata),
            manifests: Arc::new(manifests),
            domains: Arc::from(domains),
        })
    }

    #[must_use]
    pub(crate) fn root(&self) -> &Path {
        &self.root
    }

    #[must_use]
    pub(crate) fn config(&self) -> &Config {
        &self.config
    }

    pub(crate) fn domains(&self) -> impl Iterator<Item = &domain::registry::Runtime> {
        self.domains.iter()
    }

    #[must_use]
    pub(crate) fn contains(&self, path: &Path) -> bool {
        self.files.contains_key(path) || self.directories.contains(path)
    }

    #[must_use]
    pub(crate) fn is_manifest(&self, path: &Path) -> bool {
        self.manifests.contains(path)
    }

    #[must_use]
    pub(crate) fn is_source_input(&self, path: &Path) -> bool {
        self.domains
            .iter()
            .any(|runtime| runtime.is_source_input(&self.root, path))
    }

    #[must_use]
    pub(crate) fn is_dir(&self, path: &Path) -> bool {
        self.directories.contains(path)
    }

    #[must_use]
    pub(crate) fn contents(&self, path: &Path) -> Option<&str> {
        self.files.get(path)?.as_deref()
    }

    #[must_use]
    pub(crate) fn metadata(&self, dir: &Path) -> Option<&Metadata> {
        self.metadata.get(&normalize(dir))
    }

    pub(crate) fn child_dirs(&self, dir: &Path) -> impl Iterator<Item = &Path> {
        self.directories
            .iter()
            .filter(move |candidate| candidate.parent() == Some(dir))
            .map(PathBuf::as_path)
    }

    pub(crate) fn files_in(&self, dir: &Path) -> impl Iterator<Item = &Path> {
        self.files
            .keys()
            .filter(move |candidate| candidate.parent() == Some(dir))
            .map(PathBuf::as_path)
    }

    #[must_use]
    pub(crate) fn has_navigation_document(&self, dir: &Path) -> bool {
        self.has_document(dir, self.config.navigation_document())
    }

    #[must_use]
    pub(crate) fn has_document(&self, dir: &Path, file: &str) -> bool {
        let output = dir.join(file);

        if self.contains(&output) {
            return true;
        }

        let source = self.config.source_path(&output);
        let Some(relative) = source.strip_prefix(&self.root).ok() else {
            return false;
        };
        let domain = self.metadata(dir).and_then(|metadata| metadata.domain);

        self.contains(&source) && self.config.document_template(relative, domain).is_some()
    }

    pub(crate) fn files_below(
        &self,
        directory: &Path,
    ) -> impl Iterator<Item = (&Path, Option<&str>)> {
        self.files
            .iter()
            .filter(move |(path, _)| path.starts_with(directory))
            .map(|(path, contents)| (path.as_path(), contents.as_deref()))
    }

    pub(crate) fn metadata_entries(&self) -> impl Iterator<Item = (&Path, &Metadata)> {
        self.metadata
            .iter()
            .map(|(path, metadata)| (path.as_path(), metadata))
    }

    #[must_use]
    pub(crate) fn has_files_below(&self, dir: &Path) -> bool {
        self.files.keys().any(|path| path.starts_with(dir))
    }
}

fn collect_projects(
    root: &Path,
    files: &domain::IndexedFiles,
    domains: &[domain::registry::Runtime],
) -> Result<Projects, domain::Error> {
    let mut projects = Projects::new();

    for (domain_index, runtime) in domains.iter().enumerate() {
        for path in runtime.manifests(root, files)? {
            let directory = path.parent().ok_or_else(|| {
                domain::Error::message(
                    &path,
                    runtime.name(),
                    "configured manifest has no parent directory",
                )
            })?;
            let manifests = projects.entry(directory.to_path_buf()).or_default();

            if let Some((_, previous)) = manifests
                .iter()
                .find(|(index, _)| domains[*index].name() == runtime.name())
            {
                return Err(domain::Error::message(
                    &path,
                    "markupwright config",
                    format!(
                        "domain {:?} has multiple configured manifests for {}: {} and {}",
                        runtime.name(),
                        directory.display(),
                        previous.display(),
                        path.display()
                    ),
                ));
            }

            manifests.push((domain_index, path));
        }
    }

    Ok(projects)
}

pub(crate) fn normalize(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();

    for component in path.components() {
        match component {
            Component::ParentDir => {
                normalized.pop();
            }

            Component::CurDir => {}

            component => normalized.push(component.as_os_str()),
        }
    }

    normalized
}

#[must_use]
pub(crate) fn relative_path(from: &Path, to: &Path) -> String {
    let from = normalize(from);
    let to = normalize(to);
    let relative = pathdiff::diff_paths(&to, &from).unwrap_or(to);

    if relative.as_os_str().is_empty() {
        return ".".to_string();
    }

    relative.to_string_lossy().replace('\\', "/")
}

#[cfg(test)]
mod tests {
    use googletest::prelude::*;

    use super::*;

    #[gtest]
    fn relative_paths_cover_workspace_relationships() -> Result<()> {
        let cases = [
            ("/ws/crates/common", "/ws/crates/sentinel", "../sentinel"),
            ("/ws/crates/common", "/ws/crates/common", "."),
            ("/ws/crates/common", "/ws/crates", ".."),
            ("/ws/crates", "/ws/crates/common", "common"),
            ("/ws/a/deep", "/ws/b", "../../b"),
        ];

        for (from, to, expected) in cases {
            verify_eq!(relative_path(Path::new(from), Path::new(to)), expected)?;
        }

        Ok(())
    }
}