skimmd 0.4.1

Read markdown with speed and precision.
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
//! Binary-level integration tests (§11.5 range outputs, §9 error templates,
//! §12.10 exit codes, §10 edge cases). TOC golden outputs are also asserted here
//! end-to-end (the library-level copy lives in `tests/golden_toc.rs`).

use std::path::PathBuf;
use std::process::Output;

use assert_cmd::Command;

const FILE: &str = "tests/fixtures/example.md";
const DATAFILE: &str = "tests/fixtures/data-images.md";
const FIX: &str = "tests/fixtures";

fn cmd() -> Command {
    Command::cargo_bin("skimmd").unwrap()
}

fn run(args: &[&str]) -> Output {
    cmd().args(args).output().unwrap()
}

fn bytes(p: &str) -> Vec<u8> {
    std::fs::read(p).unwrap()
}

fn expect_err(args: &[&str], code: i32, stderr: &str) {
    let o = run(args);
    assert_eq!(o.status.code(), Some(code), "args={args:?}");
    assert!(
        o.stdout.is_empty(),
        "stdout must be empty on error, got: {:?}",
        String::from_utf8_lossy(&o.stdout)
    );
    assert_eq!(String::from_utf8_lossy(&o.stderr), stderr, "args={args:?}");
}

// --- version / help ----------------------------------------------------------

#[test]
fn version_smoke() {
    let o = cmd().arg("--version").output().unwrap();
    assert!(o.status.success());
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(
        s.contains(env!("CARGO_PKG_VERSION")),
        "version line missing: {s}"
    );
}

#[test]
fn help_shows_range_grammar() {
    let o = cmd().arg("--help").output().unwrap();
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(
        s.contains("N-M") && s.contains("N-"),
        "range grammar missing: {s}"
    );
}

// --- TOC golden (end-to-end) -------------------------------------------------

#[test]
fn toc_md_golden() {
    let o = run(&[FILE]);
    assert_eq!(o.status.code(), Some(0));
    assert_eq!(o.stdout, bytes("tests/fixtures/expected_toc.md"));
}

// --- TOC substring filter (-f / --filter) -----------------------------------

#[test]
fn filter_matches_title_and_body_case_insensitive() {
    // "install" is in the Install heading AND its body (`cargo install`) -> 2.
    let o = run(&[FILE, "-f", "install"]);
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(
        s.contains("| line | level | end | chars | elided | title | matches |"),
        "{s}"
    );
    assert!(s.contains("| 12 | 2 | 19 | 23 | 0 | Install | 2 |"), "{s}");
    assert_eq!(s.lines().count(), 3, "header + 1 row, got: {s}");
}

#[test]
fn filter_matches_body_only_substring() {
    // "cargo" is only in the Install body, not any title -> proves body search.
    let o = run(&[FILE, "-f", "cargo"]);
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("| 12 | 2 | 19 | 23 | 0 | Install | 1 |"), "{s}");
    assert_eq!(s.lines().count(), 3, "header + 1 row, got: {s}");
}

#[test]
fn filter_can_match_multiple_rows() {
    // "body" appears in the Usage body and the Setext body -> two rows, one hit each.
    let o = run(&[FILE, "-f", "body"]);
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(
        s.contains("| 20 | 2 | 23 | 17 | 0 | Usage \\| Notes | 1 |"),
        "{s}"
    );
    assert!(
        s.contains("| 24 | 2 | 27 | 17 | 0 | Setext Heading | 1 |"),
        "{s}"
    );
    assert_eq!(s.lines().count(), 4, "header + 2 rows, got: {s}");
}

#[test]
fn filter_drops_unmatched_sections() {
    // "brew" matches only the macOS section; Install must be filtered out.
    let o = run(&[FILE, "-f", "brew"]);
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("macOS"), "{s}");
    assert!(
        !s.contains("Install"),
        "unmatched sections must be filtered: {s}"
    );
}

#[test]
fn filter_no_match_is_empty_toc_and_exit_zero() {
    let o = run(&[FILE, "-f", "zzzz-no-such-word"]);
    assert_eq!(o.status.code(), Some(0), "no match is not an error");
    assert_eq!(
        o.stdout, b"| line | level | end | chars | elided | title | matches |\n|---|---|---|---|---|---|---|\n",
        "header only on no match"
    );
}

#[test]
fn filter_matches_across_line_break() {
    // "foo" ends one line, "bar" starts the next: the substring spans the break.
    let p = tmp_file(
        "skimmd_filter_ws.md",
        b"## Sec\nends with foo\nbar starts here\n",
    );
    let o = run(&[p.to_str().unwrap(), "-f", "foo bar"]);
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("Sec"), "cross-line substring must match: {s}");
    assert_eq!(s.lines().count(), 3, "header + 1 row, got: {s}");
}

#[test]
fn filter_matches_any_of_multiple_needles() {
    let p = tmp_file(
        "skimmd_filter_multi.md",
        b"# Alpha\nalpha body\n## Beta\nonly beta\n## Gamma\ngamma text\n",
    );
    let o = run(&[p.to_str().unwrap(), "-f", "alpha|gamma"]);
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("Alpha"), "first candidate matched: {s}");
    assert!(s.contains("Gamma"), "second candidate matched: {s}");
    assert!(!s.contains("Beta"), "non-matching section excluded: {s}");
    assert_eq!(s.lines().count(), 4, "header + 2 rows, got: {s}");
}

// --- range mode (§11.5) ------------------------------------------------------

#[test]
fn range_12_19() {
    let o = run(&[FILE, "12-19"]);
    assert_eq!(o.stdout, bytes("tests/fixtures/expected_12-19.txt"));
}

#[test]
fn range_1_4() {
    let o = run(&[FILE, "1-4"]);
    assert_eq!(o.stdout, bytes("tests/fixtures/expected_1-4.txt"));
}

#[test]
fn range_29_to_end() {
    let o = run(&[FILE, "29-"]);
    assert_eq!(o.stdout, bytes("tests/fixtures/expected_29-.txt"));
}

#[test]
fn range_8_8_and_16_to_end() {
    // two spec args
    let o = run(&[FILE, "8-8", "16-"]);
    assert_eq!(o.stdout, bytes("tests/fixtures/expected_8-8_16-.txt"));
    // equivalent comma form
    let o2 = run(&[FILE, "8-8,16-"]);
    assert_eq!(o2.stdout, o.stdout);
}

#[test]
fn range_1_minus_reproduces_file() {
    let o = run(&[FILE, "1-"]);
    assert_eq!(
        o.stdout,
        bytes(FILE),
        "1- must be byte-identical to the file (no data URLs in this fixture)"
    );
}

// --- data-URL elision + --raw ------------------------------------------------

#[test]
fn raw_1_minus_reproduces_data_file() {
    let o = run(&[DATAFILE, "1-", "--raw"]);
    assert_eq!(
        o.stdout,
        bytes(DATAFILE),
        "--raw 1- must be byte-identical to the file"
    );
}

#[test]
fn default_1_minus_elides_data_file() {
    let o = run(&[DATAFILE, "1-"]);
    assert_eq!(
        o.stdout,
        bytes("tests/fixtures/expected_data-images.txt"),
        "default 1- must match the elided golden"
    );
}

#[test]
fn toc_shows_nonzero_elided_on_image_sections() {
    let o = run(&[DATAFILE]);
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("| chars | elided |"), "header: {s}");
    // Figure section: elided markdown image -> elided > 0 (198 raw − 95 chars).
    assert!(
        s.contains("| 3 | 2 | 10 | 95 | 103 | Figure |"),
        "Figure row: {s}"
    );
    // Code sample section: fence is verbatim -> elided == 0.
    assert!(
        s.contains("| 15 | 2 | 21 | 101 | 0 | Code sample |"),
        "Code sample row: {s}"
    );
}

#[test]
fn raw_is_noop_in_toc_mode() {
    let a = run(&[DATAFILE]);
    let b = run(&[DATAFILE, "--raw"]);
    assert_eq!(a.stdout, b.stdout, "--raw must be a no-op in TOC mode");
}

#[test]
fn help_mentions_raw() {
    let o = cmd().arg("--help").output().unwrap();
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("--raw"), "help missing --raw: {s}");
}

#[test]
fn range_merge_is_equivalent() {
    let a = run(&[FILE, "5-10,3-6"]);
    let b = run(&[FILE, "3-10"]);
    assert_eq!(a.stdout, b.stdout);
}

// --- range errors (§9, exit 1, no stdout) ------------------------------------

#[test]
fn range_errors() {
    expect_err(
        &[FILE, "31-"],
        1,
        "skimmd: range 31-: start 31 exceeds file length (30 lines)\n",
    );
    expect_err(
        &[FILE, "10-5"],
        1,
        "skimmd: range 10-5: end is less than start\n",
    );
    expect_err(
        &[FILE, "5"],
        1,
        "skimmd: invalid range spec '5': expected N-M or N- (comma-separated)\n",
    );
    expect_err(
        &[FILE, "1-10,x-y"],
        1,
        "skimmd: invalid range spec '1-10,x-y': expected N-M or N- (comma-separated)\n",
    );
    expect_err(
        &[FILE, "0-"],
        1,
        "skimmd: range 0-: start must be at least 1\n",
    );
    // first failing range in pool order
    expect_err(
        &[FILE, "5-10,0-2"],
        1,
        "skimmd: range 0-2: start must be at least 1\n",
    );
}

// --- file errors (§9, exit 1) ------------------------------------------------

#[test]
fn file_not_found() {
    expect_err(
        &["/nonexistent/skimmd_test_nope.md"],
        1,
        "skimmd: /nonexistent/skimmd_test_nope.md: No such file or directory\n",
    );
}

#[test]
fn file_is_a_directory() {
    expect_err(&[FIX], 1, &format!("skimmd: {FIX}: is a directory\n"));
}

#[test]
fn file_not_utf8() {
    let p = tmp_file("skimmd_not_utf8.bin", &[0xFF, 0xFE, 0x00, 0x80]);
    expect_err(
        &[p.to_str().unwrap()],
        1,
        &format!("skimmd: {}: not valid UTF-8\n", p.display()),
    );
}

#[test]
fn bom_is_invisible() {
    let p = tmp_file("skimmd_bom.md", b"\xef\xbb\xbf# Hello\nbody\n");
    let o = run(&[p.to_str().unwrap()]);
    // BOM stripped: a normal H1 at line 1, no phantom bytes.
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("| 1 | 1 | 2 | 5 | 0 | Hello |"), "{s}");
}

// --- stdin (-) ---------------------------------------------------------------

#[test]
fn no_args_is_same_as_dash_stdin() {
    // No FILE (or `-`) reads the TOC from standard input; the two must match byte-for-byte.
    let md = "# Hello\nbody\n## Sub\ntext\n";
    let a = cmd().write_stdin(md).output().unwrap();
    let b = cmd().arg("-").write_stdin(md).output().unwrap();
    assert_eq!(a.status.code(), Some(0), "no-args must succeed");
    assert_eq!(a.stdout, b.stdout, "no-args must behave like '-'");
    let s = String::from_utf8_lossy(&a.stdout);
    assert!(
        s.contains("| 1 | 1 | 4 | 5 | 0 | Hello |"),
        "TOC missing: {s}"
    );
}

#[test]
fn stdin_toc() {
    let o = cmd()
        .arg("-")
        .write_stdin("# Hello\nbody\n## Sub\ntext\n")
        .output()
        .unwrap();
    assert_eq!(o.status.code(), Some(0));
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("| 1 | 1 | 4 | 5 | 0 | Hello |"), "{s}");
    assert!(s.contains("| 3 | 2 | 4 | 5 | 0 | Sub |"), "{s}");
}

#[test]
fn stdin_range_mode() {
    let o = cmd()
        .args(["-", "2-3"])
        .write_stdin("l1\nl2\nl3\nl4\n")
        .output()
        .unwrap();
    assert_eq!(o.status.code(), Some(0));
    assert_eq!(o.stdout, b"l2\nl3\n");
}

#[test]
fn stdin_1_minus_reproduces_input() {
    let md = "a\nb\n";
    let o = cmd().args(["-", "1-"]).write_stdin(md).output().unwrap();
    assert_eq!(o.stdout, md.as_bytes());
}

#[test]
fn stdin_bom_is_invisible() {
    let o = cmd()
        .arg("-")
        .write_stdin("\u{feff}# Hi\nx\n")
        .output()
        .unwrap();
    let s = String::from_utf8_lossy(&o.stdout);
    assert!(s.contains("| 1 | 1 | 2 | 2 | 0 | Hi |"), "{s}");
}

#[test]
fn stdin_not_utf8() {
    let o = cmd()
        .arg("-")
        .write_stdin([0xFF, 0xFE, 0x00])
        .output()
        .unwrap();
    assert_eq!(o.status.code(), Some(1));
    assert!(o.stdout.is_empty());
    assert_eq!(
        String::from_utf8_lossy(&o.stderr),
        "skimmd: <stdin>: not valid UTF-8\n"
    );
}

// --- usage errors (clap, exit 2) ---------------------------------------------

#[test]
fn unknown_flag_is_usage_error() {
    let o = run(&["--bogus", FILE]);
    assert_eq!(o.status.code(), Some(2));
}

// --- broken pipe / stdout errors (§8.4, §10) ---------------------------------

#[test]
fn broken_pipe_is_clean_exit_zero() {
    let bin = cmd().get_program().to_string_lossy().into_owned();
    // `head -n 1` closes the pipe early; skimmd must exit 0 (not SIGPIPE) quietly.
    let out = std::process::Command::new("bash")
        .arg("-c")
        .arg(format!(
            "{bin} {FILE} 1- | head -n 1 >/dev/null; echo \"${{PIPESTATUS[0]}}\""
        ))
        .output()
        .unwrap();
    let code = String::from_utf8_lossy(&out.stdout).trim().to_string();
    assert_eq!(
        code,
        "0",
        "skimmd exit on EPIPE must be 0; stderr={:?}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn non_epipe_stdout_error_is_exit_one() {
    // /dev/full makes writes fail with ENOSPC (not EPIPE) -> exit 1 with a message.
    if !std::path::Path::new("/dev/full").exists() {
        return; // non-Linux: skip
    }
    let bin = cmd().get_program().to_string_lossy().into_owned();
    let out = std::process::Command::new("bash")
        .arg("-c")
        .arg(format!("{bin} {FILE} 1- > /dev/full 2>/tmp/skimmd_nospc.$$; ec=$?; cat /tmp/skimmd_nospc.$$; rm -f /tmp/skimmd_nospc.$$; echo \"EC=$ec\""))
        .output()
        .unwrap();
    let s = String::from_utf8_lossy(&out.stdout);
    assert!(s.contains("EC=1"), "expected exit 1; got: {s}");
    assert!(
        s.contains("skimmd: error writing to stdout:"),
        "expected stdout error message; got: {s}"
    );
}

/// Write `data` to a temp file and return its path (cleaned up on drop is not
/// guaranteed; tests use unique names).
fn tmp_file(name: &str, data: &[u8]) -> PathBuf {
    let p = std::env::temp_dir().join(name);
    std::fs::write(&p, data).unwrap();
    p
}