use std::path::{Path, PathBuf};
use serde::Deserialize;
use crate::domain::{Metadata, MetadataContext};
#[derive(Debug)]
pub(crate) struct Domain;
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Config {
manifests: crate::config::Patterns,
#[serde(default, rename = "source-documentation")]
source_documentation: bool,
}
impl crate::domain::registry::Domain for Domain {
type Config = Config;
type State = ();
const NAME: &'static str = "lua";
fn manifests(
config: &Self::Config,
_state: &Self::State,
root: &Path,
files: &crate::domain::IndexedFiles,
) -> Result<Vec<PathBuf>, crate::domain::Error> {
Ok(crate::config::matching_files(
root,
files,
&config.manifests,
))
}
fn metadata(
_config: &Self::Config,
_state: &Self::State,
context: &MetadataContext<'_>,
) -> Result<Option<Metadata>, crate::domain::Error> {
let mut name = None;
let mut description = None;
for line in context.manifest_source.lines() {
let Some((key, value)) = line
.trim()
.strip_prefix("## ")
.and_then(|line| line.split_once(':'))
else {
continue;
};
match key.trim() {
"Title" => name = Some(value.trim().to_string()),
"Notes" => description = Some(value.trim().to_string()),
_ => {}
}
}
Ok(Some(Metadata {
name: name.or_else(|| crate::domain::directory_name(context.directory)),
description,
kind: "lua",
..Metadata::default()
}))
}
fn source_description(
config: &Self::Config,
_state: &Self::State,
path: &Path,
source: &str,
) -> Option<String> {
config.source_documentation.then_some(())?;
(path.extension()?.to_str()? == "lua").then_some(())?;
source.lines().take(10).find_map(|line| {
line.trim()
.strip_prefix("---")
.map(str::trim)
.filter(|description| !description.is_empty())
.map(str::to_string)
})
}
}
crate::domain::registry::register_domain!(Domain);
#[cfg(test)]
mod tests {
use googletest::prelude::*;
use super::*;
use crate::{WorkspaceFile, WorkspaceIndex};
#[gtest]
fn parses_configured_toc_metadata_as_lua() -> Result<()> {
let root = Path::new("/ws/addon");
let workspace = WorkspaceIndex::new_domain(
root.to_path_buf(),
vec![WorkspaceFile {
path: root.join("addon.toc"),
contents: Some("## Title: Example\n## Notes: Lua addon\n".into()),
}],
"lua",
toml::Value::Table(toml::toml! { manifests = ["addon.toc"] }),
);
let metadata = workspace.metadata(root).or_fail()?;
verify_eq!(metadata.kind, "lua")?;
verify_eq!(metadata.name.as_deref(), Some("Example"))?;
verify_eq!(metadata.description.as_deref(), Some("Lua addon"))
}
}