mbr-markdown-browser 0.5.1-rc1

A fast, featureful markdown viewer, browser, and (optional) static site generator
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
use clap::{ArgGroup, Parser};
use std::path::PathBuf;

/// Markdown browser and previewer
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
// The mode flags below are mutually exclusive. This is expressed as an
// `ArgGroup` rather than per-argument `conflicts_with_all` lists because two of
// the members are `#[cfg(feature = "media-metadata")]`. A `#[cfg]`-removed
// argument is simply never added to the group, whereas naming it in
// `conflicts_with_all` left a dangling reference that tripped clap's debug
// assertions and panicked on *every* invocation of a build without that
// feature. Keeping the exclusivity in one place also means new mode flags only
// have to join the group instead of being added to every other flag's list.
#[command(group(ArgGroup::new("mode").multiple(false)))]
pub struct Args {
    /// Launch GUI window (default if no mode specified)
    #[arg(short, long, group = "mode")]
    pub gui: bool,

    /// Launch HTTP server only (no GUI)
    #[arg(short, long, group = "mode")]
    pub server: bool,

    /// Render single markdown file to stdout (CLI mode)
    #[arg(short = 'o', long, group = "mode")]
    pub stdout: bool,

    /// Build static site (generate HTML for all markdown files)
    #[arg(short, long, group = "mode")]
    pub build: bool,

    /// Extract video metadata (cover, chapters, captions) and save as sidecar files.
    /// Takes a video file path and generates .cover.jpg, .chapters.en.vtt, and
    /// .captions.en.vtt files next to it (if the video contains this data).
    #[cfg(feature = "media-metadata")]
    #[arg(long, group = "mode")]
    pub extract_video_metadata: bool,

    /// Extract cover images from PDF files and save as sidecar files.
    /// Takes a PDF file or directory path and generates {file}.cover.jpg next to each PDF.
    /// For directories, recursively processes all .pdf files.
    #[cfg(feature = "media-metadata")]
    #[arg(long, group = "mode")]
    pub extract_pdf_cover: bool,

    /// Output directory for static site build (default: "build")
    #[arg(long, default_value = "build")]
    pub output: PathBuf,

    /// Markdown file or folder to serve (defaults to current directory)
    #[arg(default_value = ".")]
    pub path: PathBuf,

    /// Timeout in milliseconds for fetching oembed/OpenGraph metadata from URLs.
    /// Falls back to plain link if fetch doesn't complete in time.
    /// Set to 0 to disable oembed fetching entirely (uses plain links).
    /// Default: 500ms for server/GUI mode, 0 (disabled) for build mode.
    #[arg(long)]
    pub oembed_timeout_ms: Option<u64>,

    /// Maximum size in bytes for the oembed cache. The cache stores fetched page
    /// metadata to avoid redundant network requests. Set to 0 to disable caching.
    /// Default: 2097152 (2MB). Accepts human-readable sizes like "2MB" or "512KB".
    #[arg(long)]
    pub oembed_cache_size: Option<usize>,

    /// Override template folder (replaces default .mbr/ and compiled defaults).
    /// Files found in this folder take precedence; missing files fall back to defaults.
    #[arg(long, value_name = "PATH")]
    pub template_folder: Option<PathBuf>,

    /// Increase logging verbosity (-v = info, -vv = debug, -vvv = trace).
    /// Default is warn level. Can also set RUST_LOG env var.
    #[arg(short, long, action = clap::ArgAction::Count)]
    pub verbose: u8,

    /// Suppress all output except errors
    #[arg(short, long)]
    pub quiet: bool,

    /// Port to listen on when running in server mode (-s).
    /// Overrides the default port from config (default: 5200).
    #[arg(short = 'p', long, value_name = "PORT")]
    pub port: Option<u16>,

    /// Host/IP address to bind to when running in server mode (-s).
    /// Overrides the default from config (default: 127.0.0.1).
    /// Use 0.0.0.0 to listen on all interfaces.
    #[arg(long, value_name = "HOST")]
    pub host: Option<String>,

    /// Pico CSS theme to use. Overrides config file setting.
    /// Options: default, fluid, or a color name (amber, blue, cyan, fuchsia, green,
    /// grey, indigo, jade, lime, orange, pink, pumpkin, purple, red, sand, slate,
    /// violet, yellow, zinc). Prefix with "fluid." for fluid typography (e.g., fluid.amber).
    #[arg(long, value_name = "THEME")]
    pub theme: Option<String>,

    /// Number of files to process concurrently during static build (-b).
    /// Higher values use more memory but may be faster on multi-core systems.
    /// Default: auto (2x CPU cores, max 32).
    #[arg(long, value_name = "N")]
    pub build_concurrency: Option<usize>,

    /// Skip internal link validation during static build (-b).
    /// Useful for faster builds when you don't need link checking.
    #[arg(long)]
    pub skip_link_checks: bool,

    /// Exit with a non-zero status if the static build (-b) detects broken
    /// internal links. Intended for CI. Has no effect with --skip-link-checks
    /// (which skips validation entirely) or outside build mode.
    #[arg(long)]
    pub fail_on_broken_links: bool,

    /// Disable bidirectional link tracking (backlinks).
    /// When disabled, the links.json endpoint returns 404 and no links.json files
    /// are generated during static builds.
    #[arg(long)]
    pub no_link_tracking: bool,

    /// Disable typed relationship tracking (named frontmatter relationships).
    /// When disabled, relationships are omitted from links.json and site.json
    /// and not rendered in the info panel.
    #[arg(long)]
    pub no_relationship_tracking: bool,

    /// Highlight blocks that start with an incomplete-marker (TK/TODO/FIXME/XXX).
    /// Default: on for server/GUI mode, off for static builds.
    #[arg(long, conflicts_with = "no_mark_incomplete")]
    pub mark_incomplete: bool,

    /// Disable highlighting of incomplete-marker blocks (TK/TODO/FIXME/XXX).
    #[arg(long, conflicts_with = "mark_incomplete")]
    pub no_mark_incomplete: bool,

    /// Text to prepend to all page titles (e.g., "My Site: ").
    #[arg(long, value_name = "TEXT")]
    pub title_prefix: Option<String>,

    /// Text to append to all page titles (e.g., " | My Site").
    #[arg(long, value_name = "TEXT")]
    pub title_suffix: Option<String>,

    /// [EXPERIMENTAL] Enable dynamic video transcoding to serve lower-resolution
    /// HLS variants (720p, 480p) for bandwidth savings. Only active in server/GUI mode.
    /// Videos are transcoded on-demand as segments and cached in memory.
    /// Feedback welcome!
    #[cfg(feature = "media-metadata")]
    #[arg(long)]
    pub transcode: bool,

    /// Enable the in-browser markdown editing endpoints (server/GUI mode only).
    /// Loopback callers may edit without a token (still CSRF-protected); remote
    /// callers require a token — see --generate-edit-token. Off by default.
    #[arg(long)]
    pub edit: bool,

    /// Generate a hashed editing token from a password (prompted; leave blank to
    /// auto-generate a random token), print the token and the `edit_token_hash`
    /// config line, then exit. Nothing is written to disk.
    #[arg(long)]
    pub generate_edit_token: bool,
}

impl Args {
    /// Get the log level filter string based on verbosity flags.
    /// Returns a filter suitable for tracing_subscriber::EnvFilter.
    pub fn log_level_filter(&self) -> String {
        let level = if self.quiet {
            "error"
        } else {
            match self.verbose {
                0 => "warn",
                1 => "info",
                2 => "debug",
                _ => "trace",
            }
        };

        // Set level for mbr crate and tower_http (for request logging)
        format!(
            "{}={},tower_http={}",
            env!("CARGO_CRATE_NAME"),
            level,
            level
        )
    }
}

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

    /// Helper to create Args with specific verbosity settings
    fn args_with_verbosity(verbose: u8, quiet: bool) -> Args {
        Args {
            gui: false,
            server: false,
            stdout: false,
            build: false,
            #[cfg(feature = "media-metadata")]
            extract_video_metadata: false,
            #[cfg(feature = "media-metadata")]
            extract_pdf_cover: false,
            output: PathBuf::from("build"),
            path: PathBuf::from("."),
            oembed_timeout_ms: None,
            oembed_cache_size: None,
            template_folder: None,
            verbose,
            quiet,
            port: None,
            host: None,
            theme: None,
            build_concurrency: None,
            skip_link_checks: false,
            fail_on_broken_links: false,
            no_link_tracking: false,
            no_relationship_tracking: false,
            mark_incomplete: false,
            no_mark_incomplete: false,
            title_prefix: None,
            title_suffix: None,
            #[cfg(feature = "media-metadata")]
            transcode: false,
            edit: false,
            generate_edit_token: false,
        }
    }

    #[test]
    fn test_log_level_default_is_warn() {
        let args = args_with_verbosity(0, false);
        let filter = args.log_level_filter();
        assert!(filter.contains("=warn"));
        assert!(filter.contains("tower_http=warn"));
    }

    #[test]
    fn test_log_level_verbose_once_is_info() {
        let args = args_with_verbosity(1, false);
        let filter = args.log_level_filter();
        assert!(filter.contains("=info"));
        assert!(filter.contains("tower_http=info"));
    }

    #[test]
    fn test_log_level_verbose_twice_is_debug() {
        let args = args_with_verbosity(2, false);
        let filter = args.log_level_filter();
        assert!(filter.contains("=debug"));
        assert!(filter.contains("tower_http=debug"));
    }

    #[test]
    fn test_log_level_verbose_three_times_is_trace() {
        let args = args_with_verbosity(3, false);
        let filter = args.log_level_filter();
        assert!(filter.contains("=trace"));
        assert!(filter.contains("tower_http=trace"));
    }

    #[test]
    fn test_log_level_verbose_more_than_three_is_still_trace() {
        let args = args_with_verbosity(10, false);
        let filter = args.log_level_filter();
        assert!(filter.contains("=trace"));
    }

    #[test]
    fn test_log_level_quiet_is_error() {
        let args = args_with_verbosity(0, true);
        let filter = args.log_level_filter();
        assert!(filter.contains("=error"));
        assert!(filter.contains("tower_http=error"));
    }

    #[test]
    fn test_log_level_quiet_overrides_verbose() {
        // When both quiet and verbose are set, quiet takes precedence
        let args = args_with_verbosity(3, true);
        let filter = args.log_level_filter();
        assert!(filter.contains("=error"));
    }

    #[test]
    fn test_log_level_includes_crate_name() {
        let args = args_with_verbosity(0, false);
        let filter = args.log_level_filter();
        // Should include the crate name (mbr)
        assert!(filter.contains("mbr="));
    }

    // Test CLI parsing with clap
    #[test]
    fn test_parse_default_args() {
        // Parse with no arguments (just the program name)
        let args = Args::parse_from(["mbr"]);
        assert!(!args.gui);
        assert!(!args.server);
        assert!(!args.stdout);
        assert!(!args.build);
        assert_eq!(args.path, PathBuf::from("."));
        assert_eq!(args.output, PathBuf::from("build"));
        assert_eq!(args.verbose, 0);
        assert!(!args.quiet);
    }

    #[test]
    fn test_parse_server_mode() {
        let args = Args::parse_from(["mbr", "-s"]);
        assert!(args.server);
        assert!(!args.gui);
    }

    #[test]
    fn test_parse_gui_mode() {
        let args = Args::parse_from(["mbr", "-g"]);
        assert!(args.gui);
        assert!(!args.server);
    }

    #[test]
    fn test_parse_build_mode() {
        let args = Args::parse_from(["mbr", "-b"]);
        assert!(args.build);
        assert!(!args.server);
        assert!(!args.gui);
    }

    #[test]
    fn test_parse_stdout_mode() {
        let args = Args::parse_from(["mbr", "-o"]);
        assert!(args.stdout);
    }

    #[test]
    fn test_parse_verbose_flags() {
        let args = Args::parse_from(["mbr", "-v"]);
        assert_eq!(args.verbose, 1);

        let args = Args::parse_from(["mbr", "-vv"]);
        assert_eq!(args.verbose, 2);

        let args = Args::parse_from(["mbr", "-vvv"]);
        assert_eq!(args.verbose, 3);
    }

    #[test]
    fn test_parse_quiet_flag() {
        let args = Args::parse_from(["mbr", "-q"]);
        assert!(args.quiet);
    }

    #[test]
    fn test_parse_port() {
        let args = Args::parse_from(["mbr", "-p", "8080"]);
        assert_eq!(args.port, Some(8080));
    }

    #[test]
    fn test_parse_host() {
        let args = Args::parse_from(["mbr", "--host", "0.0.0.0"]);
        assert_eq!(args.host, Some("0.0.0.0".to_string()));
    }

    #[test]
    fn test_parse_theme() {
        let args = Args::parse_from(["mbr", "--theme", "amber"]);
        assert_eq!(args.theme, Some("amber".to_string()));
    }

    #[test]
    fn test_parse_output_directory() {
        let args = Args::parse_from(["mbr", "-b", "--output", "./public"]);
        assert!(args.build);
        assert_eq!(args.output, PathBuf::from("./public"));
    }

    #[test]
    fn test_parse_path_argument() {
        let args = Args::parse_from(["mbr", "/path/to/notes"]);
        assert_eq!(args.path, PathBuf::from("/path/to/notes"));
    }

    #[test]
    fn test_parse_oembed_timeout() {
        let args = Args::parse_from(["mbr", "--oembed-timeout-ms", "1000"]);
        assert_eq!(args.oembed_timeout_ms, Some(1000));
    }

    #[test]
    fn test_parse_build_concurrency() {
        let args = Args::parse_from(["mbr", "-b", "--build-concurrency", "8"]);
        assert_eq!(args.build_concurrency, Some(8));
    }

    #[test]
    fn test_parse_skip_link_checks() {
        let args = Args::parse_from(["mbr", "-b", "--skip-link-checks"]);
        assert!(args.skip_link_checks);
    }

    #[test]
    fn test_parse_fail_on_broken_links() {
        let args = Args::parse_from(["mbr", "-b", "--fail-on-broken-links"]);
        assert!(args.fail_on_broken_links);
    }

    #[test]
    fn test_parse_no_link_tracking() {
        let args = Args::parse_from(["mbr", "--no-link-tracking"]);
        assert!(args.no_link_tracking);
    }

    #[test]
    fn test_parse_no_relationship_tracking() {
        let args = Args::parse_from(["mbr", "--no-relationship-tracking"]);
        assert!(args.no_relationship_tracking);
    }

    #[test]
    fn test_parse_mark_incomplete() {
        let args = Args::parse_from(["mbr", "--mark-incomplete"]);
        assert!(args.mark_incomplete);
        assert!(!args.no_mark_incomplete);
    }

    #[test]
    fn test_parse_no_mark_incomplete() {
        let args = Args::parse_from(["mbr", "--no-mark-incomplete"]);
        assert!(args.no_mark_incomplete);
        assert!(!args.mark_incomplete);
    }

    #[test]
    fn test_parse_mark_incomplete_conflicts_with_no_mark_incomplete() {
        let result = Args::try_parse_from(["mbr", "--mark-incomplete", "--no-mark-incomplete"]);
        assert!(result.is_err(), "Mutually exclusive flags should error");
    }

    /// Validates the entire clap command definition: dangling `conflicts_with`
    /// / group references, duplicate ids, invalid defaults.
    ///
    /// This is clap's own self-check and it must hold under *every* feature
    /// combination. Without it, a build compiled without `media-metadata`
    /// referenced the feature-gated `extract_*` arguments in the mode flags'
    /// conflict lists and panicked inside clap on **every** invocation — a
    /// shipped-binary bug, not just a test failure.
    #[test]
    fn test_command_definition_is_valid() {
        use clap::CommandFactory;
        Args::command().debug_assert();
    }

    /// The mode flags are mutually exclusive. Only the ungated flags are used
    /// here, so this holds no matter how the crate is compiled.
    #[test]
    fn test_mode_flags_are_mutually_exclusive() {
        let modes = ["--gui", "--server", "--stdout", "--build"];
        for (i, first) in modes.iter().enumerate() {
            for second in &modes[i + 1..] {
                let result = Args::try_parse_from(["mbr", first, second]);
                assert!(
                    result.is_err(),
                    "{first} and {second} should be mutually exclusive"
                );
            }
        }
    }

    /// Each mode flag must still be accepted on its own.
    #[test]
    fn test_each_mode_flag_parses_alone() {
        for mode in ["--gui", "--server", "--stdout", "--build"] {
            assert!(
                Args::try_parse_from(["mbr", mode]).is_ok(),
                "{mode} should parse on its own"
            );
        }
    }

    /// With `media-metadata` on, the extract flags join the same exclusivity
    /// group as the other modes. This pins the behavior the `ArgGroup` replaced.
    #[cfg(feature = "media-metadata")]
    #[test]
    fn test_extract_flags_conflict_with_other_modes() {
        for extract in ["--extract-video-metadata", "--extract-pdf-cover"] {
            for mode in ["--gui", "--server", "--stdout", "--build"] {
                let result = Args::try_parse_from(["mbr", extract, mode]);
                assert!(result.is_err(), "{extract} and {mode} should conflict");
            }
        }
        let result =
            Args::try_parse_from(["mbr", "--extract-video-metadata", "--extract-pdf-cover"]);
        assert!(
            result.is_err(),
            "the two extract flags should conflict with each other"
        );
    }

    #[cfg(feature = "media-metadata")]
    #[test]
    fn test_parse_extract_pdf_cover() {
        let args = Args::parse_from(["mbr", "--extract-pdf-cover", "/path/to/pdfs"]);
        assert!(args.extract_pdf_cover);
        assert_eq!(args.path, PathBuf::from("/path/to/pdfs"));
    }

    #[test]
    fn test_parse_template_folder() {
        let args = Args::parse_from(["mbr", "--template-folder", "/custom/templates"]);
        assert_eq!(
            args.template_folder,
            Some(PathBuf::from("/custom/templates"))
        );
    }

    #[test]
    fn test_parse_title_prefix() {
        let args = Args::parse_from(["mbr", "--title-prefix", "My Site: "]);
        assert_eq!(args.title_prefix, Some("My Site: ".to_string()));
    }

    #[test]
    fn test_parse_title_suffix() {
        let args = Args::parse_from(["mbr", "--title-suffix", " | My Site"]);
        assert_eq!(args.title_suffix, Some(" | My Site".to_string()));
    }
}