mds-cli 0.5.1

MDS (Markdown Script) compiler — command-line interface
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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! `fmt` subcommand — opinionated, safety-gated auto-formatter (issue #60).
//!
//! Dispatches on the resolved input: `-` (stdin, base_dir = None, formats to
//! stdout as a filter), a directory (recurses, INCLUDING partials — formatting
//! rewrites source, unlike build/check which skip partials because they don't
//! emit their own compiled output), or a single file (base_dir = the file's
//! parent, matching how imports resolve for that file when compiled normally).
//!
//! # Channel discipline
//!
//! - Plain filter-mode formatted content (stdin, no flags) and `--diff` output
//!   go to STDOUT.
//! - All status lines, summaries, and errors go to STDERR.
//! - `--quiet` suppresses status/summaries but never errors (AC-CF-8).
//!
//! # Exit codes (reuses the existing `exit_code` mapping — no new codes)
//!
//! - 0: formatted OK / nothing to change / diff preview
//! - 1: `--check` found something that would change (after printing the
//!   summary), OR a format/parse error (`MdsError` non-io, including
//!   `FormatterInvariant`) via `Err` -> `exit_code`
//! - 2: file not found / not `.mds` / I/O / bad UTF-8 — a rewrite or a stdout write
//!   that fails included, in directory mode too, where one such file makes the run
//!   exit 2 (#157); a closed stdout is not a failure. So is a rewrite that lands in a
//!   directory it cannot then sync (#160): given the file, the failed sync is reported in
//!   place of its `Formatted:` line, which is shown only for a rewrite that is durable; a
//!   directory run — which syncs each directory once, after the last of its files, and
//!   shows their `Formatted:` lines only then — reports the failed sync in place of each
//!   such file's `Formatted:` line, and counts it formatted
//! - 3: oversized source (in directory mode, a failed file that leaves the run at 1)

use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};

use mds::effective_parent;
use miette::Result;

use crate::build::{ensure_existing_mds_file, load_config, read_stdin, resolve_input};
use crate::output::{
    catch_compile, collect_mds_files_detailed, render_unified_diff, safe_path, stdout_failure,
    walked_pin, write_stdout, Panicked, RootPaths, StdoutOutcome, WriteTarget,
};
use crate::write::{
    read_stamped, replace_if_unchanged, replace_owing_sync, DirectorySyncs, Durability, Renamed,
    Rewritten, Synced,
};

pub(crate) struct FmtArgs {
    pub(crate) input: Option<PathBuf>,
    pub(crate) check: bool,
    pub(crate) diff: bool,
    pub(crate) quiet: bool,
}

/// Bundled mode flags passed to every per-input helper — avoids the silent
/// transposition hazard of three consecutive positional `bool` parameters.
#[derive(Clone, Copy)]
struct FmtFlags {
    check: bool,
    diff: bool,
    quiet: bool,
}

pub(crate) fn run_fmt(args: FmtArgs) -> Result<()> {
    let FmtArgs {
        input,
        check,
        diff,
        quiet,
    } = args;

    let (input, auto_detected) = resolve_input(input, "fmt")?;
    if auto_detected && !quiet {
        crate::output::ewriteln!("Formatting {}", crate::output::safe_path(&input));
    }

    let flags = FmtFlags { check, diff, quiet };

    if input == Path::new("-") {
        return run_fmt_stdin(flags);
    }

    if input.is_dir() {
        // #413: the one directory-argument check every directory-mode subcommand makes
        // (a symlink, the filesystem root, a forbidden character — all `mds::io`).
        let canonical =
            crate::input::resolve_directory_argument(&input).map_err(miette::Error::from)?;
        return run_fmt_directory(&input, &canonical, flags);
    }

    ensure_existing_mds_file(&input).map_err(miette::Error::from)?;
    run_fmt_file(&input, flags)
}

/// Read the raw source of `path` for formatting: symlink-checked, size-capped,
/// UTF-8-validated (PF-004 parity with `read_stdin` and the resolver).
///
/// `mds fmt` needs the RAW, unparsed source text (not a compiled result), so it
/// can't go through `mds::compile*`. It shares `mds lint`'s reader, so the two
/// subcommands report an unreadable, symlinked or undecodable path identically —
/// as an `MdsError`, which `exit_code` maps to exit 2 (#217).
fn read_source_file(path: &Path, pin: Option<mds::EntryPin>) -> Result<String> {
    crate::lint::read_source_file(path, pin).map_err(miette::Error::from)
}

/// The result of formatting one file's content: whether it changed, and the
/// formatted string. Callers apply mode-specific policy (write-if-changed,
/// `--check` tally, `--diff` rendering) on top of this.
struct FmtResult {
    formatted: String,
    changed: bool,
}

/// Format `source` and return a [`FmtResult`] with change detection.
///
/// `file_name` is threaded into lexer and safety-gate errors so diagnostics
/// name the file rather than showing a blank path.
fn format_source_named(
    source: &str,
    base_dir: Option<&Path>,
    file_name: &str,
) -> Result<FmtResult> {
    let formatted =
        mds::format_str_named(source, base_dir, file_name).map_err(miette::Error::from)?;
    let changed = formatted != source;
    Ok(FmtResult { formatted, changed })
}

// ── stdin mode ───────────────────────────────────────────────────────────────

fn run_fmt_stdin(flags: FmtFlags) -> Result<()> {
    use crate::output::STDIN_DISPLAY_LABEL;

    let FmtFlags { check, diff, quiet } = flags;
    let source = read_stdin()?;
    // AD-211-3: one definition of the stdin sentinel, shared with lint/check/build.
    // `None` is the working directory, shown as "." (see `read_stdin`).
    let result = format_source_named(&source, None, STDIN_DISPLAY_LABEL)?;

    // A closed stdout is not an error here: the reader is gone, and the verdict below
    // still stands (#157).
    if diff {
        let rendered = render_unified_diff(&source, &result.formatted, STDIN_DISPLAY_LABEL);
        write_stdout(rendered.as_bytes()).into_batch_result()?;
    } else if !check {
        // Plain filter mode: formatted content is the output.
        write_stdout(result.formatted.as_bytes()).into_batch_result()?;
    }

    if check && result.changed {
        if !quiet {
            crate::output::ewriteln!("Would reformat: {STDIN_DISPLAY_LABEL}");
        }
        crate::output::exit(1);
    }
    Ok(())
}

// ── single-file mode ─────────────────────────────────────────────────────────

fn run_fmt_file(path: &Path, flags: FmtFlags) -> Result<()> {
    let FmtFlags { check, diff, quiet } = flags;
    let source = read_source_file(path, None)?;
    // effective_parent maps "" (bare filename) to "." so that resolve_base_dir
    // (called by format_str_named → assert_equivalent) receives a canonicalisable
    // path and does not silently fall through to the structural_equivalent fallback
    // that would swallow a genuine mds::syntax error. avoids PF-006, applies ADR-001.
    let base_dir = Some(effective_parent(path));
    // The label of its error frames and of its `--diff` header (#390).
    let file_name = safe_path(path);
    let result = format_source_named(&source, base_dir, &file_name)?;

    if diff && result.changed {
        let rendered = render_unified_diff(&source, &result.formatted, &file_name);
        write_stdout(rendered.as_bytes()).into_batch_result()?;
    }

    let read_only = check || diff;
    if !read_only {
        if result.changed {
            // Replace-by-rename preserves file permissions and avoids truncate-then-write
            // data loss on crash or full disk — the same helpers as lint --fix. A file
            // argument is anchored at its typed parent, read again there and replaced only
            // if it still holds the bytes formatted, in the directory it was read in
            // (#160).
            let read = read_stamped(&WriteTarget::as_typed(path.to_path_buf()), &source)?;
            // The file holds the rewrite either way; `Formatted:` says it is durable, so
            // a directory that could not then be synced is the run's failure, reported in
            // its place (exit 2).
            match replace_if_unchanged(read, &result.formatted, Durability::Fsync)? {
                Rewritten::Done => {
                    if !quiet {
                        crate::output::ewriteln!("Formatted: {}", crate::output::safe_path(path));
                    }
                }
                Rewritten::NotSynced(e) => return Err(e.into()),
            }
        } else if !quiet {
            crate::output::ewriteln!("Unchanged: {}", crate::output::safe_path(path));
        }
        return Ok(());
    }

    if check {
        if result.changed {
            if !quiet {
                crate::output::ewriteln!("Would reformat: {}", crate::output::safe_path(path));
            }
            crate::output::exit(1);
        }
        if !quiet {
            crate::output::ewriteln!("Unchanged: {}", crate::output::safe_path(path));
        }
    }
    Ok(())
}

// ── directory mode ───────────────────────────────────────────────────────────

/// Outcome of formatting a single file in directory mode; tallied by the caller.
enum FileOutcome {
    /// Normal mode: the file was reformatted and written; the sync of its directory, and
    /// its `Formatted:` line, are owed (#160).
    Formatted(Renamed),
    /// Normal mode: the file was already formatted (no write needed).
    Unchanged,
    /// `--check` / `--diff` mode: the file would change.
    WouldChange,
    /// `--check` / `--diff` mode: the file is already formatted.
    NoChange,
    /// Any per-file error (read, format, diff-output, or write), or a panic in the
    /// formatter, which the panic hook reported (#389).
    Failed,
}

/// Format one file in directory mode: read → format → (optional) diff → (optional) write.
///
/// Every per-file error line is printed here as a side effect, so the directory loop
/// only needs to tally the returned [`FileOutcome`] — and show the `Formatted:` line of
/// a rewrite once its directory is synced.
///
/// A diff-output failure other than a closed stdout, and a rewrite that fails, are
/// returned as [`FileOutcome::Failed`] and counted in `fail_count` — consistent with how
/// read and format errors are treated in the surrounding loop — and recorded as I/O
/// failures, so the run exits at least 2; so is a read or format error in the I/O and
/// file-system class, and one over a resource limit is recorded as such, so the run exits
/// 3 (`crate::output::eprint_file_failure`). A failing stdout is reported once per failure episode — the first
/// failed write since the run began or since a write last landed; every file whose diff
/// it lost counts as failed. A closed stdout is not a failure: the diff has no reader,
/// and the file's outcome stands (#157). A rewrite that lands is
/// [`FileOutcome::Formatted`], whose directory's sync — and with it the file's
/// `Formatted:` line — the run makes later ([`run_fmt_directory`], #160).
///
/// `file` is the walk's path, below the directory argument as typed: the label of its
/// error frames and of its `--diff` header, as a file argument typed that way is named
/// (#390). Its rewrite is anchored at `root`, the directory argument, so a directory
/// between the two that turned into a symlink after the walk is refused (#160).
fn format_one_file(
    root: &Path,
    file: &Path,
    pin: Result<mds::EntryPin>,
    flags: FmtFlags,
) -> FileOutcome {
    let FmtFlags { check, diff, .. } = flags;
    let file_name = safe_path(file);
    let source = match pin.and_then(|pin| read_source_file(file, Some(pin))) {
        Ok(s) => s,
        Err(e) => {
            // File path is embedded in the miette report; sanitize for ESC injection safety
            // (avoids PF-004 parallel-path gap — uses the shared render helper).
            crate::output::eprint_file_failure(e);
            return FileOutcome::Failed;
        }
    };
    // effective_parent maps "" (bare filename) to "." — avoids PF-006, applies ADR-001.
    let base_dir = Some(effective_parent(file));
    // A panic in the formatter fails this file alone, and the batch goes on (#389).
    let formatted = catch_compile(
        file,
        AssertUnwindSafe(|| format_source_named(&source, base_dir, &file_name)),
    );
    let result = match formatted {
        Ok(Ok(r)) => r,
        Ok(Err(e)) => {
            // MdsError::Syntax embeds user-controlled source fragments that may contain
            // raw ESC bytes; file_name is threaded into the report by format_source_named.
            crate::output::eprint_file_failure(e);
            return FileOutcome::Failed;
        }
        // The panic hook reported it, and the run will exit 101.
        Err(Panicked) => return FileOutcome::Failed,
    };

    if diff && result.changed {
        let rendered = render_unified_diff(&source, &result.formatted, &file_name);
        match write_stdout(rendered.as_bytes()) {
            StdoutOutcome::Written | StdoutOutcome::Closed => {}
            StdoutOutcome::Failed(e) => {
                crate::output::eprint_io_failure(stdout_failure(&e));
                return FileOutcome::Failed;
            }
            StdoutOutcome::FailedAgain => return FileOutcome::Failed,
        }
    }

    let read_only = check || diff;
    if read_only {
        if result.changed {
            FileOutcome::WouldChange
        } else {
            FileOutcome::NoChange
        }
    } else if !result.changed {
        FileOutcome::Unchanged
    } else {
        // Replace-by-rename preserves file permissions and avoids truncate-then-write
        // data loss on crash or full disk — the same helpers as lint --fix — and writes
        // only over the bytes formatted, in the directory they were read in (#160).
        let target = WriteTarget::walked_below(RootPaths::as_typed(root), file);
        match read_stamped(&target, &source)
            .and_then(|read| replace_owing_sync(read, &result.formatted))
        {
            Ok(renamed) => FileOutcome::Formatted(renamed),
            Err(e) => {
                crate::output::eprint_io_failure(e);
                FileOutcome::Failed
            }
        }
    }
}

/// Format every `.mds` file under `dir`, INCLUDING `_`-prefixed partials.
///
/// Deliberate divergence from `run_build_directory` / `run_check_directory`:
/// `is_partial` governs output EMISSION (a partial produces no standalone
/// compiled file), but formatting rewrites SOURCE, and a partial's source is
/// just as much a candidate for reformatting as any other file.
///
/// Continue-on-error: a per-file failure does not abort the run. Non-zero
/// exit when any file failed, or (under `--check`) when any file would change; 2 when an
/// I/O or file-system failure was recorded (#157).
fn run_fmt_directory(dir: &Path, canonical_dir: &Path, flags: FmtFlags) -> Result<()> {
    // Directory recursion depth cap, matching `run_build_directory` /
    // `run_check_directory` which also declare MAX_DEPTH as a function-local
    // constant.
    const MAX_DEPTH: usize = 64;

    // Validate mds.json even though `fmt` doesn't act on its `fmt` section's
    // content yet — consistent with build, lint and watch, which also fail loudly
    // on a malformed config rather than silently ignoring it.
    let _ = load_config(dir)?;

    let walk = collect_mds_files_detailed(dir, MAX_DEPTH, None);
    let files = &walk.files;

    if files.is_empty() {
        if walk.excluded_by_default > 0 {
            // Always emit — not suppressed by --quiet (avoids silent CI green pass).
            crate::output::ewriteln!(
                "{} .mds file(s) found but all are under default-excluded directories \
                 (hidden dirs, node_modules); nothing was formatted",
                walk.excluded_by_default
            );
            crate::output::exit(1);
        }
        // #204: an empty tree is "nothing to format", not success (mirrors build.rs).
        // Emitted even under --quiet and exit 1.  This arm sits BEFORE the `read_only`
        // split below, so `--check` and `--diff` behave identically on an empty tree.
        crate::output::ewriteln!(
            "no .mds files found in {}; nothing was formatted",
            crate::output::safe_path(dir)
        );
        crate::output::exit(1);
    }

    let read_only = flags.check || flags.diff;
    let mut changed_count: usize = 0;
    let mut unchanged_count: usize = 0;
    let mut fail_count: usize = 0;

    // Each directory a rewrite lands in is synced once, after the last file of the walk
    // in it, and only then are its rewrites' `Formatted:` lines shown (#160).
    let mut syncs = DirectorySyncs::new(files.iter().map(PathBuf::as_path));
    for (place, file) in files.iter().enumerate() {
        let pin = walked_pin(&walk, file, dir, canonical_dir).map_err(miette::Error::from);
        let landed = match format_one_file(dir, file, pin, flags) {
            FileOutcome::Formatted(renamed) => {
                changed_count += 1;
                syncs.landed(place, renamed, file.as_path())
            }
            FileOutcome::WouldChange => {
                changed_count += 1;
                None
            }
            FileOutcome::Unchanged | FileOutcome::NoChange => {
                unchanged_count += 1;
                None
            }
            FileOutcome::Failed => {
                fail_count += 1;
                None
            }
        };
        for synced in landed.into_iter().flatten() {
            show_synced(synced, flags.quiet);
        }
        for synced in syncs.past(place).into_iter().flatten() {
            show_synced(synced, flags.quiet);
        }
    }

    if read_only {
        // The `changed_count > 0` disjunct was deliberately removed: --quiet
        // suppresses status/summaries (including "N would reformat"), never
        // errors. Only fail_count > 0 forces a summary under --quiet, matching
        // the non-read_only branch's `!quiet || fail_count > 0` contract and
        // the single-file --check path (which is fully silent under --quiet,
        // exiting 1 with no message when a file would change).
        if !flags.quiet || fail_count > 0 {
            crate::output::ewriteln!(
                "{changed_count} would reformat, {unchanged_count} unchanged, {fail_count} failed"
            );
        }
    } else if !flags.quiet || fail_count > 0 {
        crate::output::ewriteln!(
            "{changed_count} formatted, {unchanged_count} unchanged, {fail_count} failed"
        );
    }

    if fail_count > 0 || (flags.check && changed_count > 0) {
        crate::output::exit(1);
    }
    Ok(())
}

/// Show a directory run's rewrite of `file` once its directory's sync is made (#160):
/// `Formatted:` when it was synced, not under `--quiet`; otherwise, in its place, the
/// failed sync, recorded as an I/O failure (exit 2). Either way the file holds the
/// rewrite, and counts as formatted.
fn show_synced(synced: Synced<&Path>, quiet: bool) {
    match synced {
        Synced::Durable(file) => {
            if !quiet {
                crate::output::ewriteln!("Formatted: {}", crate::output::safe_path(file));
            }
        }
        Synced::NotSynced(_, e) => crate::output::eprint_io_failure(e),
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use mds::MdsError;

    #[test]
    fn ensure_existing_mds_file_accepts_existing_mds() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("foo.mds");
        std::fs::write(&p, "").unwrap();
        assert!(
            ensure_existing_mds_file(&p).is_ok(),
            "existing .mds file must pass"
        );
    }

    #[test]
    fn ensure_existing_mds_file_rejects_non_mds_extension() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("foo.txt");
        std::fs::write(&p, "").unwrap();
        let err = ensure_existing_mds_file(&p).expect_err("existing .txt file must be rejected");
        // Extension error (not existence error).
        assert!(
            matches!(err, MdsError::NotMdsFile { .. }),
            "error must be NotMdsFile for existing .txt; got: {err:?}"
        );
    }

    #[test]
    fn ensure_existing_mds_file_rejects_missing_path() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("nonexistent.mds");
        let err = ensure_existing_mds_file(&p).expect_err("nonexistent file must be rejected");
        // Existence error (not extension error) — even though extension is .mds.
        assert!(
            matches!(err, MdsError::FileNotFound { .. }),
            "error must be FileNotFound for missing path; got: {err:?}"
        );
    }

    #[test]
    fn ensure_existing_mds_file_missing_non_mds_reports_not_found() {
        // Non-existent path with wrong extension must still report FileNotFound (C4/F6):
        // existence is checked before extension.
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("nonexistent.txt");
        let err = ensure_existing_mds_file(&p).expect_err("nonexistent .txt file must be rejected");
        assert!(
            matches!(err, MdsError::FileNotFound { .. }),
            "must be FileNotFound (not NotMdsFile) for non-existent path; got: {err:?}"
        );
    }

    #[test]
    fn format_source_detects_no_change() {
        let result = format_source_named("Hello!\n", None, "<source>").unwrap();
        assert!(!result.changed);
        assert_eq!(result.formatted, "Hello!\n");
    }

    #[test]
    fn format_source_detects_change() {
        let result =
            format_source_named("Hello!\r\n\r\n\r\n\r\nBye.\r\n", None, "<source>").unwrap();
        assert!(result.changed);
        assert!(!result.formatted.contains('\r'));
    }

    /// A directory run syncs each directory its rewrites landed in once, after the run is
    /// past its last file there, not once for each rewrite (#160): three files reformatted
    /// in `src` are one sync, and `src/sub`, with a rewrite of its own, one more — four
    /// rewrites, two syncs — and each file holds its rewrite. Control: the same four files
    /// given one at a time are a sync each.
    #[cfg(unix)]
    #[test]
    fn a_directory_run_syncs_each_directory_once() {
        use crate::write::sync_probe::directory_syncs;

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().canonicalize().unwrap();
        let src = root.join("src");
        std::fs::create_dir_all(src.join("sub")).unwrap();
        let files = ["a.mds", "b.mds", "sub/c.mds", "z.mds"].map(|file| src.join(file));
        let unformatted = || {
            for file in &files {
                std::fs::write(file, "Alpha\r\n").unwrap();
            }
        };
        let flags = FmtFlags {
            check: false,
            diff: false,
            quiet: true,
        };

        unformatted();
        let before = directory_syncs();
        run_fmt_directory(&src, &src, flags).unwrap();
        assert_eq!(
            directory_syncs() - before,
            2,
            "one sync for src and one for src/sub"
        );
        for file in &files {
            assert_eq!(
                std::fs::read_to_string(file).unwrap(),
                "Alpha\n",
                "{file:?}"
            );
        }

        unformatted();
        let before = directory_syncs();
        for file in &files {
            run_fmt_file(file, flags).unwrap();
        }
        assert_eq!(
            directory_syncs() - before,
            files.len(),
            "control: a file argument's rewrite syncs its directory itself"
        );
    }
}