use std::{
collections::BTreeMap,
path::{Path, PathBuf},
};
use serde::Deserialize;
use crate::domain::registry::ConfiguredDomain;
#[cfg(test)]
use crate::domain::registry;
mod error;
#[cfg(test)]
mod tests;
mod validation;
pub(crate) mod value;
pub(crate) use error::Error;
use error::ErrorKind;
pub(crate) use value::{Patterns, RepositoryPath};
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Document {
include: Patterns,
template: String,
#[serde(default)]
domain: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct Render {
templates: RepositoryPath,
header: String,
navigation: String,
#[serde(rename = "source-suffix")]
source_suffix: Box<str>,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Metadata {
pub(crate) name: Option<String>,
pub(crate) description: Option<String>,
domain: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
version: u32,
workspace: Metadata,
render: Render,
documents: Vec<Document>,
domains: BTreeMap<String, toml::Value>,
#[serde(default)]
directories: BTreeMap<String, Metadata>,
}
#[derive(Debug)]
pub(crate) struct Config {
workspace: Metadata,
render: Render,
documents: Vec<Document>,
domains: Vec<ConfiguredDomain>,
directories: BTreeMap<String, Metadata>,
}
impl Config {
pub(crate) fn indexed(path: &Path, source: Option<&str>, exists: bool) -> Result<Self, Error> {
let source = match (source, exists) {
(Some(source), _) => source,
(None, true) => {
return Err(Error {
kind: ErrorKind::NotText {
path: path.to_path_buf(),
},
});
}
(None, false) => {
return Err(Error {
kind: ErrorKind::Missing {
path: path.to_path_buf(),
},
});
}
};
Self::parse(source, path)
}
pub(crate) fn parse(source: &str, path: &Path) -> Result<Self, Error> {
let raw = toml::from_str::<RawConfig>(source).map_err(|source| Error {
kind: ErrorKind::Parse {
path: path.to_path_buf(),
source,
},
})?;
validation::validate(&raw)?;
let domains = validation::configure_domains(raw.domains)?;
validation::validate_namespaces(&domains)?;
validation::validate_metadata_domains(&raw.workspace, &raw.directories, &domains)?;
for (index, document) in raw.documents.iter().enumerate() {
if let Some(domain) = &document.domain
&& !domains.iter().any(|configured| configured.name() == domain)
{
return Err(Error::semantic(
format!("documents[{index}].domain"),
validation::unconfigured_domain(domain),
));
}
}
Ok(Self {
workspace: raw.workspace,
render: raw.render,
documents: raw.documents,
domains,
directories: raw.directories,
})
}
#[cfg(test)]
pub(crate) fn test() -> Self {
Self::parse(TEST_CONFIG, Path::new(crate::layout::CONFIG))
.expect("test config must be valid")
}
#[cfg(test)]
pub(crate) fn test_domain(name: &str, value: toml::Value) -> Self {
let mut config = Self::test();
let registration = registry::registrations()
.find(|registration| registration.name == name)
.expect("test domain must be registered");
config.domains = vec![
ConfiguredDomain::parse(registration, value).expect("test domain config must be valid"),
];
config
}
pub(crate) fn domains(&self) -> impl Iterator<Item = &ConfiguredDomain> {
self.domains.iter()
}
#[must_use]
pub(crate) fn template_directory(&self) -> &Path {
self.render.templates.as_path()
}
#[must_use]
pub(crate) fn header_template(&self) -> &str {
&self.render.header
}
#[must_use]
pub(crate) fn navigation_document(&self) -> &str {
&self.render.navigation
}
#[must_use]
pub(crate) fn output_path(&self, source: &Path) -> PathBuf {
let Some(name) = source.file_name() else {
return source.to_path_buf();
};
let name = name.to_string_lossy();
let output = name
.strip_suffix(self.render.source_suffix.as_ref())
.unwrap_or(&name);
source.with_file_name(output)
}
#[must_use]
pub(crate) fn source_path(&self, output: &Path) -> PathBuf {
let Some(name) = output.file_name() else {
return output.to_path_buf();
};
let mut name = name.to_os_string();
name.push(self.render.source_suffix.as_ref());
output.with_file_name(name)
}
#[must_use]
pub(crate) fn metadata(&self, relative_directory: &Path) -> Option<&Metadata> {
if relative_directory.as_os_str().is_empty() || relative_directory == Path::new(".") {
return Some(&self.workspace);
}
self.directories.get(&normalized(relative_directory))
}
#[must_use]
pub(crate) fn primary_domain(&self, relative_directory: &Path) -> Option<&str> {
self.metadata(relative_directory)?.domain.as_deref()
}
#[must_use]
pub(crate) fn document_template(
&self,
relative_source: &Path,
domain: Option<&str>,
) -> Option<&str> {
let relative = normalized(relative_source);
self.documents.iter().find_map(|document| {
(document
.domain
.as_deref()
.is_none_or(|required| Some(required) == domain)
&& matches_any(&document.include, &relative))
.then_some(document.template.as_str())
})
}
}
pub(crate) fn matches_any(patterns: &Patterns, relative: &str) -> bool {
patterns.matches(relative)
}
pub(crate) fn matching_files(
root: &Path,
files: &crate::domain::IndexedFiles,
patterns: &Patterns,
) -> Vec<PathBuf> {
files
.keys()
.filter_map(|path| {
let relative = path.strip_prefix(root).ok()?;
matches_any(patterns, &normalized(relative)).then(|| path.clone())
})
.collect()
}
fn normalized(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
}
#[cfg(test)]
const TEST_CONFIG: &str = r#"
version = 1
[workspace]
[render]
templates = ".markupwright/templates"
header = "header.md.j2"
navigation = "README.md"
source-suffix = ".in"
[domains.cargo]
manifests = ["__markupwright_test_no_manifest__"]
source-documentation = true
[domains.go]
manifests = ["__markupwright_test_no_manifest__"]
source-documentation = true
[domains.lua]
manifests = ["__markupwright_test_no_manifest__"]
source-documentation = true
[domains.node]
manifests = ["__markupwright_test_no_manifest__"]
source-documentation = true
[domains.php]
manifests = ["__markupwright_test_no_manifest__"]
source-documentation = true
[domains.python]
manifests = ["__markupwright_test_no_manifest__"]
source-documentation = true
[[documents]]
include = ["*.md.in", "**/*.md.in"]
template = "document.md.j2"
"#;