use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::io::Read;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use crate::output::WriteTarget;
use crate::write::{write_compiled, write_compiled_and_look, Beside, Inputs, NotRemoved, Removal};
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, 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"))
}
#[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 resolve_output_path_for_kind(
input: Option<EntryPaths<'_>>,
output: &Option<String>,
out_dir: &Option<PathBuf>,
config: &Option<ProjectConfig>,
kind: OutputKind,
) -> Result<Option<WriteTarget>> {
match output.as_deref() {
Some("-") => return Ok(None),
Some(o) => return Ok(Some(WriteTarget::as_typed(PathBuf::from(o)))),
None => {}
}
let input = input.filter(|entry| entry.typed != Path::new("-"));
let input_path = input.map(|entry| entry.canonical);
if input_path.is_none() && out_dir.is_none() {
return Ok(None);
}
if let Some(dir) = out_dir {
return Ok(Some(WriteTarget::as_typed(
compute_output_dir_path_for_kind(dir, input_path, kind),
)));
}
if let Some(ProjectConfig {
config,
dir,
shown_dir,
}) = config
{
if let Some(ref output_dir) = config.build.output_dir {
crate::output::reject_output_dir_escape(output_dir)?;
return Ok(Some(WriteTarget::below(
dir,
shown_dir,
&compute_output_dir_path_for_kind(Path::new(output_dir), input_path, kind),
)));
}
}
match input {
Some(entry) => {
let filename = derive_output_filename_for_kind(entry.canonical, kind);
Ok(Some(WriteTarget::new(
effective_parent(entry.canonical).join(&filename),
effective_parent(entry.typed).join(filename),
)))
}
None => Ok(None),
}
}
fn warn_output_extension_mismatch(output: &Option<String>, kind: OutputKind, quiet: bool) {
let Some(o) = output.as_deref().filter(|o| *o != "-") else {
return;
};
if quiet {
return;
}
if let Some(ext) = Path::new(o).extension().and_then(|e| e.to_str()) {
if ext != kind.extension() {
crate::output::ewriteln!(
"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)
);
}
}
}
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::Internal => crate::output::PANIC_EXIT,
MdsError::VarConflict { .. } => 1,
_ => 1,
}
} else {
1
}
}
pub(crate) fn ensure_existing_mds_file(path: &Path) -> Result<(), MdsError> {
crate::output::reject_forbidden_output_path("path", path.as_os_str())?;
let lossy = path.to_string_lossy();
let shown = mds::escape_path_for_message(&lossy);
let exists = path.try_exists().map_err(|e| MdsError::Io {
message: format!(
"cannot check {shown}: {}",
crate::output::safe_inline(crate::output::io_cause(&e))
),
})?;
if !exists {
return Err(MdsError::FileNotFound {
path: shown.into_owned(),
span: None,
src: None,
});
}
if path.extension().and_then(|e| e.to_str()) != Some("mds") {
return Err(MdsError::not_mds_file(shown.into_owned()));
}
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(|e| miette::Error::from(vars_file_error(&p, e)))
})
.transpose()
}
pub(crate) fn vars_file_error(typed: &Path, e: MdsError) -> MdsError {
match e {
MdsError::ImportError { .. } => MdsError::Io {
message: format!(
"--vars file must not be a symlink: \"{}\"",
mds::escape_path_for_message(&typed.to_string_lossy())
),
},
other => other,
}
}
#[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, MdsError> {
read_stdin_from(&mut std::io::stdin().lock())
}
fn read_stdin_from(reader: &mut impl Read) -> Result<String, MdsError> {
let bytes = mds::read_at_most(reader, MAX_FILE_SIZE + 1, 0).map_err(|e| MdsError::Io {
message: format!(
"cannot read stdin: {}",
crate::output::safe_inline(crate::output::io_cause(&e))
),
})?;
if bytes.len() as u64 > MAX_FILE_SIZE {
return Err(MdsError::ResourceLimit {
message: "stdin input exceeds maximum size of 10 MiB".to_owned(),
});
}
String::from_utf8(bytes).map_err(|_| MdsError::Io {
message: "cannot read stdin: stream did not contain valid UTF-8".to_owned(),
})
}
pub(crate) fn write_output(
target: Option<&WriteTarget>,
compiled: &str,
inputs: &Inputs,
quiet: bool,
announce: bool,
) -> Result<()> {
match target {
Some(target) => {
write_compiled(target, compiled, inputs)?;
if !quiet && announce {
crate::output::ewriteln!("Compiled to {}", crate::output::safe_path(&target.shown));
}
}
None => crate::output::write_stdout(compiled.as_bytes()).into_batch_result()?,
}
Ok(())
}
pub(crate) fn auto_detect_mds_file(subcommand: &str) -> Result<PathBuf> {
let entries: Vec<PathBuf> = std::fs::read_dir(".")
.map_err(|e| MdsError::Io {
message: format!(
"cannot read directory .: {}",
crate::output::safe_inline(crate::output::io_cause(&e))
),
})?
.filter_map(|res| {
let name = PathBuf::from(res.ok()?.file_name());
(name.is_file() && name.extension().and_then(|e| e.to_str()) == Some("mds"))
.then_some(name)
})
.collect();
single_mds_file(subcommand, &entries)
}
fn single_mds_file(subcommand: &str, entries: &[PathBuf]) -> Result<PathBuf> {
match entries {
[] => Err(miette::Report::new(AutoDetectError::none())),
[single] => Ok(single.clone()),
several => Err(several_mds_files(subcommand, several)),
}
}
#[derive(Debug)]
pub(crate) struct AutoDetectError {
message: String,
help: String,
}
impl AutoDetectError {
fn none() -> Self {
Self {
message: "no .mds files found in current directory".to_owned(),
help: "run 'mds init' to create a starter template".to_owned(),
}
}
}
impl std::fmt::Display for AutoDetectError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for AutoDetectError {}
impl miette::Diagnostic for AutoDetectError {
fn help<'a>(&'a self) -> Option<Box<dyn std::fmt::Display + 'a>> {
Some(Box::new(&self.help))
}
}
fn several_mds_files(subcommand: &str, entries: &[PathBuf]) -> miette::Report {
let mut names: Vec<String> = entries
.iter()
.filter_map(|p| p.file_name().and_then(|n| n.to_str()))
.map(crate::output::safe_file_display)
.collect();
names.sort();
miette::Report::new(AutoDetectError {
message: format!("multiple .mds files found: {}", names.join(", ")),
help: format!(
"specify which file, e.g. 'mds {subcommand} {}'",
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) => messages_json(&msgs).map_err(|e| {
miette::miette!(
"failed to serialize messages to JSON: {}",
crate::output::safe_inline(&e)
)
}),
_ => unreachable!("unknown CompiledOutput variant"),
}
}
pub(crate) fn messages_json(messages: &[impl serde::Serialize]) -> serde_json::Result<String> {
let mut json = serde_json::to_string_pretty(messages)?;
json.push('\n');
Ok(json)
}
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 = read_stdin()?;
mds::compile_str_with_deps_opts(&source, None, 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)?
};
compiled_content(result, quiet)
}
pub(crate) fn compile_native_to_content(
fs: mds::NativeFs,
input: &Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
opts: mds::CompileOptions,
) -> Result<CompileOutput> {
let result =
mds::compile_native_fs(fs, input, runtime_vars, opts).map_err(miette::Error::from)?;
compiled_content(result, quiet)
}
fn compiled_content(result: mds::CompileResult, quiet: bool) -> Result<CompileOutput> {
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,
})
}
#[derive(Clone, Copy)]
pub(crate) struct EntryPaths<'a> {
pub(crate) typed: &'a Path,
pub(crate) canonical: &'a Path,
}
impl<'a> EntryPaths<'a> {
pub(crate) fn as_typed(path: &'a Path) -> Self {
Self {
typed: path,
canonical: path,
}
}
}
fn file_identity(path: &Path) -> Option<PathBuf> {
let name = path.file_name()?;
let file = resolve_dir_as_created(effective_parent(path))?.join(name);
let is_link = std::fs::symlink_metadata(&file).is_ok_and(|m| m.file_type().is_symlink());
if !is_link {
if let Ok(canonical) = file.canonicalize() {
return Some(canonical);
}
}
Some(file)
}
pub(crate) fn resolve_dir_as_created(dir: &Path) -> Option<PathBuf> {
use std::path::Component;
if let Ok(canonical) = dir.canonicalize() {
return Some(canonical);
}
let absolute = std::path::absolute(dir).ok()?;
let mut resolved = PathBuf::new();
let mut created: usize = 0;
for component in absolute.components() {
match component {
Component::Prefix(_) | Component::RootDir => resolved.push(component),
Component::CurDir => {}
Component::ParentDir => {
resolved.pop();
created = created.saturating_sub(1);
}
Component::Normal(name) => {
let next = resolved.join(name);
if created > 0 {
resolved = next;
created += 1;
} else if let Ok(existing) = next.canonicalize() {
resolved = existing;
} else {
resolved = next;
created = 1;
}
}
}
}
Some(resolved)
}
fn refuse_output_over_entry(output: Option<&Path>, entry: EntryPaths<'_>) -> Result<(), MdsError> {
let Some(output) = output else {
return Ok(());
};
match (file_identity(output), file_identity(entry.canonical)) {
(Some(output), Some(canonical)) if output == canonical => Err(MdsError::Io {
message: format!(
"output would overwrite the entry file: \"{}\"; \
write it elsewhere with -o <file> or --out-dir <dir>",
mds::escape_path_for_message(&entry.typed.to_string_lossy())
),
}),
_ => Ok(()),
}
}
pub(crate) fn admit_output(
output_path: Option<&Path>,
entry: EntryPaths<'_>,
output_arg: &Option<String>,
kind: OutputKind,
quiet: bool,
) -> Result<(), MdsError> {
refuse_output_over_entry(output_path, entry)?;
warn_output_extension_mismatch(output_arg, kind, quiet);
Ok(())
}
pub(crate) struct BuildArgs {
pub(crate) input: Option<PathBuf>,
pub(crate) output: Option<OsString>,
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<ProjectConfig>,
) -> Result<PathBuf, MdsError> {
use crate::output::current_dir;
let abs = |p: PathBuf| -> Result<PathBuf, MdsError> {
if p.is_absolute() {
Ok(p)
} else {
Ok(current_dir()?.join(p))
}
};
match output.as_deref() {
Some("-") => {
current_dir()
}
Some(o) => {
abs(effective_parent(Path::new(o)).to_path_buf())
}
None => {
if let Some(dir) = out_dir {
abs(dir.clone())
} else if input == Path::new("-") {
current_dir()
} else if let Some(ProjectConfig { config, dir, .. }) = config {
if let Some(ref output_dir) = config.build.output_dir {
abs(dir.join(output_dir))
} else {
abs(effective_parent(input).to_path_buf())
}
} else {
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: &WriteTarget,
expected_basename: &str,
quiet: bool,
) -> Result<(), MdsError> {
let proof = |file: &mut std::fs::File| has_sidecar_head(file, expected_basename);
match crate::write::remove_proven(map, proof) {
Ok(Removal::Removed) => {
if !quiet {
crate::output::ewriteln!(
"Removed stale map {}",
crate::output::safe_path(&map.shown)
);
}
Ok(())
}
Ok(Removal::Missing) => Ok(()),
Ok(Removal::Kept) => keep_stale_map(map, "not proven to be written by mds", quiet),
Err(not_a_file @ NotRemoved::NotAFile) => keep_stale_map(map, not_a_file.cause(), quiet),
Err(not_removed) => Err(crate::output::stale_removal_error(
"stale map",
&map.shown,
¬_removed,
)),
}
}
fn keep_stale_map(map: &WriteTarget, why: &str, quiet: bool) -> Result<(), MdsError> {
if !quiet {
crate::output::ewriteln!(
"warning: kept stale map {}: {}",
crate::output::safe_path(&map.shown),
crate::output::safe_inline(why)
);
}
Ok(())
}
fn has_sidecar_head(reader: &mut impl Read, expected_basename: &str) -> std::io::Result<bool> {
let Ok(name) = serde_json::to_string(expected_basename) else {
return Ok(false);
};
let head = format!("{{\"version\":3,\"file\":{name},");
let len = head.len() as u64;
Ok(mds::read_at_most(reader, len, len)? == head.as_bytes())
}
pub(crate) fn reject_forbidden_output_flags(
output: Option<&OsStr>,
out_dir: Option<&Path>,
) -> Result<Option<String>> {
use crate::output::{
reject_forbidden_output_path, reject_forbidden_resolved_output_path,
reject_non_utf8_output_path,
};
let output = match output {
Some(o) => {
reject_forbidden_output_path("-o/--output", o)?;
let text = reject_non_utf8_output_path("-o/--output", o)?;
if text != "-" {
reject_forbidden_resolved_output_path("-o/--output", Path::new(o), o)?;
}
Some(text.to_owned())
}
None => None,
};
if let Some(d) = out_dir {
reject_forbidden_output_path("--out-dir", d.as_os_str())?;
reject_non_utf8_output_path("--out-dir", d.as_os_str())?;
reject_forbidden_resolved_output_path("--out-dir", d, d.as_os_str())?;
}
Ok(output)
}
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 output = reject_forbidden_output_flags(output.as_deref(), out_dir.as_deref())?;
let resolved = build_runtime_vars(RuntimeVarArgs {
vars,
set_vars,
set_string_vars,
})?;
emit_duplicate_var_warnings(&resolved, quiet);
let (input, auto_detected) = resolve_input(input, "build")?;
if auto_detected && !quiet {
crate::output::ewriteln!("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"
));
}
crate::input::resolve_directory_argument(&input).map_err(miette::Error::from)?;
let dir_config = load_config(&input)?;
let cfg_source_map = dir_config
.as_ref()
.map(|c| c.config.build.source_map)
.unwrap_or(false);
let cfg_embed_sources = dir_config
.as_ref()
.map(|c| c.config.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 {
crate::output::ewriteln!(
"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,
resolved,
quiet,
use_source_map,
use_embed_sources,
inline,
);
}
let RuntimeVars {
vars: runtime_vars,
vars_file,
..
} = resolved;
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 {
crate::output::ewriteln!(
"warning: embed_sources has no effect without source maps; \
set build.source_map=true or pass --source-map"
);
}
if use_embed_sources && inline && !quiet {
crate::output::ewriteln!(
"warning: --embed-sources with --inline ships full source text in the output \
(AC-SEC-02)"
);
}
let source_map_base = use_source_map
.then(|| compute_source_map_base(Path::new("-"), &output, &out_dir, &None))
.transpose()?;
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 = read_stdin()?;
let result = mds::compile_str_with_deps_opts(&source, None, 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 inputs = compile_inputs(
None,
&result.dependencies,
&run_reads(vars_file.as_deref(), None),
);
let output_path = resolve_output_path_for_kind(
Some(EntryPaths::as_typed(&input)),
&output,
&out_dir,
&None,
kind,
)?;
warn_output_extension_mismatch(&output, kind, quiet);
if let Some(ref mut sm) = source_map {
apply_source_map_file_label(sm, output_path.as_ref().map(|t| t.path.as_path()), 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.as_ref(), &final_content, &inputs, quiet, true);
} else {
match &output_path {
None => {
if source_map.is_none() {
return write_output(None, &content, &inputs, 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), &content, &inputs, quiet, true)?;
if let Some(ref sm) = source_map {
let map = out.sibling(map_path_for);
let map_json = sm.to_json();
write_compiled(&map, &map_json, &inputs)?;
if !quiet {
crate::output::ewriteln!(
"Source map written to {}",
crate::output::safe_path(&map.shown)
);
}
}
return Ok(());
}
}
}
}
return write_output(output_path.as_ref(), &content, &inputs, quiet, true);
}
let config = load_config(&input)?;
let cfg_source_map = config
.as_ref()
.map(|c| c.config.build.source_map)
.unwrap_or(false);
let cfg_embed_sources = config
.as_ref()
.map(|c| c.config.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 {
crate::output::ewriteln!(
"warning: embed_sources has no effect without source maps; \
set build.source_map=true or pass --source-map"
);
}
if use_embed_sources && inline && !quiet {
crate::output::ewriteln!(
"warning: --embed-sources with --inline ships full source text in the output \
(AC-SEC-02)"
);
}
let source_map_base = use_source_map
.then(|| compute_source_map_base(&input, &output, &out_dir, &config))
.transpose()?;
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 inputs = compile_inputs(
Some(&input),
&compiled.dependencies,
&run_reads(vars_file.as_deref(), config.as_ref()),
);
let entry = EntryPaths::as_typed(&input);
let output_path =
resolve_output_path_for_kind(Some(entry), &output, &out_dir, &config, compiled.kind)?;
let written_path = output_path.as_ref().map(|t| t.path.as_path());
admit_output(written_path, entry, &output, compiled.kind, quiet)
.map_err(miette::Error::from)?;
let mut source_map = compiled.source_map;
if let Some(ref mut sm) = source_map {
apply_source_map_file_label(sm, written_path, 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.as_ref(), &final_content, &inputs, quiet, true)?;
if let Some(ref out) = output_path {
verify_then_delete_map(&out.sibling(map_path_for), &file_name_of(out), quiet)?;
}
} else {
match &output_path {
None => {
if source_map.is_none() {
return write_output(None, &compiled.content, &inputs, 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(ProjectConfig::shown_file)
.unwrap_or_else(|| PathBuf::from("mds.json"));
crate::output::ewriteln!(
"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_path(&cfg_path)
);
}
return write_output(None, &compiled.content, &inputs, quiet, true);
}
Some(out) => {
write_output(Some(out), &compiled.content, &inputs, quiet, true)?;
if let Some(ref sm) = source_map {
let map = out.sibling(map_path_for);
let map_json = sm.to_json();
write_compiled(&map, &map_json, &inputs)?;
if !quiet {
crate::output::ewriteln!(
"Source map written to {}",
crate::output::safe_path(&map.shown)
);
}
}
}
}
}
} else {
write_output(
output_path.as_ref(),
&compiled.content,
&inputs,
quiet,
true,
)?;
if let Some(ref out) = output_path {
verify_then_delete_map(&out.sibling(map_path_for), &file_name_of(out), quiet)?;
}
}
Ok(())
}
fn file_name_of(output: &WriteTarget) -> String {
output
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
fn run_build_directory(
dir: &Path,
out_dir: Option<PathBuf>,
vars: RuntimeVars,
quiet: bool,
source_map: bool,
embed_sources: bool,
inline: bool,
) -> Result<()> {
use crate::output::{
collect_mds_files_detailed, is_partial, output_base_no_ext, output_path_for,
probe_and_remove_stale, resolve_output_base, stale_output, OutputBase, RootPaths,
};
const MAX_DEPTH: usize = 64;
let config = load_config(dir)?;
let reads = run_reads(vars.vars_file.as_deref(), config.as_ref());
let runtime_vars = vars.vars;
let output_base = resolve_output_base(out_dir.as_ref(), &config)?;
let canonical_dir =
crate::input::resolve_directory_argument(dir).map_err(miette::Error::from)?;
let exclude_prefix: Option<PathBuf> = match &output_base {
OutputBase::Dir { canonical: 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 {
crate::output::ewriteln!(
"{} .mds file(s) found but all are under default-excluded directories \
(hidden dirs, node_modules); nothing was built",
walk.excluded_by_default
);
crate::output::exit(1);
}
crate::output::ewriteln!(
"no .mds files found in {}; nothing was built",
crate::output::safe_path(dir)
);
crate::output::exit(1);
}
if let Some(partials_only_count) = crate::output::partials_only(files) {
crate::output::ewriteln!(
"{partials_only_count} .mds file(s) found in {} but all are _-prefixed partials; \
nothing was built",
crate::output::safe_path(dir)
);
crate::output::exit(1);
}
let mut ok_count: usize = 0;
let mut fail_count: usize = 0;
let mut empty_count: usize = 0;
for file in files {
if is_partial(file) {
continue;
}
let base_no_ext = output_base_no_ext(file, dir, &output_base);
let opts = mds::CompileOptions::default()
.with_source_map(source_map)
.with_include_sources_content(embed_sources)
.with_source_map_base(base_no_ext.parent().map(Path::to_path_buf));
let pin = match crate::output::walked_pin(&walk, file, dir, &canonical_dir) {
Ok(pin) => pin,
Err(e) => {
crate::output::eprint_file_failure(e.into());
fail_count += 1;
continue;
}
};
let fs = mds::NativeFs::new().with_entry_pin(pin);
let compiled = crate::output::catch_compile(
file,
AssertUnwindSafe(|| {
compile_native_to_content(fs, file, runtime_vars.clone(), quiet, opts)
}),
);
match compiled {
Ok(Ok(mut compiled)) => {
let ext = compiled.kind.extension();
let inputs = source_inputs(file, &compiled.dependencies, &reads);
let target = output_path_for(file, RootPaths::as_typed(dir), &output_base, ext);
if let Some(ref mut sm) = compiled.source_map {
apply_source_map_file_label(sm, Some(&target.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();
let stale = matches!(output_base, OutputBase::Dir { .. })
.then(|| stale_output(&target, compiled.kind));
let written = match &stale {
Some(stale) => {
write_compiled_and_look(&target, &final_content, &inputs, stale).map(Some)
}
None => write_compiled(&target, &final_content, &inputs).map(|()| None),
};
match written {
Ok(beside) => {
if wrote_empty {
empty_count += 1;
}
if !quiet {
crate::output::ewriteln!(
"Compiled to {}",
crate::output::safe_path(&target.shown)
);
}
if source_map && !inline {
if let Some(ref sm) = compiled.source_map {
let map = target.sibling(map_path_for);
let map_json = sm.to_json();
if let Err(e) = write_compiled(&map, &map_json, &inputs) {
crate::output::eprint_io_failure(e);
fail_count += 1;
continue;
}
if !quiet {
crate::output::ewriteln!(
"Source map written to {}",
crate::output::safe_path(&map.shown)
);
}
}
}
if beside == Some(Beside::Something) {
if let Err(e) = probe_and_remove_stale(&target, compiled.kind, quiet) {
crate::output::eprint_io_failure(e);
}
}
ok_count += 1;
}
Err(e) => {
crate::output::eprint_io_failure(e);
fail_count += 1;
}
}
}
Ok(Err(e)) => {
crate::output::eprint_file_failure(e);
fail_count += 1;
}
Err(crate::output::Panicked) => fail_count += 1,
}
}
if !quiet || fail_count > 0 {
if empty_count > 0 {
crate::output::ewriteln!("{ok_count} built ({empty_count} empty), {fail_count} failed");
} else {
crate::output::ewriteln!("{ok_count} built, {fail_count} failed");
}
}
if fail_count > 0 {
crate::output::exit(1);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn several_mds_files_names_each_file_escaped() {
let (lf, esc) = (char::from(0x0a_u8), char::from(0x1b_u8));
let hostile = format!("x{lf}Built forged{esc}.mds");
assert!(
hostile.contains(lf),
"control: the name carries a raw newline"
);
let entries = [PathBuf::from("b.mds"), PathBuf::from(&hostile)];
let error = several_mds_files("build", &entries);
assert_eq!(
error.to_string(),
format!(
"multiple .mds files found: b.mds, x{}u000ABuilt forged{}u001B.mds",
'\\', '\\'
),
"each name must be shown escaped"
);
let entries = [PathBuf::from("b.mds"), PathBuf::from("a.mds")];
let error = several_mds_files("lint", &entries);
assert_eq!(
error.to_string(),
"multiple .mds files found: a.mds, b.mds",
"control: ordinary names keep their text and their order"
);
assert_eq!(
error.help().map(|help| help.to_string()).as_deref(),
Some("specify which file, e.g. 'mds lint a.mds'"),
"the way out is the help, apart from the message"
);
}
#[test]
fn no_mds_file_keeps_its_hint_apart_from_its_message() {
let error = single_mds_file("build", &[]).expect_err("no file to use");
assert_eq!(
(error.to_string(), error.help().map(|help| help.to_string())),
(
"no .mds files found in current directory".to_owned(),
Some("run 'mds init' to create a starter template".to_owned())
)
);
assert_eq!(
single_mds_file("build", &[PathBuf::from("a.mds")]).unwrap(),
PathBuf::from("a.mds"),
"control: a single file is used"
);
}
#[test]
fn admit_output_refuses_naming_the_entry_as_typed() {
let dir = tempfile::TempDir::new().unwrap();
std::fs::create_dir(dir.path().join("sub")).unwrap();
std::fs::write(dir.path().join("page.md"), "x").unwrap();
let typed = dir.path().join("sub").join("..").join("page.md");
let canonical = dir.path().join("page.md").canonicalize().unwrap();
let entry = EntryPaths {
typed: &typed,
canonical: &canonical,
};
let admit = |output: Option<&Path>| {
admit_output(output, entry, &None, OutputKind::Markdown, true)
.map_err(|e| e.to_string())
};
let refused = admit(Some(&canonical)).unwrap_err();
assert_eq!(
refused,
format!(
"output would overwrite the entry file: \"{}\"; \
write it elsewhere with -o <file> or --out-dir <dir>",
typed.display()
)
);
assert!(
!refused.contains(&*canonical.to_string_lossy()),
"{refused}"
);
assert_eq!(
admit(Some(&dir.path().join("sub").join("..").join("page.md"))),
Err(refused),
"another spelling of the entry is the entry"
);
assert_eq!(admit(Some(&dir.path().join("out.md"))), Ok(()), "control");
assert_eq!(admit(None), Ok(()), "stdout is never the entry");
}
#[test]
fn file_identity_resolves_a_directory_the_write_creates() {
let dir = tempfile::TempDir::new().unwrap();
let root = dir.path().canonicalize().unwrap();
std::fs::create_dir(root.join("sub")).unwrap();
std::fs::write(root.join("page.md"), "x").unwrap();
let page = root.join("page.md");
let case_insensitive = root.join("PAGE.md").exists();
let variant = if case_insensitive {
page.clone()
} else {
root.join("PAGE.md")
};
let rows = [
("page.md", page.clone()),
("sub/../page.md", page.clone()),
("newdir/../page.md", page.clone()),
("a/b/../../page.md", page.clone()),
("sub/new/../../page.md", page.clone()),
("new/./x/../../page.md", page.clone()),
("newdir/page.md", root.join("newdir").join("page.md")),
(
"sub/new/page.md",
root.join("sub").join("new").join("page.md"),
),
("PAGE.md", variant.clone()),
("newdir/../PAGE.md", variant.clone()),
("a/b/../../PAGE.md", variant),
];
let mismatches: Vec<String> = rows
.iter()
.filter_map(|(rel, expected)| {
let got = file_identity(&dir.path().join(rel));
(got.as_ref() != Some(expected)).then(|| format!("{rel}: {got:?}"))
})
.collect();
assert!(mismatches.is_empty(), "{mismatches:#?}");
#[cfg(unix)]
{
std::os::unix::fs::symlink(&root, root.join("lnk")).unwrap();
assert_eq!(
file_identity(&dir.path().join("newdir/../lnk/page.md")),
Some(page.clone())
);
}
assert!(!root.join("newdir").exists() && !root.join("a").exists());
}
#[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(|e| panic!("{label}: the working directory exists: {e}"));
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(EntryPaths::as_typed(Path::new("foo.mds"))),
&Some("-".to_string()),
&None,
&None,
OutputKind::Markdown,
)
.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(EntryPaths::as_typed(Path::new("-"))),
&None,
&None,
&None,
OutputKind::Markdown,
)
.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(EntryPaths::as_typed(Path::new("/some/dir/hello.mds"))),
&None,
&None,
&None,
OutputKind::Markdown,
)
.unwrap();
assert_eq!(
result,
Some(WriteTarget::as_typed(PathBuf::from("/some/dir/hello.md"))),
"default should produce .md next to source"
);
}
#[test]
fn resolve_output_path_default_is_named_beside_the_entry_as_typed() {
let resolve = |typed: &str, out_dir: Option<&str>| {
resolve_output_path_for_kind(
Some(EntryPaths {
typed: Path::new(typed),
canonical: Path::new("/some/dir/hello.mds"),
}),
&None,
&out_dir.map(PathBuf::from),
&None,
OutputKind::Markdown,
)
.unwrap()
};
assert_eq!(
resolve("hello.mds", None),
Some(WriteTarget::below(
Path::new("/some/dir"),
Path::new("."),
Path::new("hello.md")
))
);
assert_eq!(
resolve("sub/../sub/hello.mds", None),
Some(WriteTarget::below(
Path::new("/some/dir"),
Path::new("sub/../sub"),
Path::new("hello.md")
))
);
assert_eq!(
resolve("hello.mds", Some("out")),
Some(WriteTarget::as_typed(PathBuf::from("out/hello.md")))
);
}
#[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(EntryPaths::as_typed(Path::new("-"))),
&None,
&Some(out_dir.clone()),
&None,
OutputKind::Markdown,
)
.unwrap();
assert_eq!(
result,
Some(WriteTarget::as_typed(out_dir.join("output.md"))),
"stdin with --out-dir should produce output.md inside the out dir"
);
assert!(!out_dir.exists(), "resolving creates no directory");
}
fn config_with_output_dir(shown_dir: &str) -> Option<ProjectConfig> {
Some(ProjectConfig {
config: MdsConfig {
build: BuildConfig {
output_dir: Some("build".to_string()),
..Default::default()
},
..Default::default()
},
dir: PathBuf::from("/project"),
shown_dir: PathBuf::from(shown_dir),
})
}
#[test]
fn resolve_output_path_config_output_dir_is_shown_below_the_directory_reached() {
let result = resolve_output_path_for_kind(
Some(EntryPaths::as_typed(Path::new("src/hello.mds"))),
&None,
&None,
&config_with_output_dir("src/.."),
OutputKind::Markdown,
)
.unwrap();
assert_eq!(
result,
Some(WriteTarget::below(
Path::new("/project"),
Path::new("src/.."),
&Path::new("build").join("hello.md")
))
);
}
#[test]
fn resolve_output_path_explicit_o_wins_over_config() {
let config = config_with_output_dir(".");
let result = resolve_output_path_for_kind(
Some(EntryPaths::as_typed(Path::new("/project/hello.mds"))),
&Some("out.md".to_string()),
&None,
&config,
OutputKind::Markdown,
)
.unwrap();
assert_eq!(
result,
Some(WriteTarget::as_typed(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").config;
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}"
);
}
struct Stream {
left: Option<u64>,
served: u64,
}
impl Stream {
fn sized(len: u64) -> Self {
Self {
left: Some(len),
served: 0,
}
}
fn endless() -> Self {
Self {
left: None,
served: 0,
}
}
}
impl Read for Stream {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = buf.len().min(64 * 1024);
let n = self
.left
.map_or(n, |left| n.min(usize::try_from(left).unwrap_or(n)));
buf[..n].fill(b'x');
if let Some(left) = self.left.as_mut() {
*left -= n as u64;
}
self.served += n as u64;
Ok(n)
}
}
#[test]
fn exit_code_maps_internal_failures_to_101() {
let error = MdsError::Internal;
for report in [
miette::Report::new(error.clone()),
crate::output::relabel_stdin_error(&error, ""),
] {
assert_eq!(exit_code(&report), 101);
}
}
#[test]
fn read_stdin_holds_at_most_the_cap_plus_one_byte() {
let at_cap = read_stdin_from(&mut Stream::sized(MAX_FILE_SIZE)).unwrap();
assert_eq!(
at_cap.len() as u64,
MAX_FILE_SIZE,
"exactly the cap is read"
);
assert!(
at_cap.capacity() as u64 <= MAX_FILE_SIZE + 1,
"capacity {} for {MAX_FILE_SIZE} bytes, over the cap plus one byte",
at_cap.capacity()
);
let over_cap = "resource limit exceeded: stdin input exceeds maximum size of 10 MiB";
let over: miette::Report = read_stdin_from(&mut Stream::sized(MAX_FILE_SIZE + 1))
.unwrap_err()
.into();
assert_eq!(
(exit_code(&over), over.to_string()),
(3, over_cap.to_owned())
);
let mut endless = Stream::endless();
let err: miette::Report = read_stdin_from(&mut endless).unwrap_err().into();
assert_eq!((exit_code(&err), err.to_string()), (3, over_cap.to_owned()));
assert_eq!(endless.served, MAX_FILE_SIZE + 1, "read no further");
let err: miette::Report = read_stdin_from(&mut &b"ok \xff"[..]).unwrap_err().into();
assert_eq!(
(exit_code(&err), err.to_string()),
(
2,
"cannot read stdin: stream did not contain valid UTF-8".to_owned()
)
);
let err: miette::Report = read_stdin_from(&mut Unreadable).unwrap_err().into();
assert_eq!(
(exit_code(&err), err.to_string()),
(
2,
format!("cannot read stdin: {}", std::io::ErrorKind::Other)
),
"the error's kind, not the text it carries (#390)"
);
assert_eq!(read_stdin_from(&mut &b"Hello!\n"[..]).unwrap(), "Hello!\n");
}
struct Unreadable;
impl Read for Unreadable {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::other("stream broke"))
}
}
#[test]
fn stale_map_check_reads_only_the_sidecar_head() {
let sidecar = |name: &str| {
let mut sm = mds::compile_str_with_deps_opts(
"Hi\n",
None,
None,
mds::CompileOptions::default().with_source_map(true),
)
.unwrap()
.source_map
.expect("a map was built");
apply_source_map_file_label(&mut sm, Some(Path::new(name)), false);
sm.to_json()
};
let verdict =
|bytes: &str, name: &str| has_sidecar_head(&mut bytes.as_bytes(), name).unwrap();
let mut mismatches = Vec::new();
for name in ["out.md", "a \"quoted\" name.md", "caf\u{e9}.md"] {
if !verdict(&sidecar(name), name) {
mismatches.push(format!("{name}: its own sidecar is not recognised"));
}
}
let rows = [
("another output's sidecar", sidecar("other.md")),
(
"hand-formatted, same fields",
"{ \"version\": 3, \"file\": \"out.md\", \"sources\": [], \"names\": [], \"mappings\": \"\" }".to_owned(),
),
("ends after file", "{\"version\":3,\"file\":\"out.md\"}".to_owned()),
("version 2", "{\"version\":2,\"file\":\"out.md\",\"sources\":[]}".to_owned()),
];
for (label, bytes) in rows {
if verdict(&bytes, "out.md") {
mismatches.push(format!("{label}: recognised as out.md's sidecar"));
}
}
let head = "{\"version\":3,\"file\":\"out.md\",".len() as u64;
let mut large = Stream::sized(64 * 1024 * 1024);
if has_sidecar_head(&mut large, "out.md").unwrap() || large.served > head {
mismatches.push(format!(
"64 MiB of x: read {} bytes; the head is {head}",
large.served
));
}
assert!(mismatches.is_empty(), "{mismatches:#?}");
}
#[cfg(unix)]
#[test]
fn a_stale_map_that_cannot_be_removed_is_an_io_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let map = dir.path().join("out.md.map");
let sidecar = "{\"version\":3,\"file\":\"out.md\",\"sources\":[],\"mappings\":\"\"}";
std::fs::write(&map, sidecar).unwrap();
assert!(
verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true).is_ok()
);
assert!(!map.exists(), "control: the stale sidecar must be removed");
std::fs::write(&map, sidecar).unwrap();
std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap();
let probe = std::fs::write(dir.path().join("probe"), b"");
let result = verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true);
let _ = std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755));
if probe.is_ok() {
crate::output::ewriteln!(
"skipped: a file can be created at mode 0o555 (running as root?)"
);
return;
}
match result {
Err(MdsError::Io { message }) => assert!(
message.starts_with("could not remove stale map "),
"unexpected message: {message}"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
assert!(
map.exists(),
"the sidecar that could not be removed is still there"
);
}
#[cfg(unix)]
#[test]
fn a_stale_map_that_cannot_be_read_is_an_io_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let map = dir.path().join("out.md.map");
std::fs::write(&map, "{\"hand\":\"written\"}").unwrap();
assert!(
verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true).is_ok()
);
assert!(map.exists(), "control: a hand-written map is left in place");
let sidecar = "{\"version\":3,\"file\":\"out.md\",\"sources\":[],\"mappings\":\"\"}";
std::fs::write(&map, sidecar).unwrap();
std::fs::set_permissions(&map, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::File::open(&map).is_ok() {
crate::output::ewriteln!(
"skipped: a file can be read at mode 0o000 (running as root?)"
);
return;
}
let result = verify_then_delete_map(&WriteTarget::as_typed(map.clone()), "out.md", true);
match result {
Err(MdsError::Io { message }) => assert!(
message.starts_with("cannot read stale map ") && message.contains("out.md.map"),
"unexpected message: {message}"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
assert!(map.exists(), "a map that cannot be read is left in place");
}
#[cfg(unix)]
#[test]
fn a_stale_map_is_never_removed_through_a_symlink_below_its_anchor() {
let sidecar = "{\"version\":3,\"file\":\"x.md\",\"sources\":[],\"mappings\":\"\"}";
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
std::fs::create_dir_all(anchor.join("real")).unwrap();
std::fs::create_dir(dir.path().join("victim")).unwrap();
std::os::unix::fs::symlink("../victim", anchor.join("sub")).unwrap();
let victim = dir.path().join("victim/x.md.map");
std::fs::write(&victim, sidecar).unwrap();
let map = WriteTarget::below(&anchor, Path::new("out"), Path::new("sub/x.md.map"));
let result = verify_then_delete_map(&map, "x.md", true);
assert_eq!(
std::fs::read_to_string(&victim).ok().as_deref(),
Some(sidecar),
"nothing is removed through the symlink"
);
match result {
Err(MdsError::Io { message }) => assert_eq!(
message,
"could not remove stale map out/sub/x.md.map: \
refusing to follow a symlink at out/sub"
),
other => panic!("want Err(MdsError::Io {{ .. }}); got {other:?}"),
}
let real = anchor.join("real/x.md.map");
std::fs::write(&real, sidecar).unwrap();
let map = WriteTarget::below(&anchor, Path::new("out"), Path::new("real/x.md.map"));
assert!(verify_then_delete_map(&map, "x.md", true).is_ok());
assert!(!real.exists(), "control: the stale sidecar is removed");
}
}