mdr 0.6.0

A lightweight Markdown viewer with live reload and multiple rendering backends
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
mod backend;
mod core;

use clap::Parser;
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process;
use std::time::{Duration, SystemTime};

#[derive(Parser)]
#[command(
    name = "mdr",
    version,
    about = "Lightweight Markdown viewer with live reload"
)]
struct Cli {
    /// Markdown file to render (use '-' or pipe via stdin)
    file: Option<PathBuf>,

    // Declared in alphabetical order, which is the order clap prints them in;
    // `--help` and `--version` are appended after these by clap itself.
    /// Rendering backend: auto, gui, tui, web
    #[arg(short, long, value_parser = parse_backend)]
    backend: Option<String>,

    /// Path to the config file (must exist; -v prints the one in use)
    #[arg(short, long, value_name = "PATH")]
    config: Option<PathBuf>,

    /// List available backends and exit
    #[arg(short, long)]
    list_backends: bool,

    /// Never access the network: remote images are not downloaded
    #[arg(long)]
    offline: bool,

    /// Write the backend to use into the config file and exit
    #[arg(short, long, value_name = "BACKEND", value_parser = parse_backend)]
    set_default_backend: Option<String>,

    /// Colour scheme to render with: auto, dark, light
    #[arg(short, long, value_name = "THEME", value_parser = parse_theme)]
    theme: Option<String>,

    /// Enable verbose logging (image resolution, mermaid rendering, etc.)
    #[arg(short, long)]
    verbose: bool,
}

/// Whether this binary was built with the backend `name` (`auto` always is).
fn backend_is_compiled(name: &str) -> bool {
    // Written as a chain rather than a `match`: every arm is a `cfg!`, which
    // collapses to a literal per build, and in an all-features build they all
    // collapse to `true` — which is exactly when clippy mistakes this for a
    // `matches!`. It is not one: in a single-backend build the arms differ.
    if name == "auto" {
        return true;
    }
    if name == "gui" {
        return cfg!(feature = "egui-backend");
    }
    if name == "tui" {
        return cfg!(feature = "tui-backend");
    }
    if name == "web" {
        return cfg!(feature = "webview-backend");
    }
    false
}

/// The Cargo feature that builds the backend `name`.
fn backend_feature(name: &str) -> &'static str {
    match name {
        "gui" => "egui-backend",
        "tui" => "tui-backend",
        "web" => "webview-backend",
        _ => "",
    }
}

fn print_backends() {
    fn status(compiled: bool) -> &'static str {
        if compiled {
            "✓ compiled"
        } else {
            "✗ not compiled"
        }
    }
    eprintln!("Available backends:");
    eprintln!(
        "  gui       Native window (OpenGL)                [{}]",
        status(backend_is_compiled("gui"))
    );
    eprintln!(
        "  tui       Terminal UI with image support        [{}]",
        status(backend_is_compiled("tui"))
    );
    eprintln!(
        "  web       System webview (WebKit/WebView2)      [{}]",
        status(backend_is_compiled("web"))
    );
    eprintln!("  auto      Auto-detect best available (default)");
}

fn parse_theme(s: &str) -> Result<String, String> {
    match core::Theme::parse(s) {
        Some(_) => Ok(s.to_string()),
        None => Err(format!(
            "unknown theme '{s}', expected 'auto', 'dark' or 'light'"
        )),
    }
}

fn parse_backend(s: &str) -> Result<String, String> {
    if core::config::is_valid_backend(s) {
        Ok(s.to_string())
    } else {
        Err(format!(
            "unknown backend '{s}', expected one of: {}",
            core::config::BACKENDS.join(", ")
        ))
    }
}

/// Auto-detect the best backend for the current environment.
fn detect_backend() -> &'static str {
    // SSH session → tui. Otherwise a display → gui, or web when gui is not
    // compiled in. No display and no SSH → tui as well.
    //
    // Whether stdin is a terminal is not part of it: mdr reads a document, not
    // the console, and a piped document is one of the ordinary ways to use it.
    let is_ssh = std::env::var("SSH_CONNECTION").is_ok() || std::env::var("SSH_TTY").is_ok();
    let has_display = std::env::var("DISPLAY").is_ok()
        || std::env::var("WAYLAND_DISPLAY").is_ok()
        || cfg!(target_os = "macos")
        || cfg!(target_os = "windows");

    if is_ssh {
        #[cfg(feature = "tui-backend")]
        return "tui";
    }

    if has_display {
        #[cfg(feature = "egui-backend")]
        return "gui";
        #[cfg(all(not(feature = "egui-backend"), feature = "webview-backend"))]
        return "web";
    }

    #[cfg(feature = "tui-backend")]
    return "tui";

    #[cfg(not(feature = "tui-backend"))]
    {
        #[cfg(feature = "egui-backend")]
        return "gui";
        #[cfg(all(not(feature = "egui-backend"), feature = "webview-backend"))]
        return "web";
        #[cfg(not(any(feature = "egui-backend", feature = "webview-backend")))]
        {
            eprintln!("Error: no backend compiled");
            process::exit(1);
        }
    }
}

/// Temp files left by runs that could not clean up after themselves (SIGKILL)
/// are removed once they are older than this.
const STALE_TMP_AGE: Duration = Duration::from_secs(24 * 60 * 60);

/// Directory holding the temp files created for piped input.
fn stdin_tmp_dir() -> PathBuf {
    std::env::temp_dir().join("mdr")
}

/// Create `dir` with owner-only permissions. If it already exists, refuse
/// anything that is not a plain directory we own — in a shared /tmp it could be
/// a symlink planted by another user.
#[cfg(unix)]
fn ensure_tmp_dir(dir: &Path) -> io::Result<()> {
    use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};

    match std::fs::DirBuilder::new().mode(0o700).create(dir) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
            // symlink_metadata: a symlink here must be rejected, not followed.
            let meta = std::fs::symlink_metadata(dir)?;
            if !meta.is_dir() {
                return Err(io::Error::new(
                    io::ErrorKind::AlreadyExists,
                    "exists and is not a directory",
                ));
            }
            if meta.uid() != unsafe { libc::getuid() } {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "is owned by another user",
                ));
            }
            if meta.permissions().mode() & 0o077 != 0 {
                let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
            }
            Ok(())
        }
        Err(e) => Err(e),
    }
}

#[cfg(not(unix))]
fn ensure_tmp_dir(dir: &Path) -> io::Result<()> {
    std::fs::create_dir_all(dir)
}

/// A per-run, hard-to-guess name so two instances never collide, even if the
/// system recycles a pid.
fn stdin_tmp_name() -> String {
    use std::hash::{BuildHasher, Hasher, RandomState};
    let rand = RandomState::new().build_hasher().finish();
    format!("stdin-{}-{:016x}.md", process::id(), rand)
}

/// Write `content` to a fresh file in `dir`, created readable by its owner only
/// (the mode is set at creation: the content is never world-readable).
fn write_stdin_tmp_file(dir: &Path, content: &str) -> io::Result<PathBuf> {
    let path = dir.join(stdin_tmp_name());
    let mut opts = std::fs::OpenOptions::new();
    opts.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    let mut file = opts.open(&path)?;
    file.write_all(content.as_bytes())?;
    Ok(path)
}

/// Best-effort housekeeping: drop stdin temp files older than [`STALE_TMP_AGE`].
/// Never reports an error — it must not keep mdr from starting.
fn cleanup_stale_tmp_files(dir: &Path) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    let now = SystemTime::now();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        if !name.starts_with("stdin-") || !name.ends_with(".md") {
            continue;
        }
        let path = entry.path();
        let Ok(meta) = std::fs::symlink_metadata(&path) else {
            continue;
        };
        if !meta.is_file() {
            continue;
        }
        let Ok(modified) = meta.modified() else {
            continue;
        };
        if now
            .duration_since(modified)
            .is_ok_and(|age| age >= STALE_TMP_AGE)
        {
            let _ = std::fs::remove_file(&path);
        }
    }
}

/// Read stdin and write it to a temp file, returning its path. The file is
/// deleted when mdr exits (see [`main`]); backends keep watching it until then.
fn read_stdin_to_tmpfile() -> Result<PathBuf, String> {
    let mut content = String::new();
    io::stdin()
        .lock()
        .read_to_string(&mut content)
        .map_err(|e| format!("failed to read from stdin: {e}"))?;

    let dir = stdin_tmp_dir();
    ensure_tmp_dir(&dir)
        .map_err(|e| format!("failed to create temp directory '{}': {}", dir.display(), e))?;
    cleanup_stale_tmp_files(&dir);

    let path = write_stdin_tmp_file(&dir, &content)
        .map_err(|e| format!("failed to write temp file in '{}': {}", dir.display(), e))?;
    crate::vlog!("piped input stored in {}", path.display());
    Ok(path)
}

fn main() {
    let mut tmp_file: Option<PathBuf> = None;
    let code = run(&mut tmp_file);
    // process::exit() below runs no destructor, so the temp file holding piped
    // input is removed here, explicitly, whatever the exit code.
    if let Some(path) = &tmp_file {
        let _ = std::fs::remove_file(path);
    }
    process::exit(code);
}

/// Body of `main`, returning the process exit code so that the caller can clean
/// up before exiting.
fn run(tmp_file: &mut Option<PathBuf>) -> i32 {
    let cli = Cli::parse();

    if cli.list_backends {
        print_backends();
        return 0;
    }

    // Load config. An explicit `--config` must exist — a typo in a path the user
    // just typed is a mistake, not an invitation to create a file there. The
    // default path is created on first run instead, so the settings are
    // discoverable without a flag to run first.
    let (default_path, may_create) = if cli.config.is_none() {
        let (path, confident) = core::config::default_location();
        (Some(path), confident)
    } else {
        (None, false)
    };
    let cfg_path = cli.config.clone().or(default_path).unwrap_or_default();
    let mut created_config = false;
    if may_create {
        match core::config::ensure_exists(&cfg_path) {
            // Verbosity is not known yet — it partly comes from the very file
            // being created — so the log waits until `set_verbose` below.
            Ok(true) => created_config = true,
            Ok(false) => {}
            // Not being able to write it costs nothing at this point: mdr runs
            // on its defaults, which is what the file would have said anyway.
            Err(e) => eprintln!(
                "mdr: warning: could not create '{}': {e}",
                cfg_path.display()
            ),
        }
    }
    if let Some(backend) = &cli.set_default_backend {
        // Writing a backend this binary cannot run would produce a config that
        // fails on the next start, which is not what "set the default" means.
        if !backend_is_compiled(backend) {
            eprintln!(
                "Error: {backend} backend not compiled. Rebuild with --features {}",
                backend_feature(backend)
            );
            return 1;
        }
        if !cfg_path.exists() {
            eprintln!("Error: config file '{}' not found", cfg_path.display());
            return 1;
        }
        return match core::config::set_backend(&cfg_path, backend) {
            Ok(()) => {
                eprintln!("Set backend to {backend} in {}", cfg_path.display());
                0
            }
            Err(e) => {
                eprintln!("Error: {e}");
                1
            }
        };
    }

    let cfg = if cli.config.is_some() && !cfg_path.exists() {
        eprintln!("Error: config file '{}' not found", cfg_path.display());
        return 1;
    } else {
        core::config::load(&cfg_path).unwrap_or_else(|e| {
            eprintln!("mdr: config error ({}): {}", cfg_path.display(), e);
            core::config::Config::default()
        })
    };

    core::set_verbose(cli.verbose || cfg.verbose.unwrap_or(false));
    if created_config {
        vlog!("created config file: {}", cfg_path.display());
    } else if cfg_path.exists() {
        vlog!("config file: {}", cfg_path.display());
    } else {
        vlog!("no config file at {}", cfg_path.display());
    }
    core::set_offline(cli.offline || cfg.offline.unwrap_or(false));
    core::set_theme(
        cli.theme
            .as_deref()
            .or(cfg.theme.as_deref())
            .and_then(core::Theme::parse)
            .unwrap_or_default(),
    );

    let from_stdin = |tmp_file: &mut Option<PathBuf>| match read_stdin_to_tmpfile() {
        Ok(path) => {
            // The document is now a temp file, but its relative image paths
            // were written against the directory mdr was run from.
            if let Ok(cwd) = std::env::current_dir() {
                core::set_document_base(cwd);
            }
            *tmp_file = Some(path.clone());
            Ok(path)
        }
        Err(e) => {
            eprintln!("Error: {e}");
            Err(1)
        }
    };

    let file = match cli.file {
        Some(f) if f.as_os_str() == "-" => match from_stdin(tmp_file) {
            Ok(path) => path,
            Err(code) => return code,
        },
        Some(f) => {
            if !f.exists() {
                eprintln!("Error: file '{}' not found", f.display());
                return 1;
            }
            f
        }
        None => {
            if io::stdin().is_terminal() {
                eprintln!("Error: missing required argument <FILE>");
                eprintln!("Usage: mdr <FILE> [OPTIONS]");
                eprintln!("       cat file.md | mdr [OPTIONS]");
                eprintln!("Try 'mdr --help' for more information.");
                return 1;
            }
            match from_stdin(tmp_file) {
                Ok(path) => path,
                Err(code) => return code,
            }
        }
    };

    let backend_str = cli
        .backend
        .or(cfg.backend)
        .unwrap_or_else(|| "auto".to_string());
    let backend = if backend_str == "auto" {
        detect_backend()
    } else {
        backend_str.as_str()
    };

    let result = match backend {
        #[cfg(feature = "egui-backend")]
        "gui" => backend::egui::run(file),

        #[cfg(not(feature = "egui-backend"))]
        "gui" => {
            eprintln!("Error: gui backend not compiled. Rebuild with --features egui-backend");
            return 1;
        }

        #[cfg(feature = "webview-backend")]
        "web" => backend::webview::run(file),

        #[cfg(not(feature = "webview-backend"))]
        "web" => {
            eprintln!("Error: web backend not compiled. Rebuild with --features webview-backend");
            return 1;
        }

        #[cfg(feature = "tui-backend")]
        "tui" => backend::tui::run(file),

        #[cfg(not(feature = "tui-backend"))]
        "tui" => {
            eprintln!("Error: tui backend not compiled. Rebuild with --features tui-backend");
            return 1;
        }

        // Both sources of a backend name are validated against
        // `core::config::BACKENDS`, so this is unreachable in practice — but a
        // belt-and-braces arm beats aborting the process if that ever slips.
        // `return 1` rather than `process::exit`, so `main` still removes the
        // temporary file a piped document was written to.
        other => {
            eprintln!("Error: unknown backend '{other}'");
            return 1;
        }
    };

    if let Err(e) = result {
        eprintln!("Error: {e}");
        return 1;
    }
    0
}

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

    #[test]
    fn every_backend_name_maps_to_a_cargo_feature() {
        // `backend_feature` returning "" would make the "not compiled" error
        // read "Rebuild with --features " — so adding a backend to `BACKENDS`
        // without teaching that table has to fail here.
        for name in core::config::BACKENDS {
            if *name == "auto" {
                continue;
            }
            assert!(
                !backend_feature(name).is_empty(),
                "backend '{name}' has no Cargo feature"
            );
        }
    }

    #[test]
    fn the_help_lists_every_value_the_parsers_accept() {
        // Per argument, not across the whole help text: `auto` belongs to both
        // `--backend` and `--theme`, so searching the rendered help as one
        // string would let either of them hide the other's omission.
        use clap::CommandFactory;
        let command = Cli::command();
        let help_for = |long: &str| {
            command
                .get_arguments()
                .find(|a| a.get_long() == Some(long))
                .unwrap_or_else(|| panic!("no --{long} argument"))
                .get_help()
                .map(ToString::to_string)
                .unwrap_or_default()
        };

        let backend_help = help_for("backend");
        for backend in core::config::BACKENDS {
            assert!(
                backend_help.contains(backend),
                "--backend accepts '{backend}' but its help does not say so: {backend_help}"
            );
        }
        let set_default_help = help_for("set-default-backend");
        assert!(
            !set_default_help.is_empty(),
            "--set-default-backend should describe itself"
        );

        let theme_help = help_for("theme");
        for theme in ["auto", "dark", "light"] {
            assert!(
                core::Theme::parse(theme).is_some(),
                "'{theme}' should be a theme"
            );
            assert!(
                theme_help.contains(theme),
                "--theme accepts '{theme}' but its help does not say so: {theme_help}"
            );
        }
    }

    #[test]
    fn every_long_option_has_its_short_form() {
        // The short forms are the documented spelling in the man page, so a
        // rename that drops one has to fail here rather than in someone's shell.
        let long = Cli::try_parse_from(["mdr", "--theme", "light", "--config", "c.kdl", "f.md"])
            .expect("long forms parse");
        let short = Cli::try_parse_from(["mdr", "-t", "light", "-c", "c.kdl", "f.md"])
            .expect("short forms parse");
        assert_eq!(long.theme, short.theme);
        assert_eq!(long.config, short.config);

        assert!(Cli::try_parse_from(["mdr", "-l"]).unwrap().list_backends);
        assert_eq!(
            Cli::try_parse_from(["mdr", "-s", "tui"])
                .unwrap()
                .set_default_backend
                .as_deref(),
            Some("tui")
        );
        assert_eq!(
            Cli::try_parse_from(["mdr", "-b", "web", "f.md"])
                .unwrap()
                .backend
                .as_deref(),
            Some("web")
        );
        assert!(Cli::try_parse_from(["mdr", "-v", "f.md"]).unwrap().verbose);
    }

    #[test]
    fn cli_parses_and_validates_the_theme_flag() {
        let cli = Cli::try_parse_from(["mdr", "--theme", "light", "f.md"]).unwrap();
        assert_eq!(cli.theme.as_deref(), Some("light"));
        assert!(Cli::try_parse_from(["mdr", "--theme", "neon", "f.md"]).is_err());
        assert!(
            Cli::try_parse_from(["mdr", "f.md"])
                .unwrap()
                .theme
                .is_none()
        );
    }

    #[test]
    fn cli_parses_offline_flag() {
        let cli = Cli::try_parse_from(["mdr", "--offline", "file.md"]).unwrap();
        assert!(cli.offline);

        let cli = Cli::try_parse_from(["mdr", "file.md"]).unwrap();
        assert!(!cli.offline);
    }

    #[test]
    fn write_stdin_tmp_file_writes_content_under_a_unique_name() {
        let dir = tempfile::tempdir().unwrap();
        let a = write_stdin_tmp_file(dir.path(), "# piped\n").unwrap();
        let b = write_stdin_tmp_file(dir.path(), "# piped\n").unwrap();

        assert_ne!(a, b, "two runs must not collide on the same file name");
        assert_eq!(std::fs::read_to_string(&a).unwrap(), "# piped\n");

        let name = a.file_name().unwrap().to_string_lossy().into_owned();
        assert!(name.starts_with(&format!("stdin-{}-", process::id())));
        assert!(name.ends_with(".md"));
    }

    #[cfg(unix)]
    #[test]
    fn write_stdin_tmp_file_creates_owner_only_file() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = write_stdin_tmp_file(dir.path(), "secret").unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    #[cfg(unix)]
    #[test]
    fn ensure_tmp_dir_creates_an_owner_only_directory() {
        use std::os::unix::fs::PermissionsExt;

        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("mdr");
        ensure_tmp_dir(&dir).unwrap();
        let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "expected 0700, got {mode:o}");
    }

    #[cfg(unix)]
    #[test]
    fn ensure_tmp_dir_tightens_a_loose_existing_directory() {
        use std::os::unix::fs::PermissionsExt;

        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("mdr");
        std::fs::create_dir(&dir).unwrap();
        std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o777)).unwrap();

        ensure_tmp_dir(&dir).unwrap();
        let mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o700, "expected 0700, got {mode:o}");
    }

    #[cfg(unix)]
    #[test]
    fn ensure_tmp_dir_refuses_a_symlink() {
        let base = tempfile::tempdir().unwrap();
        let target = base.path().join("elsewhere");
        std::fs::create_dir(&target).unwrap();
        let dir = base.path().join("mdr");
        std::os::unix::fs::symlink(&target, &dir).unwrap();

        assert!(
            ensure_tmp_dir(&dir).is_err(),
            "a symlinked temp directory must be refused, not followed"
        );
    }

    #[test]
    fn ensure_tmp_dir_refuses_a_regular_file() {
        let base = tempfile::tempdir().unwrap();
        let dir = base.path().join("mdr");
        std::fs::write(&dir, "not a directory").unwrap();

        assert!(ensure_tmp_dir(&dir).is_err());
    }

    #[test]
    fn cleanup_stale_tmp_files_only_removes_old_stdin_files() {
        let dir = tempfile::tempdir().unwrap();
        let old = SystemTime::now() - Duration::from_secs(48 * 3600);

        let write_aged = |name: &str, aged: bool| {
            let path = dir.path().join(name);
            std::fs::write(&path, "x").unwrap();
            if aged {
                std::fs::File::options()
                    .write(true)
                    .open(&path)
                    .unwrap()
                    .set_modified(old)
                    .unwrap();
            }
            path
        };

        let stale = write_aged("stdin-1-deadbeef.md", true);
        let fresh = write_aged("stdin-2-cafebabe.md", false);
        let unrelated = write_aged("notes.md", true);
        let other_ext = write_aged("stdin-3.txt", true);

        cleanup_stale_tmp_files(dir.path());

        assert!(!stale.exists(), "old stdin temp files must be removed");
        assert!(fresh.exists(), "recent stdin temp files must be kept");
        assert!(unrelated.exists(), "other files must never be touched");
        assert!(other_ext.exists(), "other files must never be touched");
    }

    #[test]
    fn cleanup_stale_tmp_files_ignores_a_missing_directory() {
        cleanup_stale_tmp_files(Path::new("/nonexistent/mdr-no-such-dir"));
    }
}