use std::collections::HashMap;
use std::path::{Path, PathBuf};
use crate::write::Inputs;
use mds::{effective_parent, MAX_TRAVERSAL_DEPTH};
use miette::Result;
use serde::Deserialize;
#[derive(Debug, Default, Deserialize)]
pub(crate) struct MdsConfig {
#[serde(default)]
pub(crate) build: BuildConfig,
#[allow(
dead_code,
reason = "scaffolding for a rule not implemented until a future version"
)]
#[serde(default)]
pub(crate) fmt: FmtConfig,
#[serde(default)]
pub(crate) lint: LintCliConfig,
}
#[derive(Debug, Default, Deserialize)]
pub(crate) struct LintCliConfig {
#[serde(default, deserialize_with = "deserialize_lint_rules")]
pub(crate) rules: HashMap<String, mds::Severity>,
}
fn deserialize_lint_rules<'de, D>(
deserializer: D,
) -> std::result::Result<HashMap<String, mds::Severity>, D::Error>
where
D: serde::Deserializer<'de>,
{
let rules = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
mds::parse_rule_severities(rules, "lint.rules").map_err(serde::de::Error::custom)
}
impl LintCliConfig {
pub(crate) fn into_core_config(self) -> (mds::LintConfig, Option<mds::UnknownRuleNames>) {
mds::LintConfig::from_rules_checked(self.rules)
}
}
#[derive(Debug, Default, Deserialize)]
pub(crate) struct BuildConfig {
pub(crate) output_dir: Option<String>,
#[serde(default)]
pub(crate) source_map: bool,
#[serde(default)]
pub(crate) embed_sources: bool,
}
#[derive(Debug, Deserialize)]
pub(crate) struct FmtConfig {
#[allow(
dead_code,
reason = "scaffolding for a rule not implemented until a future version"
)]
#[serde(default = "default_sort_frontmatter_keys")]
pub(crate) sort_frontmatter_keys: bool,
}
impl Default for FmtConfig {
fn default() -> Self {
Self {
sort_frontmatter_keys: default_sort_frontmatter_keys(),
}
}
}
fn default_sort_frontmatter_keys() -> bool {
true
}
const MAX_CONFIG_SIZE: u64 = 1024 * 1024;
pub(crate) struct ProjectConfig {
pub(crate) config: MdsConfig,
pub(crate) dir: PathBuf,
pub(crate) shown_dir: PathBuf,
}
impl ProjectConfig {
pub(crate) fn shown_file(&self) -> PathBuf {
self.shown_dir.join("mds.json")
}
pub(crate) fn file(&self) -> PathBuf {
self.dir.join("mds.json")
}
}
pub(crate) fn compile_inputs(
entry: Option<&Path>,
dependencies: &[String],
reads: &[PathBuf],
) -> Inputs {
Inputs::new(
entry
.map(Path::to_path_buf)
.into_iter()
.chain(dependencies.iter().map(PathBuf::from))
.chain(reads.iter().cloned()),
)
}
pub(crate) fn run_reads(vars: Option<&Path>, config: Option<&ProjectConfig>) -> Vec<PathBuf> {
vars.map(Path::to_path_buf)
.into_iter()
.chain(config.map(ProjectConfig::file))
.collect()
}
pub(crate) fn load_config(start: &Path) -> Result<Option<ProjectConfig>> {
let Some((current, shown_dir)) = config_dir(start) else {
return Ok(None);
};
let candidate = current.join("mds.json");
let shown = crate::output::safe_path(&shown_dir.join("mds.json"));
let cannot_read = |e: std::io::Error| {
miette::miette!(
"cannot read {shown}: {}",
crate::output::safe_inline(crate::output::io_cause(&e))
)
};
let too_large = |size: u64| {
miette::miette!("mds.json at {shown} is too large ({size} bytes; maximum is 1 MiB)")
};
let mut file = std::fs::File::open(&candidate).map_err(cannot_read)?;
let size = file.metadata().map_err(cannot_read)?.len();
if size > MAX_CONFIG_SIZE {
return Err(too_large(size));
}
let bytes = mds::read_at_most(&mut file, MAX_CONFIG_SIZE + 1, size).map_err(cannot_read)?;
if bytes.len() as u64 > MAX_CONFIG_SIZE {
return Err(too_large(bytes.len() as u64));
}
let raw = String::from_utf8(bytes).map_err(|e| {
miette::miette!(
"invalid UTF-8 in {shown}: {}",
crate::output::safe_inline(&e)
)
})?;
let config: MdsConfig = serde_json::from_str(&raw).map_err(|e| {
miette::miette!(
"invalid mds.json at {shown}: {}",
crate::output::safe_inline(&e)
)
})?;
if let Some(output_dir) = &config.build.output_dir {
let typed = std::ffi::OsStr::new(output_dir);
crate::output::reject_forbidden_output_path("mds.json build.output_dir", typed)?;
crate::output::reject_forbidden_resolved_output_path(
"mds.json build.output_dir",
¤t.join(output_dir),
typed,
)?;
}
Ok(Some(ProjectConfig {
config,
dir: current,
shown_dir,
}))
}
fn config_dir(start: &Path) -> Option<(PathBuf, PathBuf)> {
let raw_start_dir = if start.is_dir() {
start.to_path_buf()
} else {
effective_parent(start).to_path_buf()
};
let mut shown_dir = raw_start_dir.clone();
let mut current = match raw_start_dir.canonicalize() {
Ok(p) => p,
Err(_) => raw_start_dir,
};
for _ in 0..MAX_TRAVERSAL_DEPTH {
if current.join("mds.json").is_file() {
return Some((current, shown_dir));
}
match current.parent() {
Some(parent) => current = parent.to_path_buf(),
None => break,
}
shown_dir.push("..");
}
None
}
pub(crate) fn source_inputs(source: &Path, dependencies: &[String], reads: &[PathBuf]) -> Inputs {
compile_inputs(Some(source), dependencies, reads).and_found_from(source, nearest_config)
}
fn nearest_config(source: &Path) -> Option<PathBuf> {
config_dir(source).map(|(dir, _)| dir.join("mds.json"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fmt_config_malformed_bool_field_fails_loading() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("mds.json"),
r#"{"fmt": {"sort_frontmatter_keys": "not-a-bool"}}"#,
)
.unwrap();
let result = load_config(dir.path());
assert!(
result.is_err(),
"a malformed fmt config (wrong type for sort_frontmatter_keys) must fail config loading"
);
}
#[test]
fn fmt_config_valid_section_loads_cleanly() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("mds.json"),
r#"{"fmt": {"sort_frontmatter_keys": false}}"#,
)
.unwrap();
let result = load_config(dir.path()).expect("valid fmt config must load");
let config = result.expect("mds.json must be found").config;
assert!(
!config.fmt.sort_frontmatter_keys,
"sort_frontmatter_keys: false must deserialize correctly"
);
}
}