use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use clap::{Args, Parser, Subcommand};
use mdlit_core::{
Diagnostic, DiagnosticCode, Document, LanguageOutput, LitError, MdlitConfig,
MdlitConfigBuilder, Severity, emit_diagnostic_to_stderr, emit_error_to_stderr, parse_document,
plan_all_outputs, validate_document,
};
#[derive(Parser, Debug)]
#[command(
name = "mdlit",
about = "Literate programming tool for Markdown",
long_about = "mdlit validates and emits source code from Markdown documents with embedded code blocks.\n\nLanguages are inferred from named blocks. With one language, generated source is written to stdout. With multiple languages or -o, one file per language is written using canonical suffixes (e.g. .py, .rs). Diagnostics go to stderr.",
version
)]
struct Cli {
#[arg(
long = "list-warnings",
help = "List warning diagnostic codes and exit",
long_help = "List all warning diagnostic codes with their codes and descriptions, then exit cleanly."
)]
list_warnings: bool,
#[arg(
long = "list-diagnostics",
help = "List all diagnostic codes and exit",
long_help = "List all diagnostic codes (errors and warnings) with their codes, default severities, and descriptions, then exit cleanly."
)]
list_diagnostics: bool,
#[arg(
long = "explain",
value_name = "CODE",
help = "Explain a diagnostic code and exit",
long_help = "Show an in-depth explanation, architectural rationale, code example, and remediation for a diagnostic code, then exit."
)]
explain: Option<String>,
#[command(subcommand)]
command: Option<Commands>,
}
#[derive(Subcommand, Debug)]
enum Commands {
#[command(
about = "Validate a Markdown document without emitting source",
long_about = "Parse the document and validate every named block and reference, detecting duplicate IDs, missing targets, cycles, malformed syntax, ambiguous roots, and invalid single-use references."
)]
Check(DocumentArgs),
#[command(
about = "Emit source code from a Markdown document",
long_about = "Infer language-specific output streams or aggregate streams, expand macros, validate include-once references, and write source to stdout or files."
)]
Emit(EmitArgs),
#[command(
about = "Explain a diagnostic code and remediation steps",
long_about = "Print the architectural rationale, erroneous Markdown example, and remediation instructions for a diagnostic code."
)]
Explain(ExplainArgs),
}
#[derive(Args, Debug)]
struct ExplainArgs {
#[arg(
value_name = "CODE",
help = "Diagnostic code or name (e.g. MDLIT003 or duplicate-id)"
)]
code: String,
}
#[derive(Args, Debug, Clone)]
struct DocumentArgs {
#[arg(value_name = "FILE", help = "Markdown document to process")]
path: String,
#[arg(
long = "deny-warnings",
help = "Treat warnings as errors",
long_help = "Treat all warnings as fatal errors and return a non-zero exit status."
)]
deny_warnings: bool,
#[arg(
long = "no-diagnostic-spans",
help = "Omit source code excerpts and caret spans from diagnostics",
long_help = "Omit source code excerpts and caret spans from diagnostics, producing concise single-line locations."
)]
no_diagnostic_spans: bool,
}
#[derive(Args, Debug)]
struct EmitArgs {
#[command(flatten)]
document: DocumentArgs,
#[arg(
short = 'o',
long = "output",
num_args = 0..=1,
default_missing_value = "",
value_name = "BASENAME",
help = "Write output to file(s) with canonical language suffixes",
long_help = "Write output to file(s) with canonical language suffixes (e.g. .py, .rs). If BASENAME is omitted, uses the Markdown file stem."
)]
output: Option<String>,
}
impl From<&DocumentArgs> for MdlitConfigBuilder {
fn from(args: &DocumentArgs) -> Self {
let mut builder = MdlitConfig::builder();
if args.deny_warnings {
builder = builder.deny_warnings(true);
}
if args.no_diagnostic_spans {
builder = builder.diagnostic_spans(false);
}
builder
}
}
impl From<&DocumentArgs> for MdlitConfig {
fn from(args: &DocumentArgs) -> Self {
MdlitConfigBuilder::from(args).build()
}
}
impl From<&EmitArgs> for MdlitConfig {
fn from(args: &EmitArgs) -> Self {
let mut builder = MdlitConfigBuilder::from(&args.document);
if let Some(ref out) = args.output {
builder = builder.output(out);
}
builder.build()
}
}
fn load_document(path: &str, cli_config: MdlitConfig) -> Result<Document, CliError> {
let source = read_source(path).map_err(CliError::message)?;
let mut document = parse_document(path, &source)
.map_err(|e| CliError::diagnostic(e, cli_config.show_spans()))?;
document.config.merge(cli_config);
Ok(document)
}
enum CliError {
Diagnostic(LitError, bool),
Message(String),
}
impl CliError {
fn diagnostic(error: LitError, show_spans: bool) -> Self {
Self::Diagnostic(error, show_spans)
}
fn message(msg: impl Into<String>) -> Self {
Self::Message(msg.into())
}
}
fn main() -> ExitCode {
match run(env::args().collect()) {
Ok(status) => status,
Err(cli_err) => {
match cli_err {
CliError::Diagnostic(error, show_spans) => {
emit_error_to_stderr(&error, show_spans);
}
CliError::Message(msg) => {
eprintln!("{msg}");
}
}
ExitCode::from(1)
}
}
}
fn run(arguments: Vec<String>) -> Result<ExitCode, CliError> {
let cli = match Cli::try_parse_from(&arguments) {
Ok(cli) => cli,
Err(err) => {
if err.kind() == clap::error::ErrorKind::DisplayHelp
|| err.kind() == clap::error::ErrorKind::DisplayVersion
{
print!("{err}");
return Ok(ExitCode::SUCCESS);
}
let msg = err.to_string();
let formatted = if err.kind() == clap::error::ErrorKind::InvalidSubcommand {
format!("error: unknown command\n\n{msg}")
} else {
msg
};
return Err(CliError::message(formatted));
}
};
if cli.list_warnings {
print_warnings_list();
return Ok(ExitCode::SUCCESS);
}
if cli.list_diagnostics {
print_diagnostics_list();
return Ok(ExitCode::SUCCESS);
}
if let Some(ref code) = cli.explain {
return handle_explain(code);
}
let Some(command) = cli.command else {
return Err(usage_error("missing command"));
};
match command {
Commands::Explain(args) => handle_explain(&args.code),
Commands::Check(args) => {
let document = load_document(&args.path, (&args).into())?;
let report = validate_document(&document)
.map_err(|e| CliError::diagnostic(e, document.config.show_spans()))?;
handle_warnings(&report.warnings, &document.config)?;
Ok(ExitCode::SUCCESS)
}
Commands::Emit(args) => {
let document = load_document(&args.document.path, (&args).into())?;
let show_spans = document.config.show_spans();
let outputs =
plan_all_outputs(&document).map_err(|e| CliError::diagnostic(e, show_spans))?;
if outputs.is_empty() {
return Err(CliError::diagnostic(
LitError::from_diagnostic(Diagnostic::without_location(
Severity::Error,
DiagnosticCode::NoOutput,
"document has no named blocks to emit",
)),
show_spans,
));
}
if document.config.output().is_none() && outputs.len() > 1 {
let langs: Vec<_> = outputs.iter().map(|o| o.language.as_str()).collect();
return Err(CliError::diagnostic(
LitError::from_diagnostic(Diagnostic::without_location(
Severity::Error,
DiagnosticCode::MultipleOutputs,
format!(
"document contains multiple languages ({}); use -o to write one file per language",
langs.join(", ")
),
)),
show_spans,
));
}
let all_warnings: Vec<Diagnostic> = outputs
.iter()
.flat_map(|output| output.warnings.iter().cloned())
.collect();
handle_warnings(&all_warnings, &document.config)?;
if let Some(output_dest) = document.config.output() {
write_outputs(&args.document.path, output_dest, &outputs)
} else {
print!("{}", outputs[0].source);
Ok(ExitCode::SUCCESS)
}
}
}
}
fn handle_warnings(warnings: &[Diagnostic], config: &MdlitConfig) -> Result<(), CliError> {
let show_spans = config.show_spans();
if config.should_deny_warnings() && !warnings.is_empty() {
return Err(CliError::diagnostic(
warnings_as_errors(warnings),
show_spans,
));
}
print_warnings(warnings, show_spans);
Ok(())
}
fn write_outputs(
doc_path: &str,
output_dest: &str,
outputs: &[LanguageOutput],
) -> Result<ExitCode, CliError> {
if outputs.len() == 1
&& !output_dest.is_empty()
&& (output_dest.ends_with(&outputs[0].suffix)
|| Path::new(output_dest).extension().is_some())
{
let out_path = PathBuf::from(output_dest);
if let Some(parent) = out_path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
{
let _ = fs::create_dir_all(parent);
}
fs::write(&out_path, &outputs[0].source).map_err(|error| {
CliError::message(format!(
"error: could not write `{}`: {error}",
out_path.display()
))
})?;
} else {
let base_path = if output_dest.is_empty() {
Path::new(doc_path).with_extension("")
} else {
Path::new(output_dest).to_path_buf()
};
let parent = base_path.parent();
let stem = base_path
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("output");
for output in outputs {
let filename = format!("{}{}", stem, output.suffix);
let out_path = if let Some(dir) = parent {
if dir.as_os_str().is_empty() {
PathBuf::from(&filename)
} else {
dir.join(&filename)
}
} else {
PathBuf::from(&filename)
};
if let Some(parent) = out_path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
{
let _ = fs::create_dir_all(parent);
}
fs::write(&out_path, &output.source).map_err(|error| {
CliError::message(format!(
"error: could not write `{}`: {error}",
out_path.display()
))
})?;
}
}
Ok(ExitCode::SUCCESS)
}
fn handle_explain(query: &str) -> Result<ExitCode, CliError> {
let Some(code) = find_diagnostic_by_name_or_code(query) else {
return Err(CliError::message(format!(
"error: unknown diagnostic code '{query}'. Use --list-diagnostics to see available codes."
)));
};
print!("{}", code.explain());
Ok(ExitCode::SUCCESS)
}
fn find_diagnostic_by_name_or_code(query: &str) -> Option<DiagnosticCode> {
let trimmed = query.trim();
if trimmed.is_empty() {
return None;
}
for &code in DiagnosticCode::ALL {
if code.as_str().eq_ignore_ascii_case(trimmed) {
return Some(code);
}
}
let normalized = trimmed.to_ascii_lowercase();
let num_str = normalized.strip_prefix("mdlit").unwrap_or(&normalized);
if let Ok(num) = num_str.parse::<usize>() {
for &code in DiagnosticCode::ALL {
let code_num_str = code.as_str().strip_prefix("MDLIT").unwrap_or("");
if code_num_str.parse::<usize>().ok() == Some(num) {
return Some(code);
}
}
}
let name_query = normalized.replace(['-', '_', ' '], "");
for &code in DiagnosticCode::ALL {
let variant_name = format!("{:?}", code).to_ascii_lowercase();
if variant_name == name_query {
return Some(code);
}
}
None
}
fn print_warnings_list() {
println!("Warning diagnostic codes:");
for code in DiagnosticCode::ALL {
if code.is_warning() {
println!(" {}: {}", code.as_str(), code.description());
}
}
}
fn print_diagnostics_list() {
println!("Diagnostic codes:");
for code in DiagnosticCode::ALL {
let severity = if code.is_warning() {
"warning"
} else {
"error"
};
println!(" {} [{severity}]: {}", code.as_str(), code.description());
}
}
fn warnings_as_errors(warnings: &[Diagnostic]) -> LitError {
let diagnostics = warnings
.iter()
.cloned()
.map(|mut warning| {
warning.severity = Severity::Error;
warning.message = format!("warning denied: {}", warning.message);
warning
})
.collect();
LitError::new(diagnostics)
}
fn read_source(path: &str) -> Result<String, String> {
fs::read_to_string(path).map_err(|error| format!("error: could not read `{path}`: {error}"))
}
fn print_warnings(warnings: &[Diagnostic], show_spans: bool) {
for warning in warnings {
emit_diagnostic_to_stderr(warning, show_spans);
}
}
fn usage_error(message: &str) -> CliError {
CliError::message(format!("error: {message}\n\n{}", usage()))
}
fn usage() -> &'static str {
"Usage:\n mdlit check FILE [--deny-warnings]\n mdlit emit FILE [-o [BASENAME]] [--deny-warnings]\n mdlit explain CODE\n\nThe CLI validates and emits source from Markdown. Languages are inferred from\nnamed blocks. With one language, generated source is written to stdout. With\nmultiple languages or -o, one file per language is written using canonical\nsuffixes (e.g. .py, .rs). Diagnostics go to stderr."
}