use std::collections::{HashMap, HashSet};
use std::ffi::OsString;
use std::io::Read;
use std::path::{Path, PathBuf};
use crate::output::Durability;
use mds::{
effective_parent, CompiledOutput, MdsError, MAX_FILE_SIZE, MAX_TRAVERSAL_DEPTH,
STRING_SOURCE_MAP_LABEL,
};
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)]
pub(crate) rules: HashMap<String, mds::Severity>,
}
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) fn load_config(start: &Path) -> Result<Option<(MdsConfig, PathBuf)>> {
let raw_start_dir = if start.is_dir() {
start.to_path_buf()
} else {
effective_parent(start).to_path_buf()
};
let mut current = match raw_start_dir.canonicalize() {
Ok(p) => p,
Err(_) => raw_start_dir,
};
for _ in 0..MAX_TRAVERSAL_DEPTH {
let candidate = current.join("mds.json");
if candidate.is_file() {
let bytes = std::fs::read(&candidate)
.map_err(|e| miette::miette!("cannot read {}: {e}", candidate.display()))?;
if bytes.len() as u64 > MAX_CONFIG_SIZE {
return Err(miette::miette!(
"mds.json at {} is too large ({} bytes; maximum is 1 MB)",
candidate.display(),
bytes.len()
));
}
let raw = String::from_utf8(bytes)
.map_err(|e| miette::miette!("invalid UTF-8 in {}: {e}", candidate.display()))?;
let config: MdsConfig = serde_json::from_str(&raw)
.map_err(|e| miette::miette!("invalid mds.json at {}: {e}", candidate.display()))?;
return Ok(Some((config, current)));
}
match current.parent() {
Some(parent) => current = parent.to_path_buf(),
None => break,
}
}
Ok(None)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum OutputKind {
Markdown,
Messages,
}
impl OutputKind {
pub(crate) fn extension(self) -> &'static str {
match self {
OutputKind::Markdown => "md",
OutputKind::Messages => "json",
}
}
pub(crate) fn stale_extension(self) -> &'static str {
match self {
OutputKind::Markdown => "json", OutputKind::Messages => "md", }
}
}
fn kind_label(kind: OutputKind) -> &'static str {
match kind {
OutputKind::Markdown => "markdown (.md)",
OutputKind::Messages => "messages JSON (.json)",
}
}
impl From<&CompiledOutput> for OutputKind {
fn from(output: &CompiledOutput) -> Self {
match output {
CompiledOutput::Markdown(_) => OutputKind::Markdown,
CompiledOutput::Messages(_) => OutputKind::Messages,
_ => unreachable!("unknown CompiledOutput variant"),
}
}
}
pub(crate) fn derive_output_filename_for_kind(input: &Path, kind: OutputKind) -> OsString {
let stem = input.file_stem().unwrap_or(input.as_os_str());
let mut name = OsString::from(stem);
name.push(".");
name.push(kind.extension());
name
}
pub(crate) fn compute_output_dir_path_for_kind(
dir: &Path,
input_path: Option<&Path>,
kind: OutputKind,
) -> PathBuf {
let filename = input_path
.map(|p| derive_output_filename_for_kind(p, kind))
.unwrap_or_else(|| {
OsString::from(match kind {
OutputKind::Markdown => "output.md",
OutputKind::Messages => "output.json",
})
});
dir.join(filename)
}
pub(crate) fn prepare_output_dir_for_kind(
dir: &Path,
input_path: Option<&Path>,
kind: OutputKind,
) -> Result<PathBuf> {
std::fs::create_dir_all(dir)
.map_err(|e| miette::miette!("cannot create output directory {}: {e}", dir.display()))?;
Ok(compute_output_dir_path_for_kind(dir, input_path, kind))
}
pub(crate) fn resolve_output_path_for_kind(
input: &Option<PathBuf>,
output: &Option<String>,
out_dir: &Option<PathBuf>,
config: &Option<(MdsConfig, PathBuf)>,
kind: OutputKind,
quiet: bool,
) -> Result<Option<PathBuf>> {
match output.as_deref() {
Some("-") => return Ok(None),
Some(o) => {
let path = PathBuf::from(o);
if !quiet {
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
let expected = kind.extension();
if ext != expected {
eprintln!(
"warning: output path '{}' has extension '.{}' but compiled \
output is {}; writing to '{}' anyway",
crate::output::safe_inline(o),
crate::output::safe_inline(ext),
kind_label(kind),
crate::output::safe_inline(o)
);
}
}
}
return Ok(Some(path));
}
None => {}
}
let input_path = input.as_deref().filter(|p| *p != Path::new("-"));
if input_path.is_none() && out_dir.is_none() {
return Ok(None);
}
if let Some(dir) = out_dir {
return Ok(Some(prepare_output_dir_for_kind(dir, input_path, kind)?));
}
if let Some((cfg, config_dir)) = config {
if let Some(ref output_dir) = cfg.build.output_dir {
let traversal = Path::new(output_dir)
.components()
.any(|c| c == std::path::Component::ParentDir);
if traversal {
return Err(miette::miette!(
"mds.json output_dir '{}' must not contain '..' components",
output_dir
));
}
let dir = config_dir.join(output_dir);
return Ok(Some(prepare_output_dir_for_kind(&dir, input_path, kind)?));
}
}
match input_path {
Some(p) => {
let filename = derive_output_filename_for_kind(p, kind);
let dir = effective_parent(p);
Ok(Some(dir.join(filename)))
}
None => Ok(None),
}
}
pub(crate) fn parse_key_value(s: &str) -> std::result::Result<(String, String), String> {
let pos = s
.find('=')
.ok_or_else(|| format!("invalid KEY=VALUE: no '=' found in '{s}'"))?;
Ok((s[..pos].to_string(), s[pos + 1..].to_string()))
}
pub(crate) fn parse_cli_value(val: String) -> mds::Value {
match val.as_str() {
"true" => return mds::Value::Boolean(true),
"false" => return mds::Value::Boolean(false),
"null" => return mds::Value::Null,
_ => {}
}
if let Ok(n) = val.parse::<i64>() {
return mds::Value::Number(n as f64);
}
if let Ok(f) = val.parse::<f64>() {
if f.is_finite() {
return mds::Value::Number(f);
}
}
if val.starts_with('[') && val.ends_with(']') {
let inner = &val[1..val.len() - 1];
if inner.trim().is_empty() {
return mds::Value::Array(vec![]);
}
let items: Vec<mds::Value> = inner
.split(',')
.map(|s| mds::Value::String(s.trim().to_string()))
.collect();
return mds::Value::Array(items);
}
mds::Value::String(val)
}
pub(crate) fn exit_code(err: &miette::Error) -> i32 {
let mds_err = err.downcast_ref::<MdsError>().or_else(|| {
err.downcast_ref::<crate::output::StdinRelabeledError>()
.map(crate::output::StdinRelabeledError::inner)
});
if let Some(mds_err) = mds_err {
match mds_err {
MdsError::Io { .. } | MdsError::FileNotFound { .. } | MdsError::NotMdsFile { .. } => 2,
MdsError::ResourceLimit { .. } => 3,
MdsError::VarConflict { .. } => 1,
_ => 1,
}
} else {
1
}
}
pub(crate) fn ensure_existing_mds_file(path: &Path) -> Result<(), MdsError> {
let exists = path.try_exists().map_err(|e| MdsError::Io {
message: format!("cannot check {}: {e}", path.display()),
})?;
if !exists {
return Err(MdsError::FileNotFound {
path: path.display().to_string(),
span: None,
src: None,
});
}
if path.extension().and_then(|e| e.to_str()) != Some("mds") {
return Err(MdsError::NotMdsFile {
path: path.display().to_string(),
});
}
Ok(())
}
pub(crate) struct RuntimeVarArgs {
pub(crate) vars: Option<PathBuf>,
pub(crate) set_vars: Vec<(String, String)>,
pub(crate) set_string_vars: Vec<(String, String)>,
}
pub(crate) fn load_optional_vars_file(path: Option<PathBuf>) -> Result<Option<mds::VarsLoad>> {
path.map(|p| mds::load_vars_file_reporting_duplicates(&p).map_err(miette::Error::from))
.transpose()
}
#[derive(Debug)]
pub(crate) struct RuntimeVars {
pub(crate) vars: Option<HashMap<String, mds::Value>>,
pub(crate) duplicate_set_keys: Vec<String>,
pub(crate) duplicate_set_string_keys: Vec<String>,
pub(crate) duplicate_vars_file_keys: Vec<String>,
pub(crate) duplicate_vars_file_keys_omitted: usize,
pub(crate) vars_file: Option<PathBuf>,
}
fn duplicate_keys(pairs: &[(String, String)]) -> Vec<String> {
let mut seen: HashSet<&str> = HashSet::new();
let mut dupes: Vec<String> = Vec::new();
for (k, _) in pairs {
if !seen.insert(k.as_str()) && !dupes.iter().any(|d: &String| d == k) {
dupes.push(k.clone());
}
}
dupes
}
pub(crate) fn build_runtime_vars(args: RuntimeVarArgs) -> Result<RuntimeVars> {
let RuntimeVarArgs {
vars,
set_vars,
set_string_vars,
} = args;
let set_keys: HashSet<&str> = set_vars.iter().map(|(k, _)| k.as_str()).collect();
for (key, _) in &set_string_vars {
if set_keys.contains(key.as_str()) {
return Err(miette::Error::from(MdsError::VarConflict {
key: key.clone(),
}));
}
}
let duplicate_set_keys = duplicate_keys(&set_vars);
let duplicate_set_string_keys = duplicate_keys(&set_string_vars);
let vars_file = vars.clone();
let loaded = load_optional_vars_file(vars)?;
let (mut runtime_vars, duplicate_vars_file_keys, duplicate_vars_file_keys_omitted) =
match loaded {
Some(mds::VarsLoad {
vars,
duplicate_keys,
duplicate_keys_omitted,
..
}) => (Some(vars), duplicate_keys, duplicate_keys_omitted),
None => (None, Vec::new(), 0),
};
for (key, val) in set_vars {
runtime_vars
.get_or_insert_with(HashMap::new)
.insert(key, parse_cli_value(val));
}
for (key, val) in set_string_vars {
runtime_vars
.get_or_insert_with(HashMap::new)
.insert(key, mds::Value::String(val));
}
Ok(RuntimeVars {
vars: runtime_vars,
duplicate_set_keys,
duplicate_set_string_keys,
duplicate_vars_file_keys,
duplicate_vars_file_keys_omitted,
vars_file,
})
}
pub(crate) fn emit_duplicate_vars_file_warnings(resolved: &RuntimeVars, quiet: bool) {
if quiet {
return;
}
let Some(path) = resolved.vars_file.as_deref() else {
return;
};
for key in &resolved.duplicate_vars_file_keys {
crate::output::eprint_warning(&format!(
"warning: key '{}' is set more than once in vars file {}; the last value wins",
crate::output::safe_inline(key),
crate::output::safe_path(path)
));
}
if resolved.duplicate_vars_file_keys_omitted > 0 {
crate::output::eprint_warning(&format!(
"warning: {} more duplicate keys in vars file {} are not listed",
crate::output::safe_inline(resolved.duplicate_vars_file_keys_omitted),
crate::output::safe_path(path)
));
}
}
pub(crate) fn emit_duplicate_var_warnings(resolved: &RuntimeVars, quiet: bool) {
if quiet {
return;
}
emit_duplicate_vars_file_warnings(resolved, quiet);
for key in &resolved.duplicate_set_keys {
crate::output::eprint_warning(&format!(
"warning: variable '{}' is set more than once by --set; the last value wins",
crate::output::safe_inline(key)
));
}
for key in &resolved.duplicate_set_string_keys {
crate::output::eprint_warning(&format!(
"warning: variable '{}' is set more than once by --set-string; the last value wins",
crate::output::safe_inline(key)
));
}
}
pub(crate) fn read_stdin() -> Result<(String, PathBuf)> {
let mut source = String::new();
std::io::stdin()
.take(MAX_FILE_SIZE + 1)
.read_to_string(&mut source)
.map_err(|e| miette::miette!("cannot read stdin: {e}"))?;
if source.len() as u64 > MAX_FILE_SIZE {
return Err(miette::miette!("stdin input exceeds maximum size of 10 MB"));
}
let cwd = std::env::current_dir()
.map_err(|e| miette::miette!("cannot determine current directory: {e}"))?;
Ok((source, cwd))
}
pub(crate) fn write_output(
output_path: Option<PathBuf>,
compiled: &str,
quiet: bool,
announce: bool,
) -> Result<()> {
match output_path {
Some(path) => {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent).map_err(|e| {
miette::miette!("cannot create output directory {}: {e}", parent.display())
})?;
}
}
crate::output::atomic_write_file(&path, compiled, Durability::RenameOnly)?;
if !quiet && announce {
eprintln!("Compiled to {}", crate::output::safe_path(&path));
}
}
None => {
use std::io::Write as _;
print!("{compiled}");
std::io::stdout()
.flush()
.map_err(|e| miette::miette!("cannot flush stdout: {e}"))?;
}
}
Ok(())
}
pub(crate) fn auto_detect_mds_file(subcommand: &str) -> Result<PathBuf> {
let cwd = std::env::current_dir()
.map_err(|e| miette::miette!("cannot determine current directory: {e}"))?;
let entries: Vec<PathBuf> = std::fs::read_dir(&cwd)
.map_err(|e| miette::miette!("cannot read directory {}: {e}", cwd.display()))?
.filter_map(|res| {
let path = res.ok()?.path();
(path.is_file() && path.extension().and_then(|e| e.to_str()) == Some("mds"))
.then_some(path)
})
.collect();
match entries.as_slice() {
[] => Err(miette::miette!(
"no .mds files found in current directory\n \
hint: run 'mds init' to create a starter template"
)),
[single] => Ok(single.clone()),
_ => {
let mut names: Vec<String> = entries
.iter()
.filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(str::to_owned))
.collect();
names.sort();
Err(miette::miette!(
"multiple .mds files found: {}\n \
hint: specify which file, e.g. 'mds {subcommand} {}'",
names.join(", "),
names.first().map(|s| s.as_str()).unwrap_or("<file>.mds"),
))
}
}
}
pub(crate) struct CompileOutput {
pub(crate) content: String,
pub(crate) kind: OutputKind,
pub(crate) dependencies: Vec<String>,
pub(crate) source_map: Option<mds::SourceMap>,
}
fn serialize_output(output: CompiledOutput) -> Result<String> {
match output {
CompiledOutput::Markdown(s) => Ok(s),
CompiledOutput::Messages(msgs) => {
let mut json = serde_json::to_string_pretty(&msgs)
.map_err(|e| miette::miette!("failed to serialize messages to JSON: {e}"))?;
json.push('\n');
Ok(json)
}
_ => unreachable!("unknown CompiledOutput variant"),
}
}
pub(crate) fn compile_to_content(
input: &Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
opts: mds::CompileOptions,
) -> Result<CompileOutput> {
let result = if input == Path::new("-") {
let (source, cwd) = read_stdin()?;
mds::compile_str_with_deps_opts(&source, Some(&cwd), runtime_vars, opts)
.map_err(|e| crate::output::relabel_stdin_error(&e, &source))?
} else {
mds::compile_with_deps_opts(input, runtime_vars, opts).map_err(miette::Error::from)?
};
if !quiet {
for w in &result.warnings {
crate::output::eprint_warning(w);
}
}
let kind = OutputKind::from(&result.output);
let source_map = result.source_map;
let content = serialize_output(result.output)?;
Ok(CompileOutput {
content,
kind,
dependencies: result.dependencies,
source_map,
})
}
pub(crate) fn compile_and_write(
input: &Path,
output: &Option<String>,
out_dir: &Option<PathBuf>,
config: &Option<(MdsConfig, PathBuf)>,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
opts: mds::CompileOptions,
) -> Result<(Option<PathBuf>, Vec<String>, String)> {
let compiled = compile_to_content(input, runtime_vars, quiet, opts)?;
let output_path = resolve_output_path_for_kind(
&Some(input.to_path_buf()),
output,
out_dir,
config,
compiled.kind,
quiet,
)?;
write_output(output_path.clone(), &compiled.content, quiet, true)?;
Ok((output_path, compiled.dependencies, compiled.content))
}
pub(crate) struct BuildArgs {
pub(crate) input: Option<PathBuf>,
pub(crate) output: Option<String>,
pub(crate) out_dir: Option<PathBuf>,
pub(crate) vars: Option<PathBuf>,
pub(crate) set_vars: Vec<(String, String)>,
pub(crate) set_string_vars: Vec<(String, String)>,
pub(crate) quiet: bool,
pub(crate) source_map: bool,
pub(crate) no_source_map: bool,
pub(crate) inline: bool,
pub(crate) embed_sources: bool,
}
pub(crate) fn resolve_input(input: Option<PathBuf>, subcommand: &str) -> Result<(PathBuf, bool)> {
match input {
Some(p) => Ok((p, false)),
None => auto_detect_mds_file(subcommand).map(|p| (p, true)),
}
}
pub(crate) fn map_path_for(output_path: &Path) -> PathBuf {
let mut s = output_path.as_os_str().to_owned();
s.push(".map");
PathBuf::from(s)
}
pub(crate) fn base64_encode(input: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let n = (b0 << 16) | (b1 << 8) | b2;
out.push(ALPHABET[((n >> 18) & 0x3f) as usize] as char);
out.push(ALPHABET[((n >> 12) & 0x3f) as usize] as char);
if chunk.len() > 1 {
out.push(ALPHABET[((n >> 6) & 0x3f) as usize] as char);
} else {
out.push('=');
}
if chunk.len() > 2 {
out.push(ALPHABET[(n & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
out
}
pub(crate) fn carrier_line(map_json: &str) -> String {
let b64 = base64_encode(map_json.as_bytes());
format!("<!--# sourceMappingURL=data:application/json;base64,{b64} -->")
}
fn strip_existing_carrier(content: &str) -> &str {
let trimmed = content.trim_end_matches('\n');
if let Some(pos) = trimmed.rfind('\n') {
let last_line = &trimmed[pos + 1..];
if last_line.starts_with("<!--# sourceMappingURL=data:") {
return &content[..pos + 1];
}
} else if trimmed.starts_with("<!--# sourceMappingURL=data:") {
return "";
}
content
}
pub(crate) fn embed_carrier(content: String, map_json: &str) -> String {
let base = strip_existing_carrier(&content);
let sep = if base.ends_with('\n') { "" } else { "\n" };
format!("{base}{sep}{}\n", carrier_line(map_json))
}
fn compute_source_map_base(
input: &Path,
output: &Option<String>,
out_dir: &Option<PathBuf>,
config: &Option<(MdsConfig, PathBuf)>,
) -> Option<PathBuf> {
let cwd = || std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let abs = |p: PathBuf| -> PathBuf {
if p.is_absolute() {
p
} else {
cwd().join(p)
}
};
match output.as_deref() {
Some("-") => {
Some(cwd())
}
Some(o) => {
Some(abs(effective_parent(Path::new(o)).to_path_buf()))
}
None => {
if let Some(dir) = out_dir {
Some(abs(dir.clone()))
} else if input == Path::new("-") {
Some(cwd())
} else if let Some((cfg, config_dir)) = config {
if let Some(ref output_dir) = cfg.build.output_dir {
Some(abs(config_dir.join(output_dir)))
} else {
Some(abs(effective_parent(input).to_path_buf()))
}
} else {
Some(abs(effective_parent(input).to_path_buf()))
}
}
}
}
pub(crate) fn apply_source_map_file_label(
sm: &mut mds::SourceMap,
output_path: Option<&Path>,
stdin_label: bool,
) {
if let Some(out) = output_path {
sm.file = out.file_name().map(|n| n.to_string_lossy().into_owned());
}
if stdin_label {
for src in &mut sm.sources {
if src == STRING_SOURCE_MAP_LABEL {
*src = crate::output::STDIN_DISPLAY_LABEL.to_string();
}
}
}
}
pub(crate) fn verify_then_delete_map(map_path: &Path, expected_basename: &str, quiet: bool) {
let Ok(bytes) = std::fs::read(map_path) else {
return;
};
let Ok(text) = std::str::from_utf8(&bytes) else {
return;
};
let Ok(v) = serde_json::from_str::<serde_json::Value>(text) else {
return;
};
if v.get("version").and_then(|x| x.as_u64()) != Some(3) {
if !quiet {
eprintln!(
"warning: leaving {} in place — not a tool-generated SMv3 map (version/file mismatch)",
crate::output::safe_path(map_path)
);
}
return;
}
if v.get("file").and_then(|x| x.as_str()) != Some(expected_basename) {
if !quiet {
eprintln!(
"warning: leaving {} in place — not a tool-generated SMv3 map (version/file mismatch)",
crate::output::safe_path(map_path)
);
}
return;
}
if let Err(e) = std::fs::remove_file(map_path) {
if !quiet {
eprintln!(
"warning: could not remove stale map {}: {}",
crate::output::safe_path(map_path),
crate::output::safe_inline(&e)
);
}
} else if !quiet {
eprintln!("Removed stale map {}", crate::output::safe_path(map_path));
}
}
pub(crate) fn run_build(args: BuildArgs) -> Result<()> {
let BuildArgs {
input,
output,
out_dir,
vars,
set_vars,
set_string_vars,
quiet,
source_map: flag_source_map,
no_source_map,
inline,
embed_sources: flag_embed_sources,
} = args;
let resolved = build_runtime_vars(RuntimeVarArgs {
vars,
set_vars,
set_string_vars,
})?;
emit_duplicate_var_warnings(&resolved, quiet);
let runtime_vars = resolved.vars;
let (input, auto_detected) = resolve_input(input, "build")?;
if auto_detected && !quiet {
eprintln!("Building {}", crate::output::safe_path(&input));
}
if input != Path::new("-") && input.is_dir() {
if output.is_some() {
return Err(miette::miette!(
"build directory mode does not support -o/--output; \
use --out-dir to specify an output directory"
));
}
if input
.symlink_metadata()
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
{
return Err(miette::miette!(
"directory argument must not be a symlink: {}",
input.display()
));
}
let dir_config = load_config(&input)?;
let cfg_source_map = dir_config
.as_ref()
.map(|(c, _)| c.build.source_map)
.unwrap_or(false);
let cfg_embed_sources = dir_config
.as_ref()
.map(|(c, _)| c.build.embed_sources)
.unwrap_or(false);
let use_source_map = (flag_source_map || cfg_source_map) && !no_source_map;
let use_embed_sources = flag_embed_sources || cfg_embed_sources;
if use_embed_sources && !use_source_map && !quiet {
eprintln!(
"warning: embed_sources has no effect without source maps; \
set build.source_map=true or pass --source-map"
);
}
return run_build_directory(
&input,
out_dir,
runtime_vars,
quiet,
use_source_map,
use_embed_sources,
inline,
);
}
if input == Path::new("-") {
let use_source_map = flag_source_map && !no_source_map;
let use_embed_sources = flag_embed_sources;
if use_embed_sources && !use_source_map && !quiet {
eprintln!(
"warning: embed_sources has no effect without source maps; \
set build.source_map=true or pass --source-map"
);
}
if use_embed_sources && inline && !quiet {
eprintln!(
"warning: --embed-sources with --inline ships full source text in the output \
(AC-SEC-02)"
);
}
let source_map_base = compute_source_map_base(Path::new("-"), &output, &out_dir, &None);
let opts = mds::CompileOptions::default()
.with_source_map(use_source_map)
.with_include_sources_content(use_embed_sources)
.with_source_map_base(source_map_base);
let (source, cwd) = read_stdin()?;
let result = mds::compile_str_with_deps_opts(&source, Some(&cwd), runtime_vars, opts)
.map_err(|e| crate::output::relabel_stdin_error(&e, &source))?;
if !quiet {
for w in &result.warnings {
crate::output::eprint_warning(w);
}
}
let mut source_map = result.source_map;
let kind = OutputKind::from(&result.output);
let content = serialize_output(result.output)?;
let output_path =
resolve_output_path_for_kind(&Some(input), &output, &out_dir, &None, kind, quiet)?;
if let Some(ref mut sm) = source_map {
apply_source_map_file_label(sm, output_path.as_deref(), true);
}
if use_source_map {
if inline {
let map_json = source_map.as_ref().map(|sm| sm.to_json());
let final_content = if let Some(ref json) = map_json {
embed_carrier(content, json)
} else {
content
};
return write_output(output_path, &final_content, quiet, true);
} else {
match &output_path {
None => {
if source_map.is_none() {
return write_output(None, &content, quiet, true);
}
return Err(miette::miette!(
"--source-map (sidecar) requires an output file; use -o <file> or \
--out-dir, --inline to embed the map for stdout, or --no-source-map \
to skip it"
));
}
Some(out) => {
write_output(Some(out.clone()), &content, quiet, true)?;
if let Some(ref sm) = source_map {
let map_path = map_path_for(out);
let map_json = sm.to_json();
crate::output::atomic_write_file(
&map_path,
&map_json,
Durability::RenameOnly,
)?;
if !quiet {
eprintln!(
"Source map written to {}",
crate::output::safe_path(&map_path)
);
}
}
return Ok(());
}
}
}
}
return write_output(output_path, &content, quiet, true);
}
let config = load_config(&input)?;
let cfg_source_map = config
.as_ref()
.map(|(c, _)| c.build.source_map)
.unwrap_or(false);
let cfg_embed_sources = config
.as_ref()
.map(|(c, _)| c.build.embed_sources)
.unwrap_or(false);
let use_source_map = (flag_source_map || cfg_source_map) && !no_source_map;
let use_embed_sources = flag_embed_sources || cfg_embed_sources;
if use_embed_sources && !use_source_map && !quiet {
eprintln!(
"warning: embed_sources has no effect without source maps; \
set build.source_map=true or pass --source-map"
);
}
if use_embed_sources && inline && !quiet {
eprintln!(
"warning: --embed-sources with --inline ships full source text in the output \
(AC-SEC-02)"
);
}
let source_map_base = compute_source_map_base(&input, &output, &out_dir, &config);
let opts = mds::CompileOptions::default()
.with_source_map(use_source_map)
.with_include_sources_content(use_embed_sources)
.with_source_map_base(source_map_base);
let compiled = compile_to_content(&input, runtime_vars, quiet, opts)?;
let output_path = resolve_output_path_for_kind(
&Some(input.clone()),
&output,
&out_dir,
&config,
compiled.kind,
quiet,
)?;
let mut source_map = compiled.source_map;
if let Some(ref mut sm) = source_map {
apply_source_map_file_label(sm, output_path.as_deref(), false);
}
if use_source_map {
if inline {
let map_json = source_map.as_ref().map(|sm| sm.to_json());
let final_content = if let Some(ref json) = map_json {
embed_carrier(compiled.content, json)
} else {
compiled.content
};
write_output(output_path.clone(), &final_content, quiet, true)?;
if let Some(ref out) = output_path {
let map_path = map_path_for(out);
let basename = out
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
verify_then_delete_map(&map_path, &basename, quiet);
}
} else {
match &output_path {
None => {
if source_map.is_none() {
return write_output(None, &compiled.content, quiet, true);
}
if flag_source_map {
return Err(miette::miette!(
"--source-map (sidecar) requires an output file; use -o <file> or \
--out-dir, --inline to embed the map for stdout, or --no-source-map \
to skip it"
));
}
if !quiet {
let cfg_path = config
.as_ref()
.map(|(_, p)| p.display().to_string())
.unwrap_or_else(|| "mds.json".to_owned());
eprintln!(
"warning: source_map in {} has no effect when writing to \
stdout (sidecar requires -o <file> or --out-dir); use --inline to \
embed the map, or --no-source-map to silence this warning",
crate::output::safe_inline(&cfg_path)
);
}
return write_output(None, &compiled.content, quiet, true);
}
Some(out) => {
write_output(Some(out.clone()), &compiled.content, quiet, true)?;
if let Some(ref sm) = source_map {
let map_path = map_path_for(out);
let map_json = sm.to_json();
crate::output::atomic_write_file(
&map_path,
&map_json,
Durability::RenameOnly,
)?;
if !quiet {
eprintln!(
"Source map written to {}",
crate::output::safe_path(&map_path)
);
}
}
}
}
}
} else {
write_output(output_path.clone(), &compiled.content, quiet, true)?;
if let Some(ref out) = output_path {
let map_path = map_path_for(out);
if map_path.exists() {
let basename = out
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
verify_then_delete_map(&map_path, &basename, quiet);
}
}
}
Ok(())
}
fn run_build_directory(
dir: &Path,
out_dir: Option<PathBuf>,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
source_map: bool,
embed_sources: bool,
inline: bool,
) -> Result<()> {
use crate::output::{
canonicalize_out_dir, collect_mds_files_detailed, is_partial, output_base_no_ext,
output_path_for, probe_and_remove_stale, resolve_output_base, OutputBase,
};
const MAX_DEPTH: usize = 64;
let config = load_config(dir)?;
let abs_out_dir = canonicalize_out_dir(out_dir.as_ref());
let output_base = resolve_output_base(abs_out_dir.as_deref(), &config)?;
let canonical_dir = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
let exclude_prefix: Option<PathBuf> = match &output_base {
OutputBase::Dir(d) if d.starts_with(&canonical_dir) => Some(d.clone()),
_ => None,
};
let walk = collect_mds_files_detailed(dir, MAX_DEPTH, exclude_prefix.as_deref());
let files = walk.files;
if files.is_empty() {
if walk.excluded_by_default > 0 {
eprintln!(
"{} .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was built",
walk.excluded_by_default
);
std::process::exit(1);
}
eprintln!(
"no .mds files found in {}; nothing was built",
crate::output::safe_path(dir)
);
std::process::exit(1);
}
if let Some(partials_only_count) = crate::output::partials_only(&files) {
eprintln!(
"{partials_only_count} .mds file(s) found in {} but all are _-prefixed partials; \
nothing was built",
crate::output::safe_path(dir)
);
std::process::exit(1);
}
let mut ok_count: usize = 0;
let mut fail_count: usize = 0;
let mut empty_count: usize = 0;
let mut written_this_run: HashSet<PathBuf> = HashSet::new();
for file in &files {
if is_partial(file) {
continue;
}
let base_no_ext = output_base_no_ext(file, dir, &output_base);
let source_map_base = base_no_ext
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
let opts = mds::CompileOptions::default()
.with_source_map(source_map)
.with_include_sources_content(embed_sources)
.with_source_map_base(Some(source_map_base));
match compile_to_content(file, runtime_vars.clone(), quiet, opts) {
Ok(mut compiled) => {
let ext = compiled.kind.extension();
let out_path = output_path_for(file, dir, &output_base, ext);
if let Some(parent) = out_path.parent() {
if !parent.as_os_str().is_empty() {
if let Err(e) = std::fs::create_dir_all(parent) {
eprintln!(
"error: cannot create output directory {}: {}",
crate::output::safe_path(parent),
crate::output::safe_inline(&e)
);
fail_count += 1;
continue;
}
}
}
if let Some(ref mut sm) = compiled.source_map {
apply_source_map_file_label(sm, Some(&out_path), false);
}
let final_content = if source_map && inline {
if let Some(ref sm) = compiled.source_map {
embed_carrier(compiled.content, &sm.to_json())
} else {
compiled.content
}
} else {
compiled.content
};
let wrote_empty = final_content.is_empty();
match crate::output::atomic_write_file(
&out_path,
&final_content,
Durability::RenameOnly,
) {
Ok(()) => {
if wrote_empty {
empty_count += 1;
}
if !quiet {
eprintln!("Compiled to {}", crate::output::safe_path(&out_path));
}
written_this_run.insert(out_path.clone());
if source_map && !inline {
if let Some(ref sm) = compiled.source_map {
let map_path = map_path_for(&out_path);
let map_json = sm.to_json();
if let Err(e) = crate::output::atomic_write_file(
&map_path,
&map_json,
Durability::RenameOnly,
) {
eprintln!("error: {}", crate::output::safe_inline(&e));
fail_count += 1;
continue;
}
if !quiet {
eprintln!(
"Source map written to {}",
crate::output::safe_path(&map_path)
);
}
}
}
let base_no_ext = output_base_no_ext(file, dir, &output_base);
let stale_path =
base_no_ext.with_extension(compiled.kind.stale_extension());
let safe_to_delete = matches!(output_base, OutputBase::Dir(_))
|| written_this_run.contains(&stale_path);
if safe_to_delete {
probe_and_remove_stale(&base_no_ext, compiled.kind);
}
ok_count += 1;
}
Err(e) => {
eprintln!("error: {}", crate::output::safe_inline(&e));
fail_count += 1;
}
}
}
Err(e) => {
crate::output::eprint_error(e);
fail_count += 1;
}
}
}
if !quiet || fail_count > 0 {
if empty_count > 0 {
eprintln!("{ok_count} built ({empty_count} empty), {fail_count} failed");
} else {
eprintln!("{ok_count} built, {fail_count} failed");
}
}
if fail_count > 0 {
std::process::exit(1);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_map_base_is_absolute_for_every_output_mode() {
let input = PathBuf::from("src/a.mds");
let cases: Vec<(&str, Option<String>, Option<PathBuf>)> = vec![
("-o - (stdout)", Some("-".to_string()), None),
(
"-o relative/out.md",
Some("relative/out.md".to_string()),
None,
),
("-o bare.md", Some("bare.md".to_string()), None),
("-o /abs/out.md", Some("/abs/out.md".to_string()), None),
("--out-dir relative", None, Some(PathBuf::from("dist"))),
("--out-dir /abs", None, Some(PathBuf::from("/abs/dist"))),
("default (beside source)", None, None),
];
for (label, output, out_dir) in cases {
let got = compute_source_map_base(&input, &output, &out_dir, &None)
.unwrap_or_else(|| panic!("{label}: source_map_base must never be None"));
assert!(
got.is_absolute(),
"{label}: source_map_base must be absolute so core's root-containment \
check succeeds; got {got:?}"
);
}
}
#[test]
fn source_map_base_for_bare_filename_output_is_cwd() {
let got = compute_source_map_base(
Path::new("src/a.mds"),
&Some("out.md".to_string()),
&None,
&None,
)
.expect("bare -o must still produce a base");
let cwd = std::env::current_dir().unwrap();
assert_eq!(
got, cwd,
"`-o out.md` writes into the CWD, so the map base is the CWD"
);
}
#[test]
fn source_map_base_tracks_the_output_file_directory() {
let got = compute_source_map_base(
Path::new("src/a.mds"),
&Some("dist/nested/a.md".to_string()),
&None,
&None,
)
.expect("base must be Some");
assert_eq!(got, std::env::current_dir().unwrap().join("dist/nested"));
}
#[test]
fn parse_cli_value_nan_is_string() {
assert_eq!(
parse_cli_value("NaN".to_string()),
mds::Value::String("NaN".to_string()),
"--set val=NaN must produce Value::String, not Value::Number(NaN)"
);
}
#[test]
fn parse_cli_value_infinity_is_string() {
assert_eq!(
parse_cli_value("Infinity".to_string()),
mds::Value::String("Infinity".to_string()),
"--set val=Infinity must produce Value::String, not Value::Number(inf)"
);
}
#[test]
fn parse_cli_value_neg_infinity_is_string() {
assert_eq!(
parse_cli_value("-Infinity".to_string()),
mds::Value::String("-Infinity".to_string()),
"--set val=-Infinity must produce Value::String, not Value::Number(-inf)"
);
}
#[test]
fn parse_cli_value_finite_float_is_number() {
assert_eq!(
parse_cli_value("2.5".to_string()),
mds::Value::Number(2.5),
"finite float must still become Value::Number"
);
}
#[test]
fn derive_output_filename_swaps_mds_extension() {
assert_eq!(
derive_output_filename_for_kind(Path::new("foo.mds"), OutputKind::Markdown),
OsString::from("foo.md")
);
}
#[test]
fn derive_output_filename_preserves_compound_extension() {
assert_eq!(
derive_output_filename_for_kind(Path::new("foo.bar.mds"), OutputKind::Markdown),
OsString::from("foo.bar.md")
);
}
#[test]
fn derive_output_filename_no_extension() {
assert_eq!(
derive_output_filename_for_kind(Path::new("README"), OutputKind::Markdown),
OsString::from("README.md")
);
}
#[test]
fn derive_output_filename_other_extension() {
assert_eq!(
derive_output_filename_for_kind(Path::new("foo.txt"), OutputKind::Markdown),
OsString::from("foo.md")
);
}
#[test]
fn resolve_output_path_dash_o_dash_is_stdout() {
let result = resolve_output_path_for_kind(
&Some(PathBuf::from("foo.mds")),
&Some("-".to_string()),
&None,
&None,
OutputKind::Markdown,
true,
)
.unwrap();
assert_eq!(result, None, "-o - should resolve to stdout (None)");
}
#[test]
fn resolve_output_path_stdin_no_o_is_stdout() {
let result = resolve_output_path_for_kind(
&Some(PathBuf::from("-")),
&None,
&None,
&None,
OutputKind::Markdown,
true,
)
.unwrap();
assert_eq!(
result, None,
"stdin input with no -o should resolve to stdout"
);
}
#[test]
fn resolve_output_path_default_file_next_to_source() {
let result = resolve_output_path_for_kind(
&Some(PathBuf::from("/some/dir/hello.mds")),
&None,
&None,
&None,
OutputKind::Markdown,
true,
)
.unwrap();
assert_eq!(
result,
Some(PathBuf::from("/some/dir/hello.md")),
"default should produce .md next to source"
);
}
#[test]
fn resolve_output_path_stdin_with_out_dir_uses_out_dir() {
let dir = tempfile::tempdir().unwrap();
let out_dir = dir.path().join("out");
let result = resolve_output_path_for_kind(
&Some(PathBuf::from("-")),
&None,
&Some(out_dir.clone()),
&None,
OutputKind::Markdown,
true,
)
.unwrap();
assert_eq!(
result,
Some(out_dir.join("output.md")),
"stdin with --out-dir should produce output.md inside the out dir"
);
}
#[test]
fn resolve_output_path_explicit_o_wins_over_config() {
let config = Some((
MdsConfig {
build: BuildConfig {
output_dir: Some("build".to_string()),
..Default::default()
},
..Default::default()
},
PathBuf::from("/project"),
));
let result = resolve_output_path_for_kind(
&Some(PathBuf::from("/project/hello.mds")),
&Some("out.md".to_string()),
&None,
&config,
OutputKind::Markdown,
true,
)
.unwrap();
assert_eq!(
result,
Some(PathBuf::from("out.md")),
"-o should win over mds.json config"
);
}
#[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");
assert!(
!config.fmt.sort_frontmatter_keys,
"sort_frontmatter_keys: false must deserialize correctly"
);
}
#[test]
fn build_runtime_vars_cross_flag_duplicate_is_error() {
let result = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![("x".to_string(), "1".to_string())],
set_string_vars: vec![("x".to_string(), "2".to_string())],
});
assert!(result.is_err(), "cross-flag duplicate key must be rejected");
let msg = format!("{}", result.unwrap_err());
assert!(
msg.contains("variable 'x' is set by both --set and --set-string"),
"error message must identify the key; got: {msg}"
);
assert!(
msg.contains("use only one"),
"error message must say 'use only one'; got: {msg}"
);
}
#[test]
fn build_runtime_vars_check_command_cross_flag_duplicate_is_error() {
let result = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![("count".to_string(), "3".to_string())],
set_string_vars: vec![("count".to_string(), "three".to_string())],
});
assert!(
result.is_err(),
"cross-flag duplicate must be rejected in check parity"
);
let msg = format!("{}", result.unwrap_err());
assert!(
msg.contains("variable 'count'"),
"error must name the duplicate key; got: {msg}"
);
}
#[test]
fn build_runtime_vars_same_flag_last_wins() {
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![
("x".to_string(), "1".to_string()),
("x".to_string(), "2".to_string()),
],
set_string_vars: vec![],
})
.expect("same-flag last-wins must not error");
let map = resolved.vars.expect("non-empty vars");
assert_eq!(
map.get("x"),
Some(&mds::Value::Number(2.0)),
"last --set wins within the same flag"
);
assert_eq!(
resolved.duplicate_set_keys,
vec!["x".to_string()],
"duplicate_set_keys must list 'x'"
);
assert!(
resolved.duplicate_set_string_keys.is_empty(),
"duplicate_set_string_keys must be empty"
);
}
#[test]
fn build_runtime_vars_same_flag_string_last_wins() {
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![],
set_string_vars: vec![
("id".to_string(), "007".to_string()),
("id".to_string(), "009".to_string()),
],
})
.expect("same-flag last-wins in --set-string must not error");
let map = resolved.vars.expect("non-empty vars");
assert_eq!(
map.get("id"),
Some(&mds::Value::String("009".to_string())),
"last --set-string wins within the same flag"
);
assert_eq!(
resolved.duplicate_set_string_keys,
vec!["id".to_string()],
"duplicate_set_string_keys must list 'id'"
);
assert!(
resolved.duplicate_set_keys.is_empty(),
"duplicate_set_keys must be empty"
);
}
#[test]
fn build_runtime_vars_triple_repeat_reported_once() {
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![
("x".to_string(), "1".to_string()),
("x".to_string(), "2".to_string()),
("x".to_string(), "3".to_string()),
],
set_string_vars: vec![],
})
.expect("triple repeat must not error");
assert_eq!(
resolved.duplicate_set_keys,
vec!["x".to_string()],
"a key repeated 3 times must appear exactly once in duplicate_set_keys; \
got: {:?}",
resolved.duplicate_set_keys
);
}
#[test]
fn build_runtime_vars_distinct_keys_no_duplicates() {
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![
("a".to_string(), "1".to_string()),
("b".to_string(), "2".to_string()),
],
set_string_vars: vec![("c".to_string(), "three".to_string())],
})
.expect("distinct keys must not error");
assert!(
resolved.duplicate_set_keys.is_empty(),
"distinct --set keys must produce no duplicates; got: {:?}",
resolved.duplicate_set_keys
);
assert!(
resolved.duplicate_set_string_keys.is_empty(),
"distinct --set-string keys must produce no duplicates; got: {:?}",
resolved.duplicate_set_string_keys
);
}
#[test]
fn build_runtime_vars_cross_flag_wins_over_intra_flag_duplicate() {
let result = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![
("x".to_string(), "1".to_string()),
("x".to_string(), "2".to_string()),
],
set_string_vars: vec![("x".to_string(), "three".to_string())],
});
assert!(
result.is_err(),
"cross-flag collision must be a hard error even when --set also has a duplicate"
);
let msg = format!("{}", result.unwrap_err());
assert!(
msg.contains("variable 'x' is set by both --set and --set-string"),
"error must identify the cross-flag collision; got: {msg}"
);
}
#[test]
fn embed_carrier_is_idempotent() {
let json = r#"{"version":3,"sources":["a.mds"],"mappings":"AAAA"}"#;
let once = embed_carrier("Hello world\n".to_string(), json);
let twice = embed_carrier(once.clone(), json);
assert_eq!(
once, twice,
"embedding the carrier twice must be idempotent"
);
assert_eq!(
twice.matches("sourceMappingURL=data:").count(),
1,
"the carrier must appear exactly once, got:\n{twice}"
);
}
#[test]
fn carrier_line_cannot_break_out_of_html_comment() {
let hostile_json = r#"{"sourcesContent":["--> break out <script>"]}"#;
let line = carrier_line(hostile_json);
let payload = line
.strip_prefix("<!--# sourceMappingURL=data:application/json;base64,")
.and_then(|s| s.strip_suffix(" -->"))
.expect("carrier must have the expected envelope");
assert!(!payload.contains('<'), "payload must not contain '<'");
assert!(!payload.contains('>'), "payload must not contain '>'");
assert!(!payload.contains('-'), "payload must not contain '-'");
}
#[test]
fn build_runtime_vars_distinct_keys_no_error() {
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![("num".to_string(), "42".to_string())],
set_string_vars: vec![("id".to_string(), "007".to_string())],
})
.expect("distinct keys across flags must not error");
let map = resolved.vars.expect("non-empty vars");
assert_eq!(map.get("num"), Some(&mds::Value::Number(42.0)));
assert_eq!(map.get("id"), Some(&mds::Value::String("007".to_string())));
}
#[test]
fn build_runtime_vars_vars_file_duplicate_key_is_reported() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("vars.json");
std::fs::write(&path, r#"{"x": 1, "x": 2}"#).unwrap();
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: Some(path.clone()),
set_vars: vec![],
set_string_vars: vec![],
})
.expect("duplicate vars-file key must not error");
assert_eq!(resolved.duplicate_vars_file_keys, vec!["x".to_string()]);
assert_eq!(resolved.vars_file, Some(path));
let map = resolved.vars.expect("non-empty vars");
assert_eq!(map.get("x"), Some(&mds::Value::Number(2.0)));
}
#[test]
fn build_runtime_vars_vars_file_nested_duplicate_reports_dotted_path() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("vars.json");
std::fs::write(&path, r#"{"cfg":{"a":1,"a":2}}"#).unwrap();
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: Some(path),
set_vars: vec![],
set_string_vars: vec![],
})
.expect("nested duplicate vars-file key must not error");
assert_eq!(resolved.duplicate_vars_file_keys, vec!["cfg.a".to_string()]);
}
#[test]
fn build_runtime_vars_vars_file_without_duplicates_reports_none() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("vars.json");
std::fs::write(&path, r#"{"name": "World"}"#).unwrap();
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: Some(path.clone()),
set_vars: vec![],
set_string_vars: vec![],
})
.expect("clean vars file must not error");
assert!(
resolved.duplicate_vars_file_keys.is_empty(),
"expected no duplicates, got: {:?}",
resolved.duplicate_vars_file_keys
);
assert_eq!(resolved.duplicate_vars_file_keys_omitted, 0);
assert!(resolved.vars_file.is_some(), "vars_file must be populated");
}
#[test]
fn build_runtime_vars_no_vars_file_reports_no_duplicates_and_no_path() {
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: None,
set_vars: vec![("a".to_string(), "1".to_string())],
set_string_vars: vec![],
})
.expect("no vars file must not error");
assert!(
resolved.duplicate_vars_file_keys.is_empty(),
"expected no duplicates when no vars file was given, got: {:?}",
resolved.duplicate_vars_file_keys
);
assert_eq!(resolved.duplicate_vars_file_keys_omitted, 0);
assert_eq!(
resolved.vars_file, None,
"vars_file must be None when --vars was not given"
);
}
#[test]
fn build_runtime_vars_cross_flag_error_precedes_the_vars_file_read() {
let result = build_runtime_vars(RuntimeVarArgs {
vars: Some(PathBuf::from("/does/not/exist/vars.json")),
set_vars: vec![("x".to_string(), "1".to_string())],
set_string_vars: vec![("x".to_string(), "2".to_string())],
});
assert!(
result.is_err(),
"cross-flag collision must be a hard error even with a nonexistent vars path"
);
let msg = format!("{}", result.unwrap_err());
assert!(
msg.contains("variable 'x' is set by both --set and --set-string"),
"error must be the cross-flag collision, not a file-read error; got: {msg}"
);
}
}