mdo-cli 0.6.1

A simple Rust CLI to convert Markdown to HTML5 (styled with simple.css), with optional file watching
Documentation
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

#[cfg(unix)]
use std::time::{Duration, Instant};

#[cfg(target_os = "linux")]
use std::hash::{Hash, Hasher};
#[cfg(target_os = "linux")]
use std::os::unix::fs::{symlink, PermissionsExt};

fn fixture_dir(name: &str) -> PathBuf {
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system time should be after Unix epoch")
        .as_nanos();
    let dir = std::env::temp_dir().join(format!("mdo-test-{name}-{}-{stamp}", std::process::id()));
    fs::create_dir_all(&dir).expect("failed to create temp fixture dir");
    dir
}

#[test]
fn setup_prints_new_user_path_without_prompt_when_piped() {
    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--setup")
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Welcome to mdo."));
    assert!(stdout.contains("mdo --open notes.md"));
    if cfg!(any(target_os = "linux", target_os = "windows")) {
        assert!(stdout.contains("mdo --install-file-manager"));
    } else {
        assert!(stdout.contains("does not have a built-in mdo installer yet"));
    }
    assert!(!stdout.contains("Install Open as HTML file-manager integration now?"));
}

#[test]
fn no_args_prints_short_landing_page_and_succeeds() {
    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Open Markdown as HTML."));
    assert!(stdout.contains("mdo FILE.md"));
    assert!(stdout.contains("mdo --setup"));
    assert!(stdout.contains("mdo --help"));
    assert!(!stdout.contains("--unsafe-html"));
    assert!(output.stderr.is_empty());
}

#[test]
fn help_prints_full_cli_reference() {
    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--help")
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo --help failed: {output:?}");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout
        .lines()
        .any(|line| line.starts_with("Usage: mdo") && line.ends_with("[OPTIONS] [INPUT]")));
    assert!(stdout.contains("--setup"));
    assert!(stdout.contains("--unsafe-html"));
}

#[test]
fn converts_markdown_to_styled_html5_document() {
    let dir = fixture_dir("html5");
    let input = dir.join("sample.md");
    fs::write(
        &input,
        "# Sample Title\n\nA paragraph with **strong** text.\n\n| A | B |\n|---|---|\n| 1 | 2 |\n",
    )
    .expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(dir.join("sample.html"))
        .expect("failed to read html output")
        .replace("\r\n", "\n");
    assert!(html.contains("<!DOCTYPE html>"));
    assert!(html.contains("<title>Sample Title</title>"));
    assert!(html.contains("<h1>Sample Title</h1>"));
    assert!(html.contains("<strong>strong</strong>"));
    assert!(html.contains("<table>"));
    assert!(html.contains("#theme-toggle"));
    assert!(html.contains(r#"id="mdo-default-typography""#));
    assert!(html.contains("body {\n  font-size: 1rem;"));
    assert!(html.contains("h1 {\n  font-size: 2.4rem;"));
    assert!(html.contains("h2 {\n  font-size: 2rem;"));
    assert!(html.contains("h3 {\n  font-size: 1.4rem;"));
    assert!(html.contains(&format!(
        "<meta name=\"generator\" content=\"mdo {}\">",
        env!("CARGO_PKG_VERSION")
    )));

    // v0.6 quiet output: provenance lives only in <meta name="generator">.
    // No visible branding, homepage link, version, or render timing.
    assert!(!html.contains("Generated by"));
    assert!(!html.contains(env!("CARGO_PKG_HOMEPAGE")));
    assert_eq!(
        html.matches(env!("CARGO_PKG_VERSION")).count(),
        1,
        "mdo version should appear only in the generator meta tag"
    );

    // Source freshness: the source file's modification time, with a
    // machine-readable datetime attribute.
    assert!(html.contains("<footer class=\"mdo-source-meta\">Source modified: <time datetime=\""));
    assert!(html.contains("</time></footer>"));

    // Theme toggle is still present and carries an accessible label.
    assert!(html.contains("aria-label"));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn theme_toggle_manual_flag_survives_storage_write_failure() {
    // Regression test for a review finding on the theme toggle: the script
    // must track "the user made an explicit choice" with an in-memory flag,
    // not solely by re-reading localStorage. Otherwise, on pages where
    // localStorage.setItem throws (e.g. file:// pages in some browsers), a
    // later prefers-color-scheme change would silently overwrite the user's
    // manual click.
    let dir = fixture_dir("theme-manual-flag");
    let input = dir.join("sample.md");
    fs::write(&input, "# Sample Title\n\nBody text.\n").expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(dir.join("sample.html"))
        .expect("failed to read html output")
        .replace("\r\n", "\n");

    let manual_init_pos = html
        .find("var manual=saved!==null;")
        .expect("script should initialize an in-memory manual-choice flag from saved state");

    let click_set_pos = html
        .find("manual=true;")
        .expect("click handler should set the manual flag unconditionally");
    let click_try_pos = html
        .find("try{localStorage.setItem('theme',next)}catch(e){}")
        .expect("click handler should still attempt to persist the choice");
    assert!(
        click_set_pos < click_try_pos,
        "manual flag must be set before the (possibly failing) localStorage write, so a \
         persistence failure can never suppress the in-memory record of an explicit choice"
    );

    let mq_change_pos = html
        .find("mq.addEventListener('change'")
        .expect("script should still track OS theme changes live");
    assert!(
        mq_change_pos > manual_init_pos,
        "manual flag should be declared before it is referenced by the media-query handler"
    );
    assert!(
        html[mq_change_pos..].contains("if(!manual){"),
        "prefers-color-scheme handler must gate on the in-memory manual flag, not a fresh \
         localStorage read, so a failed setItem() can't cause it to override an explicit choice"
    );
    assert!(
        !html[mq_change_pos..].contains("if(!read())"),
        "prefers-color-scheme handler should not fall back to re-reading localStorage to decide \
         whether the user already made a manual choice"
    );

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn css_override_is_embedded_after_default_styles() {
    let dir = fixture_dir("css-override");
    let input = dir.join("sample.md");
    let css = dir.join("override.css");
    let output_path = dir.join("sample.html");
    fs::write(&input, "# Sample Title\n\nA paragraph.\n")
        .expect("failed to write markdown fixture");
    fs::write(
        &css,
        "h1 { font-size: 1.75rem; }\nh2 { font-size: 1.35rem; }\n",
    )
    .expect("failed to write css fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--css")
        .arg(&css)
        .arg("--output")
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    let theme_pos = html
        .find("#theme-toggle")
        .expect("styled output should contain theme toggle CSS");
    let default_pos = html
        .find("id=\"mdo-default-typography\"")
        .expect("styled output should contain default mdo typography block");
    let override_pos = html
        .find("id=\"mdo-css-override\"")
        .expect("styled output should contain CSS override block");

    assert!(
        default_pos > theme_pos,
        "default mdo typography should be appended after built-in styles"
    );
    assert!(
        override_pos > default_pos,
        "custom CSS should be appended after mdo defaults"
    );
    assert!(html.contains("h1 { font-size: 1.75rem; }"));
    assert!(html.contains("h2 { font-size: 1.35rem; }"));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn bundled_restore_simple_css_can_restore_vendored_typography() {
    let dir = fixture_dir("restore-simple-css");
    let input = dir.join("sample.md");
    let output_path = dir.join("sample.html");
    let restore_css = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("assets")
        .join("restore-simple-css.css");
    fs::write(&input, "# Sample Title\n\nA paragraph.\n")
        .expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--css")
        .arg(&restore_css)
        .arg("--output")
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    let default_pos = html
        .find("id=\"mdo-default-typography\"")
        .expect("styled output should contain default mdo typography block");
    let override_pos = html
        .find("id=\"mdo-css-override\"")
        .expect("styled output should contain CSS override block");

    assert!(
        override_pos > default_pos,
        "restore CSS should be appended after mdo defaults"
    );
    assert!(html.contains("font-size: 1.15rem;"));
    assert!(html.contains("font-size: 3rem;"));
    assert!(html.contains("font-size: 2.6rem;"));
    assert!(html.contains("font-size: 2rem;"));
    assert!(html.contains("@media only screen and (width <= 720px)"));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn css_override_cannot_be_combined_with_bare_output() {
    let dir = fixture_dir("css-override-bare");
    let input = dir.join("sample.md");
    let css = dir.join("override.css");
    fs::write(&input, "# Sample Title\n").expect("failed to write markdown fixture");
    fs::write(&css, "h1 { font-size: 1.75rem; }\n").expect("failed to write css fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--bare")
        .arg("--css")
        .arg(&css)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(!output.status.success(), "mdo unexpectedly succeeded");
    assert_eq!(output.status.code(), Some(2));

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("--css cannot be combined with --bare"));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn bare_output_omits_document_shell() {
    let dir = fixture_dir("bare");
    let input = dir.join("fragment.md");
    let output_path = dir.join("fragment.html");
    fs::write(&input, "**bare** fragment").expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .args(["--bare", "--output"])
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    assert!(html.contains("<p><strong>bare</strong> fragment</p>"));
    assert!(!html.contains("<!DOCTYPE html>"));
    assert!(!html.contains("<html"));
    assert!(!html.contains("<style>"));
    assert!(!html.contains("name=\"generator\""));
    assert!(!html.contains("Generated by"));
    assert!(!html.contains("Source modified"));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn sanitizes_active_html_by_default() {
    let dir = fixture_dir("sanitize");
    let input = dir.join("payload.md");
    let output_path = dir.join("payload.html");
    fs::write(
        &input,
        "# Payload\n\n<script>window.__mdo_xss=1</script>\n\n<img src=x onerror=\"window.__mdo_img=1\">\n",
    )
    .expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .args(["--bare", "--output"])
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    assert!(html.contains("<h1>Payload</h1>"));
    assert!(!html.contains("<script>"));
    assert!(!html.contains("window.__mdo_xss"));
    assert!(!html.contains("onerror"));
    assert!(html.contains("<img src=\"x\">"));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn unsafe_html_preserves_raw_html() {
    let dir = fixture_dir("unsafe-html");
    let input = dir.join("payload.md");
    let output_path = dir.join("payload.html");
    fs::write(
        &input,
        "# Payload\n\n<script>window.__mdo_xss=1</script>\n\n<img src=x onerror=\"window.__mdo_img=1\">\n",
    )
    .expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .args(["--unsafe-html", "--bare", "--output"])
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    assert!(html.contains("<script>window.__mdo_xss=1</script>"));
    assert!(html.contains("onerror=\"window.__mdo_img=1\""));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn sanitizer_keeps_markdown_task_list_checkboxes() {
    let dir = fixture_dir("task-list");
    let input = dir.join("tasks.md");
    let output_path = dir.join("tasks.html");
    fs::write(&input, "- [ ] unchecked\n- [x] checked\n")
        .expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .args(["--bare", "--output"])
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    assert!(html.contains(r#"<input type="checkbox" disabled="">"#));
    assert!(html.contains(r#"<input type="checkbox" checked="" disabled="">"#));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn sanitizer_keeps_markdown_footnote_links() {
    let dir = fixture_dir("footnotes");
    let input = dir.join("notes.md");
    let output_path = dir.join("notes.html");
    fs::write(&input, "A footnote ref[^1].\n\n[^1]: Footnote text.\n")
        .expect("failed to write markdown fixture");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .args(["--bare", "--output"])
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let html = fs::read_to_string(output_path).expect("failed to read html output");
    assert!(html.contains(r#"class="footnote-reference""#));
    assert!(html.contains(r##"href="#1""##));
    assert!(html.contains(r#"class="footnote-definition""#));
    assert!(html.contains(r#"id="1""#));

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn verbose_html_is_byte_identical_and_diagnostics_go_to_stderr() {
    let dir = fixture_dir("verbose");
    let input = dir.join("sample.md");
    let quiet_out = dir.join("quiet.html");
    let verbose_out = dir.join("verbose.html");
    fs::write(
        &input,
        "# Sample Title\n\nA paragraph with **strong** text.\n\n- [ ] a task\n",
    )
    .expect("failed to write markdown fixture");

    let quiet = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--output")
        .arg(&quiet_out)
        .arg(&input)
        .output()
        .expect("failed to run mdo");
    assert!(quiet.status.success(), "mdo failed: {quiet:?}");
    assert!(
        quiet.stderr.is_empty(),
        "a successful non-verbose run should write nothing to stderr: {quiet:?}"
    );

    let verbose = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--verbose")
        .arg("--output")
        .arg(&verbose_out)
        .arg(&input)
        .output()
        .expect("failed to run mdo");
    assert!(
        verbose.status.success(),
        "mdo --verbose failed: {verbose:?}"
    );

    // The generated HTML must be byte-identical with and without --verbose:
    // timing diagnostics may never leak into the document.
    let quiet_html = fs::read(&quiet_out).expect("failed to read quiet html output");
    let verbose_html = fs::read(&verbose_out).expect("failed to read verbose html output");
    assert_eq!(
        quiet_html, verbose_html,
        "--verbose must not change the generated HTML"
    );
    assert!(!String::from_utf8_lossy(&verbose_html).contains("Render workflow"));

    // Diagnostics go to stderr, covering the whole workflow stage by stage.
    let stderr = String::from_utf8_lossy(&verbose.stderr);
    assert!(
        stderr.contains("Render workflow"),
        "stderr should carry the timing report: {stderr}"
    );
    for stage in ["read", "markdown", "sanitize", "assemble", "write", "total"] {
        assert!(
            stderr.contains(stage),
            "stderr should report the {stage} stage: {stderr}"
        );
    }
    assert!(stderr.contains(" ms"), "timings should be in ms: {stderr}");

    // Stdout stays brief: the usual success line, no timing report.
    let stdout = String::from_utf8_lossy(&verbose.stdout);
    assert!(stdout.contains("Converted"));
    assert!(
        !stdout.contains("Render workflow") && !stdout.contains("total"),
        "timing diagnostics must not appear on stdout: {stdout}"
    );

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[test]
fn verbose_cannot_be_combined_with_setup() {
    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .args(["--setup", "--verbose"])
        .output()
        .expect("failed to run mdo");

    assert!(!output.status.success(), "mdo unexpectedly succeeded");
    assert_eq!(output.status.code(), Some(2));

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("--setup cannot be combined"));
}

#[cfg(target_os = "linux")]
#[test]
fn normal_output_respects_umask_for_new_files() {
    let dir = fixture_dir("normal-permissions");
    let input = dir.join("sample.md");
    let output_path = dir.join("sample.html");
    fs::write(&input, "# Permissions\n").expect("failed to write markdown fixture");

    let output = Command::new("sh")
        .arg("-c")
        .arg("umask 022; exec \"$@\"")
        .arg("mdo-test-sh")
        .arg(env!("CARGO_BIN_EXE_mdo"))
        .arg("--output")
        .arg(&output_path)
        .arg(&input)
        .output()
        .expect("failed to run mdo through shell");

    assert!(output.status.success(), "mdo failed: {output:?}");

    let mode = fs::metadata(&output_path)
        .expect("failed to stat html output")
        .permissions()
        .mode()
        & 0o777;
    assert_eq!(mode, 0o644);

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[cfg(target_os = "linux")]
#[test]
fn open_output_refuses_precreated_symlink() {
    let dir = fixture_dir("open-symlink");
    let input = dir.join("sample.md");
    let target = dir.join("target.txt");
    fs::write(&input, "# Safe\n\nreplacement").expect("failed to write markdown fixture");
    fs::write(&target, "do not overwrite").expect("failed to write symlink target");

    let output_path = temp_output_for_test(&input);
    fs::create_dir_all(
        output_path
            .parent()
            .expect("temp output should have a parent"),
    )
    .expect("failed to create temp output parent");
    symlink(&target, &output_path).expect("failed to create temp output symlink");

    let fake_bin = dir.join("bin");
    fs::create_dir_all(&fake_bin).expect("failed to create fake bin dir");
    let fake_xdg_open = fake_bin.join("xdg-open");
    fs::write(&fake_xdg_open, "#!/bin/sh\nexit 0\n").expect("failed to write fake xdg-open");
    fs::set_permissions(&fake_xdg_open, fs::Permissions::from_mode(0o700))
        .expect("failed to chmod fake xdg-open");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--open")
        .arg(&input)
        .env("PATH", &fake_bin)
        .output()
        .expect("failed to run mdo");

    // Refusing the pre-created symlink means nothing was rendered, so mdo now
    // exits non-zero (so scripts/pipelines can detect it). The safe no-op is
    // still enforced by the assertions below.
    assert!(
        !output.status.success(),
        "mdo should exit non-zero when it refuses the symlinked output: {output:?}"
    );
    let target_contents = fs::read_to_string(&target).expect("failed to read symlink target");
    assert_eq!(target_contents, "do not overwrite");
    assert!(
        fs::symlink_metadata(&output_path)
            .expect("failed to stat temp output")
            .file_type()
            .is_symlink(),
        "temp output symlink should not have been replaced"
    );

    fs::remove_file(&output_path).expect("failed to remove temp output symlink");
    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[cfg(target_os = "linux")]
fn temp_output_for_test(input: &std::path::Path) -> PathBuf {
    let canonical = fs::canonicalize(input).unwrap_or_else(|_| input.to_path_buf());
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    canonical.hash(&mut hasher);
    let hash = hasher.finish();

    let stem = input
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("document");

    std::env::temp_dir()
        .join(format!("mdo-{}", unsafe { libc::geteuid() }))
        .join(format!("{hash:016x}"))
        .join(format!("{stem}.html"))
}

/// An empty directory suitable for use as `PATH` when a test needs to make
/// sure no desktop opener (xdg-open, gio, ...) can be found on it.
#[cfg(target_os = "linux")]
fn empty_path_dir(dir: &std::path::Path) -> PathBuf {
    let empty = dir.join("empty-path");
    fs::create_dir_all(&empty).expect("failed to create empty PATH dir");
    empty
}

#[cfg(target_os = "linux")]
#[test]
fn open_launch_failure_exits_nonzero_and_reports_path() {
    let dir = fixture_dir("open-launch-failure");
    let input = dir.join("sample.md");
    fs::write(&input, "# Sample\n\nSome text.\n").expect("failed to write markdown fixture");

    // PATH points at an empty directory, so every opener `launch_browser`
    // tries (xdg-open, gio, gnome-open, kde-open5, kde-open, wslview) fails
    // to spawn and the launch itself fails with "no desktop opener found".
    let empty_path = empty_path_dir(&dir);

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--open")
        .arg(&input)
        .env("PATH", &empty_path)
        .output()
        .expect("failed to run mdo");

    assert!(
        !output.status.success(),
        "mdo --open should exit non-zero when the browser launch fails: {output:?}"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Failed to launch browser"),
        "stderr should report the launch failure: {stderr}"
    );

    let rendered_path = temp_output_for_test(&input);
    assert!(
        stderr.contains(
            rendered_path
                .to_str()
                .expect("rendered path should be valid UTF-8")
        ),
        "stderr should point at the rendered output path {rendered_path:?}: {stderr}"
    );

    // The render itself succeeded and nothing should have deleted it just
    // because the browser could not be launched.
    assert!(
        rendered_path.exists(),
        "rendered output should still exist at {rendered_path:?} after a launch failure"
    );
    let html = fs::read_to_string(&rendered_path).expect("failed to read rendered output");
    assert!(html.contains("<h1>Sample</h1>"));

    fs::remove_dir_all(rendered_path.parent().expect("rendered path has a parent"))
        .expect("failed to clean up temp render dir");
    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[cfg(target_os = "linux")]
#[test]
fn open_success_exits_zero() {
    let dir = fixture_dir("open-launch-success");
    let input = dir.join("sample.md");
    fs::write(&input, "# Sample\n\nSome text.\n").expect("failed to write markdown fixture");

    let fake_bin = dir.join("bin");
    fs::create_dir_all(&fake_bin).expect("failed to create fake bin dir");
    let fake_xdg_open = fake_bin.join("xdg-open");
    fs::write(&fake_xdg_open, "#!/bin/sh\nexit 0\n").expect("failed to write fake xdg-open");
    fs::set_permissions(&fake_xdg_open, fs::Permissions::from_mode(0o700))
        .expect("failed to chmod fake xdg-open");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--open")
        .arg(&input)
        .env("PATH", &fake_bin)
        .output()
        .expect("failed to run mdo");

    assert!(
        output.status.success(),
        "mdo --open should exit zero when render and launch both succeed: {output:?}"
    );

    let rendered_path = temp_output_for_test(&input);
    assert!(rendered_path.exists());

    fs::remove_dir_all(rendered_path.parent().expect("rendered path has a parent"))
        .expect("failed to clean up temp render dir");
    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

/// An opener that exists and spawns but then reports failure (exits nonzero,
/// e.g. because no browser handler is configured) must fail `--open` just as
/// honestly as an opener that is missing entirely — spawning is not opening.
#[cfg(target_os = "linux")]
#[test]
fn open_reports_failure_when_opener_exits_nonzero() {
    let dir = fixture_dir("open-opener-fails");
    let input = dir.join("sample.md");
    fs::write(&input, "# Sample\n\nSome text.\n").expect("failed to write markdown fixture");

    let fake_bin = dir.join("bin");
    fs::create_dir_all(&fake_bin).expect("failed to create fake bin dir");
    let fake_xdg_open = fake_bin.join("xdg-open");
    fs::write(&fake_xdg_open, "#!/bin/sh\nexit 3\n").expect("failed to write fake xdg-open");
    fs::set_permissions(&fake_xdg_open, fs::Permissions::from_mode(0o700))
        .expect("failed to chmod fake xdg-open");

    let output = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--open")
        .arg(&input)
        .env("PATH", &fake_bin)
        .output()
        .expect("failed to run mdo");

    assert!(
        !output.status.success(),
        "mdo --open should exit non-zero when the opener runs but fails: {output:?}"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Failed to launch browser"),
        "stderr should report the launch failure: {stderr}"
    );

    let rendered_path = temp_output_for_test(&input);
    assert!(
        rendered_path.exists(),
        "rendered output should survive an opener failure"
    );

    fs::remove_dir_all(rendered_path.parent().expect("rendered path has a parent"))
        .expect("failed to clean up temp render dir");
    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

/// Polls `path` until its contents contain `needle` or `timeout` elapses.
/// Used by the watch tests instead of a fixed sleep so they stay reliable
/// under slow/loaded CI without waiting any longer than necessary.
#[cfg(unix)]
fn wait_for_file_containing(path: &std::path::Path, needle: &str, timeout: Duration) -> bool {
    let start = Instant::now();
    loop {
        if let Ok(contents) = fs::read_to_string(path) {
            if contents.contains(needle) {
                return true;
            }
        }
        if start.elapsed() >= timeout {
            return false;
        }
        std::thread::sleep(Duration::from_millis(100));
    }
}

/// Kills the wrapped `--watch` child on drop so a failing assertion (or an
/// early return) never leaves a background `mdo --watch` process running
/// past the end of the test.
#[cfg(unix)]
struct WatchGuard(std::process::Child);

#[cfg(unix)]
impl Drop for WatchGuard {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

#[cfg(unix)]
#[test]
fn watch_survives_atomic_rename() {
    use std::process::Stdio;

    let dir = fixture_dir("watch-atomic-rename");
    let input = dir.join("sample.md");
    let output_path = dir.join("sample.html");
    let tmp = dir.join("sample.md.tmp");
    fs::write(&input, "# Initial\n").expect("failed to write markdown fixture");

    let child = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--watch")
        .arg(&input)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("failed to spawn mdo --watch");
    let _guard = WatchGuard(child);

    assert!(
        wait_for_file_containing(&output_path, "Initial", Duration::from_secs(10)),
        "initial render should appear within the timeout"
    );

    // Simulate an editor's atomic save: write the new content to a sibling
    // temp file, then rename it over the target. This replaces the target's
    // inode, which is exactly the case a file-level watch goes dead on.
    // Repeating it three times checks that watch mode keeps recovering
    // rather than surviving only the first rename by luck.
    for i in 0..3 {
        let marker = format!("Rewrite marker {i}");
        fs::write(&tmp, format!("# {marker}\n")).expect("failed to write rewrite temp file");
        fs::rename(&tmp, &input).expect("failed to atomically rename over the target");

        assert!(
            wait_for_file_containing(&output_path, &marker, Duration::from_secs(10)),
            "rewrite {i} should be re-rendered within the timeout"
        );
    }

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}

#[cfg(unix)]
#[test]
fn watch_ignores_sibling_changes() {
    use std::process::Stdio;

    let dir = fixture_dir("watch-sibling-changes");
    let input = dir.join("sample.md");
    let output_path = dir.join("sample.html");
    let sibling = dir.join("other.md");
    fs::write(&input, "# Initial\n").expect("failed to write markdown fixture");

    let child = Command::new(env!("CARGO_BIN_EXE_mdo"))
        .arg("--watch")
        .arg(&input)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("failed to spawn mdo --watch");
    let _guard = WatchGuard(child);

    assert!(
        wait_for_file_containing(&output_path, "Initial", Duration::from_secs(10)),
        "initial render should appear within the timeout"
    );
    let rendered_before =
        fs::read_to_string(&output_path).expect("failed to read initial rendered output");
    let mtime_before = fs::metadata(&output_path)
        .and_then(|m| m.modified())
        .expect("failed to read initial rendered output mtime");

    fs::write(&sibling, "# Sibling\n\nUnrelated file.\n")
        .expect("failed to write sibling markdown file");
    std::thread::sleep(Duration::from_secs(1));

    // A sibling-file event must not trigger a re-render. Byte-comparing the
    // output alone is not conclusive — the embedded generated date is
    // day-granular and fast renders can format to the same duration — so
    // also require the file's mtime (nanosecond granularity on Linux) to be
    // untouched: any rewrite, even byte-identical, would bump it.
    let rendered_after = fs::read_to_string(&output_path)
        .expect("failed to read rendered output after sibling change");
    let mtime_after = fs::metadata(&output_path)
        .and_then(|m| m.modified())
        .expect("failed to read rendered output mtime after sibling change");
    assert_eq!(
        rendered_before, rendered_after,
        "watch mode should not re-render sample.html for changes to an unrelated sibling file"
    );
    assert_eq!(
        mtime_before, mtime_after,
        "sample.html should not have been rewritten (mtime changed) for a sibling-file change"
    );

    fs::remove_dir_all(dir).expect("failed to clean up temp fixture dir");
}