mdlit-cli 0.1.0

Command-line interface for mdlit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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())
    {
        // Exact filename destination for single output stream
        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;
    }

    // Direct match against all codes (e.g. "MDLIT003", "mdlit003", "MDLIT101")
    for &code in DiagnosticCode::ALL {
        if code.as_str().eq_ignore_ascii_case(trimmed) {
            return Some(code);
        }
    }

    // Match numeric portion: e.g. "3", "003", "mdlit003", "MDLIT3", "101", "103"
    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);
            }
        }
    }

    // Match by enum name: e.g. "duplicate-id", "duplicate_id", "DuplicateId"
    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."
}