treemd 0.7.0

A markdown navigator with tree-based structural navigation and syntax highlighting
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
//! End-to-end integration tests for the `treemd` binary.
//!
//! These tests invoke the actual built binary and assert on its
//! stdout/stderr/exit code, exercising the full CLI surface.
//!
//! No assert_cmd / predicates dependency — uses the built-in
//! `CARGO_BIN_EXE_treemd` env var that Cargo sets for integration tests.

use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

/// Path to the built `treemd` binary.
fn bin() -> PathBuf {
    PathBuf::from(env!("CARGO_BIN_EXE_treemd"))
}

/// A small fixture markdown document used across most tests.
const FIXTURE: &str = "\
# Title

Intro paragraph.

## Installation

Install steps here.

```rust
// `# fake heading` inside a code block must be ignored by parsing.
let x = 1;
```

## Usage

Some usage notes.

### Advanced

Deep section.

## Conclusion

End of doc.
";

/// Write the fixture to a tempfile and return its path.
/// Caller is responsible for cleanup (we leak — test process exits anyway).
fn fixture_file() -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "treemd-it-{}-{}",
        std::process::id(),
        // Add a tiny salt so concurrent tests don't collide on the same fixture.
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    ));
    std::fs::create_dir_all(&dir).expect("create temp dir");
    let path = dir.join("doc.md");
    std::fs::write(&path, FIXTURE).expect("write fixture");
    path
}

/// Run treemd with args, return (stdout, stderr, exit code).
fn run(args: &[&str]) -> (String, String, i32) {
    let out = Command::new(bin())
        .args(args)
        .output()
        .expect("spawn treemd");
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.code().unwrap_or(-1),
    )
}

/// Run treemd with stdin piped from `input` and the given args.
fn run_with_stdin(args: &[&str], input: &str) -> (String, String, i32) {
    let mut child = Command::new(bin())
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn treemd");
    child
        .stdin
        .as_mut()
        .expect("stdin")
        .write_all(input.as_bytes())
        .expect("write stdin");
    let out = child.wait_with_output().expect("wait");
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.code().unwrap_or(-1),
    )
}

// ------------------------------------------------------------------
// --version / --help — basic CLI plumbing
// ------------------------------------------------------------------

#[test]
fn version_flag_prints_version_and_exits_zero() {
    let (stdout, _, code) = run(&["--version"]);
    assert_eq!(code, 0);
    assert!(
        stdout.contains("treemd"),
        "version output should mention treemd, got: {stdout}"
    );
}

#[test]
fn help_flag_prints_usage_and_exits_zero() {
    let (stdout, _, code) = run(&["--help"]);
    assert_eq!(code, 0);
    assert!(stdout.contains("Usage"), "help output should contain Usage");
    assert!(
        stdout.contains("--list") && stdout.contains("--tree"),
        "help should mention --list and --tree"
    );
}

#[test]
fn query_help_prints_query_docs_and_exits_zero() {
    let (stdout, _, code) = run(&["--query-help"]);
    assert_eq!(code, 0);
    assert!(stdout.contains("Query Language") || stdout.contains("ELEMENT SELECTORS"));
}

// ------------------------------------------------------------------
// --list (plain / json) and filtering
// ------------------------------------------------------------------

#[test]
fn list_plain_emits_all_headings() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    // Exactly one line per heading in the fixture (5 of them).
    let lines: Vec<_> = stdout.lines().collect();
    assert_eq!(lines.len(), 5, "expected 5 heading lines, got: {:?}", lines);
    assert!(lines[0].starts_with("# Title"));
    assert!(lines[1].starts_with("## Installation"));
    assert!(lines[2].starts_with("## Usage"));
    assert!(lines[3].starts_with("### Advanced"));
    assert!(lines[4].starts_with("## Conclusion"));
}

#[test]
fn list_with_level_filter_keeps_only_that_level() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", "-L", "2", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    for line in stdout.lines() {
        assert!(line.starts_with("## "), "non-h2 line leaked: {line}");
    }
    assert_eq!(stdout.lines().count(), 3); // Installation, Usage, Conclusion
}

#[test]
fn list_with_text_filter_is_case_insensitive() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", "--filter", "INSTALL", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert_eq!(stdout.trim(), "## Installation");
}

#[test]
fn list_json_output_is_valid_and_has_expected_shape() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", "-o", "json", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    let v: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let doc = &v["document"];
    assert_eq!(doc["metadata"]["headingCount"], 5);
    assert_eq!(doc["metadata"]["maxDepth"], 3);
    let sections = doc["sections"].as_array().expect("sections array");
    assert_eq!(sections.len(), 1);
    assert_eq!(sections[0]["title"], "Title");
    let children = sections[0]["children"].as_array().expect("children");
    assert_eq!(children.len(), 3); // Installation, Usage, Conclusion
}

// ------------------------------------------------------------------
// --tree
// ------------------------------------------------------------------

#[test]
fn tree_output_uses_box_drawing_chars() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["--tree", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    // At least one branch and one terminal connector should appear.
    assert!(stdout.contains("") || stdout.contains(""), "no branches");
    assert!(stdout.contains("Title"));
    assert!(stdout.contains("Advanced"));
}

#[test]
fn tree_with_filter_narrows_tree() {
    // Regression: --filter was documented to work with --tree but
    // print_tree ignored it.
    let f = fixture_file();
    let (stdout, _, code) = run(&["--tree", "--filter", "Install", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(stdout.contains("Installation"));
    assert!(!stdout.contains("Title"), "non-matching headings leaked");
    assert!(!stdout.contains("Usage"), "non-matching headings leaked");
    assert!(
        !stdout.contains("Conclusion"),
        "non-matching headings leaked"
    );
}

#[test]
fn tree_with_level_narrows_tree() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["--tree", "-L", "2", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(stdout.contains("Installation"));
    assert!(stdout.contains("Usage"));
    assert!(stdout.contains("Conclusion"));
    assert!(!stdout.contains("# Title"), "h1 leaked: {stdout}");
    assert!(!stdout.contains("Advanced"), "h3 leaked: {stdout}");
}

// ------------------------------------------------------------------
// -n / --line-numbers
// ------------------------------------------------------------------

#[test]
fn list_with_line_numbers_appends_ranges() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", "-n", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    let lines: Vec<_> = stdout.lines().collect();
    assert_eq!(lines.len(), 5);
    // "Title" is h1 and nests every other heading in the fixture, so its
    // range must run through the end of the document.
    assert_eq!(lines[0], "# Title [1-24]");
    // "Conclusion" is the last heading and has no children.
    assert_eq!(lines[4], "## Conclusion [22-24]");
    for line in &lines {
        assert!(
            line.contains('[') && line.ends_with(']'),
            "missing line range: {line}"
        );
    }
}

#[test]
fn list_without_line_numbers_has_no_ranges() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(!stdout.contains('['), "unexpected line range: {stdout}");
}

#[test]
fn tree_with_line_numbers_appends_ranges() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["--tree", "-n", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(stdout.contains("Title [1-24]"));
    assert!(stdout.contains("Conclusion [22-24]"));
}

#[test]
fn list_with_line_numbers_and_level_filter_keeps_document_wide_ranges() {
    // Ranges must reflect the full document even when the *displayed* set
    // of headings is narrowed by --level.
    let f = fixture_file();
    let (stdout, _, code) = run(&["-l", "-n", "-L", "2", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    let lines: Vec<_> = stdout.lines().collect();
    assert_eq!(lines.len(), 3);
    assert!(lines[0].starts_with("## Installation ["));
    assert!(lines[1].starts_with("## Usage ["));
    assert!(lines[2].starts_with("## Conclusion ["));
}

#[test]
fn list_json_output_ignores_line_numbers_flag() {
    let f = fixture_file();
    let (with_n, _, code1) = run(&["-l", "-n", "-o", "json", f.to_str().unwrap()]);
    let (without_n, _, code2) = run(&["-l", "-o", "json", f.to_str().unwrap()]);
    assert_eq!(code1, 0);
    assert_eq!(code2, 0);
    assert_eq!(with_n, without_n, "-n should not affect JSON output");
}

// ------------------------------------------------------------------
// -s / --section
// ------------------------------------------------------------------

#[test]
fn section_extracts_named_section_only() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-s", "Installation", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(stdout.contains("Install steps here"));
    assert!(!stdout.contains("Some usage notes"));
}

#[test]
fn section_missing_exits_nonzero() {
    let f = fixture_file();
    let (_, stderr, code) = run(&["-s", "Nonexistent", f.to_str().unwrap()]);
    assert_ne!(code, 0, "missing section should exit nonzero");
    assert!(stderr.contains("not found"));
}

// ------------------------------------------------------------------
// --count
// ------------------------------------------------------------------

#[test]
fn count_reports_per_level_and_total() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["--count", f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert!(stdout.contains("#: 1"), "expected one h1");
    assert!(stdout.contains("##: 3"), "expected three h2");
    assert!(stdout.contains("###: 1"), "expected one h3");
    assert!(stdout.contains("Total: 5"));
}

// ------------------------------------------------------------------
// -q / query mode
// ------------------------------------------------------------------

#[test]
fn query_h2_returns_only_h2_headings() {
    let f = fixture_file();
    let (stdout, _, code) = run(&["-q", ".h2", f.to_str().unwrap()]);
    assert_eq!(code, 0, "stdout: {stdout}");
    // Should reference all three h2 headings.
    assert!(stdout.contains("Installation"));
    assert!(stdout.contains("Usage"));
    assert!(stdout.contains("Conclusion"));
    assert!(!stdout.contains("Advanced"), "h3 leaked into h2 query");
}

#[test]
fn query_invalid_syntax_exits_nonzero() {
    let f = fixture_file();
    let (_, stderr, code) = run(&["-q", ".h2 | nonexistent_fn(((", f.to_str().unwrap()]);
    assert_ne!(code, 0);
    assert!(!stderr.is_empty(), "expected an error message on stderr");
}

// ------------------------------------------------------------------
// stdin piping
// ------------------------------------------------------------------

#[test]
fn list_reads_markdown_from_stdin() {
    let input = "# Alpha\n## Beta\n";
    let (stdout, _, code) = run_with_stdin(&["-l", "-"], input);
    assert_eq!(code, 0, "stdout: {stdout}");
    let lines: Vec<_> = stdout.lines().collect();
    assert_eq!(lines.len(), 2);
    assert_eq!(lines[0], "# Alpha");
    assert_eq!(lines[1], "## Beta");
}

// ------------------------------------------------------------------
// --at-line
// ------------------------------------------------------------------

#[test]
fn at_line_finds_enclosing_heading() {
    let f = fixture_file();
    // 1-indexed line number of "## Usage" in FIXTURE.
    let usage_line = FIXTURE
        .lines()
        .position(|l| l.starts_with("## Usage"))
        .expect("Usage heading present")
        + 1;
    // A line *inside* the Usage section — should resolve to "## Usage".
    let target = usage_line + 1;
    let (stdout, stderr, code) = run(&["--at-line", &target.to_string(), f.to_str().unwrap()]);
    assert_eq!(code, 0, "stderr: {stderr}");
    assert_eq!(stdout.trim(), "## Usage");
}

#[test]
fn at_line_on_heading_line_returns_that_heading() {
    let f = fixture_file();
    let install_line = FIXTURE
        .lines()
        .position(|l| l.starts_with("## Installation"))
        .expect("Installation heading present")
        + 1;
    let (stdout, _, code) = run(&["--at-line", &install_line.to_string(), f.to_str().unwrap()]);
    assert_eq!(code, 0);
    assert_eq!(stdout.trim(), "## Installation");
}

#[test]
fn at_line_before_first_heading_exits_nonzero() {
    // First heading is on line 5; line 2 has no heading at or before it.
    let dir = std::env::temp_dir().join(format!("treemd-it-noheading-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("doc.md");
    std::fs::write(&path, "lorem\nipsum\ndolor\nsit\n# Hello\nbody\n").unwrap();
    let (_, stderr, code) = run(&["--at-line", "2", path.to_str().unwrap()]);
    assert_ne!(code, 0);
    assert!(stderr.contains("No heading"));
}

#[test]
fn at_line_zero_is_rejected() {
    let f = fixture_file();
    let (_, stderr, code) = run(&["--at-line", "0", f.to_str().unwrap()]);
    assert_ne!(code, 0);
    assert!(stderr.contains(">= 1"));
}

// ------------------------------------------------------------------
// -s with formatted heading text (regression: previously broken because
// main.rs::extract_section did string-search on heading.text, which is
// the stripped form, so `## **Bold** Section` was never found).
// ------------------------------------------------------------------

#[test]
fn section_with_inline_markdown_in_heading() {
    let dir = std::env::temp_dir().join(format!("treemd-it-fmt-{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let path = dir.join("doc.md");
    std::fs::write(
        &path,
        "# Top\n\n## **Bold** Section\nbody-of-bold\n\n## Next\nbody-of-next\n",
    )
    .unwrap();

    let (stdout, stderr, code) = run(&["-s", "Bold Section", path.to_str().unwrap()]);
    assert_eq!(code, 0, "stderr: {stderr}");
    assert!(
        stdout.contains("body-of-bold"),
        "expected body of formatted-heading section, got: {stdout:?}"
    );
    assert!(!stdout.contains("body-of-next"));
}