docextract 0.4.0

documentation extractor
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
//! CLI integration tests for the `cargo-docextract` binary.
//!
//! These tests spawn the compiled binary via
//! `env!("CARGO_BIN_EXE_cargo-docextract")` (set by Cargo for integration
//! tests when the `[[bin]]` target exists) and exercise argument parsing, I/O
//! routing, error reporting, and exit code behavior per cli-spec.md §10.
//!
//! RED phase: `src/main.rs` is currently a no-op stub, so every test below
//! fails — that is the expected and desired state before implementation.
//!
//! Conventions (matching `tests/integration_tests.rs` and `src/lib.rs`):
//! - Each test creates its own unique temp directory (parallel-safe).
//! - Every test comments the REQ-ID / spec section it traces to.
//! - Root-independence: permission-based failures (EACCES) are bypassed when
//!   running as root, so "cannot create output" / "cannot read input" are
//!   tested deterministically with an existing directory (EISDIR on create /
//!   read), the same pattern already established in `src/lib.rs` (b08).
#![allow(clippy::unwrap_used)]

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

/// Path to the compiled `cargo-docextract` binary, provided by Cargo at
/// compile time for integration tests.
const BIN: &str = env!("CARGO_BIN_EXE_cargo-docextract");

/// The verbatim help text from cli-spec.md §5.3 — byte-for-byte.
///
/// Notes per spec: plain ASCII hyphen-minus on the first line; the Unicode
/// RIGHTWARDS ARROW (`→`, U+2192) in the "Pipe stdin → stdout" example; every
/// line ends with LF; two-space indentation in Arguments/Examples; no
/// trailing spaces; the final blank line before EOF is significant.
const EXPECTED_HELP: &str = "\
cargo-docextract - extract //// documentation from Rust source files

Usage: cargo-docextract <output> [inputs...]

Arguments:
  <output>       Output file path, or '-' for stdout (mandatory).
                 Prefix with 'filter@' for output filtering,
                 e.g., 'chapter.*@output.md'.
  [inputs...]    Input file paths, or '-' for stdin (zero or more).
                 Prefix with 'filter@' to filter by tag pattern,
                 e.g., 'api@src/lib.rs'.

Tag filtering:
  Lines can be tagged with ////tagname directives in source files.
  Use 'filter@path' to extract only lines matching a pattern.
  Multiple filtered reads of the same file reorder output.
  Without '@', behavior is identical to before.

Examples:
  cargo-docextract docs.md src/macros.rs      Extract from one file
  cargo-docextract - src/macros.rs            Extract to stdout
  cargo-docextract api@docs.md src/lib.rs     Filter by 'api' tag
  cargo-docextract 'chapter.*'@out.md chapter1@in.rs chapter2@in.rs
  cargo-docextract -                          Pipe stdin → stdout
  cargo-docextract --help                     Print this help

There are no options or flags. All arguments are positional.

";

/// Unique per-test temp directory; removed on drop (also on panic).
struct TempDir(PathBuf);

impl TempDir {
    fn new(name: &str) -> TempDir {
        let dir = std::env::temp_dir().join(format!(
            "docextract-cli-{}-pid{}-{:?}",
            name,
            std::process::id(),
            std::thread::current().id(),
        ));
        fs::create_dir_all(&dir).unwrap();
        TempDir(dir)
    }

    fn file(&self, name: &str) -> PathBuf {
        self.0.join(name)
    }

    fn write(&self, name: &str, content: &str) -> PathBuf {
        let path = self.file(name);
        fs::write(&path, content).unwrap();
        path
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn read_str(path: &Path) -> String {
    fs::read_to_string(path).unwrap()
}

/// Run the binary with null stdin (tests that don't read stdin).
fn run(args: &[&str]) -> Output {
    Command::new(BIN)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap()
}

/// Run the binary with the given stdin content piped in (closed before
/// waiting, so the child sees EOF — required for `-` input tests).
///
/// The stdin write is best-effort: during RED the stub binary exits without
/// reading stdin, so the pipe is already closed and `write_all` would fail
/// with `BrokenPipe`. Ignoring that write error lets the behavioral assertions
/// below produce the meaningful failure; once the CLI reads stdin to EOF the
/// write succeeds.
fn run_with_stdin(args: &[&str], input: &str) -> Output {
    let mut child = Command::new(BIN)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    {
        let mut stdin = child.stdin.take().expect("stdin is piped");
        let _ = stdin.write_all(input.as_bytes());
    }
    child.wait_with_output().unwrap()
}

/// Run the binary with a specific working directory (for flag-like file-path
/// tests, so the created file lands inside the test's temp dir).
fn run_in_dir(args: &[&str], dir: &Path) -> Output {
    Command::new(BIN)
        .current_dir(dir)
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .unwrap()
}

// --- T01-T22: CLI behavior per cli-spec.md §10.1 ---

#[test]
fn cli_zero_args_prints_help_and_exits_0() {
    // REQ-CLI-F-008 / §5.1: zero arguments prints help to stdout, exit 0.
    let output = run(&[]);
    assert_eq!(output.status.code(), Some(0), "exit code must be 0");
    assert!(
        output.status.success(),
        "zero-argument invocation must succeed"
    );
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        EXPECTED_HELP,
        "help text must go to stdout verbatim"
    );
    assert!(
        output.stderr.is_empty(),
        "help must not produce stderr output"
    );
}

#[test]
fn cli_help_flag_prints_help_and_exits_0() {
    // REQ-CLI-F-009 / §5.1: `--help` prints help to stdout, exit 0.
    let output = run(&["--help"]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(
        String::from_utf8_lossy(&output.stdout),
        EXPECTED_HELP,
        "--help must print the exact help text"
    );
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_help_anywhere_in_args_prints_help() {
    // REQ-CLI-F-009 / §2.3 + §13.3: `--help` at any position (first, middle,
    // last) triggers help; all other arguments are ignored. Spec rows:
    // `cargo-docextract output.md --help` and `cargo-docextract --help output.md`.
    let tmp = TempDir::new("help-anywhere");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    // --help last: output.md must be ignored (not created).
    let last = run(&[out_str, "--help"]);
    assert_eq!(last.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&last.stdout), EXPECTED_HELP);
    assert!(
        !out.exists(),
        "output argument must be ignored when --help is present"
    );

    // --help first: same result.
    let first = run(&["--help", out_str]);
    assert_eq!(first.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&first.stdout), EXPECTED_HELP);
    assert!(!out.exists());

    // --help in the middle of input args.
    let middle = run(&[out_str, "--help", out_str]);
    assert_eq!(middle.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&middle.stdout), EXPECTED_HELP);
    assert!(!out.exists());
}

#[test]
fn cli_single_file_input_extracts_to_output_file() {
    // REQ-CLI-F-001 / C03: `cargo-docextract output.md src.rs` writes
    // extracted docs to the file, exit 0.
    let tmp = TempDir::new("single-file");
    let src = tmp.write("test.rs", "//// Hello World\nfn main() {}\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, src.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert!(output.stderr.is_empty(), "no warnings expected");
    assert!(
        output.stdout.is_empty(),
        "file output must not leak to stdout"
    );
    assert_eq!(read_str(&out), "Hello World\n");
}

#[test]
fn cli_multiple_inputs_concatenated_no_separator() {
    // REQ-CLI-F-002 / C10: multiple input files → blocks concatenated in
    // order with no inter-file separator, exit 0.
    let tmp = TempDir::new("multi-file");
    let a = tmp.write("a.rs", "//// From A\n");
    let b = tmp.write("b.rs", "//// From B\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, a.to_str().unwrap(), b.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(read_str(&out), "From A\nFrom B\n");
}

#[test]
fn cli_dash_output_writes_to_stdout() {
    // REQ-CLI-F-004 / C04: `cargo-docextract - src.rs` writes extracted docs
    // to stdout, exit 0, and creates no file named "-".
    let tmp = TempDir::new("dash-output");
    let src = tmp.write("test.rs", "//// To stdout\n");

    let output = run(&["-", src.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&output.stdout), "To stdout\n");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_dash_input_reads_from_stdin() {
    // REQ-CLI-F-005 / C05: `echo "//// Hello" | cargo-docextract out.md -`
    // reads stdin and writes the file, exit 0.
    let tmp = TempDir::new("dash-input");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run_with_stdin(&[out_str, "-"], "//// Hello\n");
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(read_str(&out), "Hello\n");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_lone_dash_stdin_to_stdout_shorthand() {
    // REQ-CLI-F-004 + REQ-CLI-F-005 / C07 + §4.3: a single `-` alone implies
    // output=stdout and input=stdin (pipe pass-through), exit 0.
    let output = run_with_stdin(&["-"], "//// Shorthand\n");
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&output.stdout), "Shorthand\n");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_explicit_dash_dash_stdin_to_stdout() {
    // REQ-CLI-F-004 + REQ-CLI-F-005 / C06 + §4.2: `cargo-docextract - -`
    // reads stdin and writes stdout, exit 0.
    let output = run_with_stdin(&["-", "-"], "//// Explicit\n");
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(String::from_utf8_lossy(&output.stdout), "Explicit\n");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_missing_input_warns_and_continues() {
    // REQ-CLI-F-006 / C14 + §4.5: missing input file → warning to stderr,
    // remaining files still processed, exit 0.
    let tmp = TempDir::new("missing-input");
    let valid = tmp.write("valid.rs", "//// From Valid\n");
    let missing = tmp.file("missing.rs");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, missing.to_str().unwrap(), valid.to_str().unwrap()]);
    assert_eq!(
        output.status.code(),
        Some(0),
        "exit 0 when some inputs succeed"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("warning: input file not found:") && stderr.contains("missing.rs"),
        "missing file warning must reference the file, got: {stderr}"
    );
    assert_eq!(
        read_str(&out),
        "From Valid\n",
        "valid file must still be processed"
    );
}

#[test]
fn cli_input_read_error_exits_2() {
    // REQ-CLI-F-010 / C16 + §4.6 + §7.3: an input that exists but cannot be
    // read → error to stderr, exit 2. Root-independent: an existing directory
    // passes the CLI's exists() pre-check, then File::open succeeds and the
    // read yields EISDIR (same pattern as src/lib.rs b08).
    let tmp = TempDir::new("read-error");
    let dir_input = tmp.file("a_directory");
    fs::create_dir_all(&dir_input).unwrap();
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, dir_input.to_str().unwrap()]);
    assert_eq!(
        output.status.code(),
        Some(2),
        "input read error must exit 2"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("cargo-docextract: error:") && stderr.contains("Is a directory"),
        "input read error must be reported to stderr, got: {stderr}"
    );
}

#[test]
fn cli_output_create_error_exits_2() {
    // REQ-CLI-F-010 / C13 + §3.3 + §7.1: output file cannot be created →
    // error to stderr, exit 2. Root-independent: an existing directory cannot
    // be File::create'd (EISDIR), regardless of privileges.
    let tmp = TempDir::new("output-error");
    let out_dir = tmp.file("out_dir");
    fs::create_dir_all(&out_dir).unwrap();
    let src = tmp.write("test.rs", "//// Doc\n");

    let output = run(&[out_dir.to_str().unwrap(), src.to_str().unwrap()]);
    assert_eq!(
        output.status.code(),
        Some(2),
        "output create failure must exit 2"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("cargo-docextract: error:") && stderr.contains("Is a directory"),
        "output create error must be reported to stderr, got: {stderr}"
    );
}

#[test]
#[cfg(target_os = "linux")]
fn cli_output_flush_error_exits_2() {
    // REQ-CLI-F-010 + REQ-CLI-F-011 / C17 + §7.5: output write/flush error
    // (disk full via /dev/full) → `cargo-docextract: error: output: {msg}` to
    // stderr, exit 2. /dev/full returns ENOSPC ("No space left on device") on
    // flush — same pattern already established in src/lib.rs.
    let dir = TempDir::new("flush-error");
    let src = dir.path().join("src.rs");
    std::fs::write(&src, "//// Hello\n").unwrap();

    let output = run(&["/dev/full", src.to_str().unwrap()]);

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("error: output:"));
    assert!(stderr.contains("No space left on device"));
}

#[test]
#[cfg(target_os = "linux")]
fn cli_stdout_flush_error_exits_2() {
    // REQ-CLI-F-010 + REQ-CLI-F-011 / §7.5: with `-` as the output target
    // (stdout), a stdout flush failure (disk full via /dev/full) →
    // `cargo-docextract: error: output: {msg}` to stderr, exit 2.
    //
    // Mutation-killer: `OutputTarget::flush` replaced with `Ok(())` (the
    // library's flush error path). The doc line deliberately has NO trailing
    // newline: the 32 KiB BufWriter holds it, so the ENOSPC is only reached
    // when `.done()` flushes the *inner* Stdout (LineWriter flush) — the
    // exact `flush` code path the mutation targets. A trailing newline would
    // instead surface the error on the write path, which the mutation does
    // not touch (cf. cli_output_flush_error_exits_2, which catches only the
    // file-write path).
    //
    // The /dev/full handle is opened O_WRONLY: `File::open` would be O_RDONLY
    // and writes would fail with EBADF (silently ignored), not ENOSPC.
    let tmp = TempDir::new("stdout-flush-error");
    let src = tmp.write("eof.rs", "//// Hello"); // no trailing newline
    let dev_full = std::fs::OpenOptions::new()
        .write(true)
        .open("/dev/full")
        .unwrap();

    let output = Command::new(BIN)
        .args(["-", src.to_str().unwrap()])
        .stdin(Stdio::null())
        .stdout(Stdio::from(dev_full))
        .stderr(Stdio::piped())
        .output()
        .unwrap();

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("error: output:"));
    assert!(stderr.contains("No space left on device"));
}

#[test]
fn cli_zero_inputs_creates_empty_output_file() {
    // REQ-CLI-F-002 / C08 + §4.4: `cargo-docextract out.md` (no inputs)
    // creates an empty output file, exit 0.
    let tmp = TempDir::new("zero-inputs");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str]);
    assert_eq!(output.status.code(), Some(0));
    assert!(
        out.exists(),
        "output file must be created even with zero inputs"
    );
    assert_eq!(read_str(&out), "", "output must be empty");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_empty_input_file_produces_empty_output() {
    // REQ-F-015 analog at the CLI level: an empty input file yields an empty
    // (but created) output and no error, exit 0.
    let tmp = TempDir::new("empty-input");
    let empty = tmp.write("empty.rs", "");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, empty.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert!(out.exists());
    assert_eq!(read_str(&out), "");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_mixed_valid_and_missing_inputs() {
    // REQ-CLI-F-006 / C14 + §4.5: valid/missing/valid — the missing file
    // warns and is skipped; both valid files are processed in order, exit 0.
    let tmp = TempDir::new("mixed-inputs");
    let a = tmp.write("a.rs", "//// From A\n");
    let missing = tmp.file("missing.rs");
    let b = tmp.write("b.rs", "//// From B\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[
        out_str,
        a.to_str().unwrap(),
        missing.to_str().unwrap(),
        b.to_str().unwrap(),
    ]);
    assert_eq!(output.status.code(), Some(0));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("warning: input file not found:"),
        "got: {stderr}"
    );
    assert_eq!(read_str(&out), "From A\nFrom B\n");
}

#[test]
fn cli_all_inputs_missing_exits_2() {
    // REQ-CLI-F-007 / C15 + §4.5 + §7.6: all inputs missing → warning for
    // each, error message to stderr, exit 2.
    let dir = TempDir::new("all-missing");
    let out = dir.path().join("out.md");
    let missing1 = dir.path().join("nonexistent1.rs");
    let missing2 = dir.path().join("nonexistent2.rs");

    let output = run(&[
        out.to_str().unwrap(),
        missing1.to_str().unwrap(),
        missing2.to_str().unwrap(),
    ]);

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(stderr.contains("warning:"));
    assert!(stderr.contains("nonexistent1.rs"));
    assert!(stderr.contains("nonexistent2.rs"));
    assert!(stderr.contains("no input files could be read"));
}

#[test]
fn cli_stdin_and_file_combined() {
    // REQ-CLI-F-005 + REQ-CLI-F-002 / C20-style + §4: file input and `-`
    // stdin input combined in one invocation, in order, no separator.
    let tmp = TempDir::new("stdin-file");
    let file = tmp.write("file.rs", "//// From File\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run_with_stdin(&[out_str, file.to_str().unwrap(), "-"], "//// From stdin\n");
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(read_str(&out), "From File\nFrom stdin\n");
}

#[test]
fn cli_duplicate_stdin_reads_once() {
    // REQ-CLI-F-005 / C20 + §4.7 + §13.6: `-` appearing multiple times reads
    // stdin exactly once; subsequent `-` entries are no-ops (stdin_consumed).
    // Output must contain the stdin content once, not duplicated.
    let dir = TempDir::new("dup-stdin");
    let out = dir.path().join("out.md");

    let output = run_with_stdin(&[out.to_str().unwrap(), "-", "-"], "//// Once\n");

    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(stdout, ""); // output goes to file
    let result = std::fs::read_to_string(&out).unwrap();
    assert_eq!(result, "Once\n"); // Only once, not duplicated
    assert!(String::from_utf8_lossy(&output.stderr).is_empty());
}

#[test]
fn cli_help_text_matches_spec_exactly() {
    // REQ-CLI-F-008 / C21 + §5.3: the help text is byte-for-byte the
    // specified string — including the LF endings, the two-space indentation,
    // the Unicode arrow (→), and the final blank line before EOF.
    let output = run(&["--help"]);
    assert_eq!(output.status.code(), Some(0));
    let stdout = String::from_utf8_lossy(&output.stdout);

    assert_eq!(stdout, EXPECTED_HELP, "help must match spec §5.3 exactly");
    // Character-by-character notes from spec §5.3:
    assert!(
        stdout.starts_with("cargo-docextract - extract //// documentation"),
        "first line uses ASCII hyphen-minus"
    );
    assert!(
        stdout.contains("Pipe stdin → stdout"),
        "example must contain the Unicode RIGHTWARDS ARROW"
    );
    assert!(
        stdout.ends_with("All arguments are positional.\n\n"),
        "final blank line before EOF is significant"
    );
    assert!(!stdout.contains('\r'), "help must use LF line endings only");
    assert!(output.stderr.is_empty());
}

#[test]
fn cli_flag_like_args_treated_as_file_paths() {
    // REQ-CLI-F-003 / C18-C19 + §5.4: only `--help` (exact match) triggers
    // help. `-h`, `-v`, `--version`, and `--` are treated as file paths — here
    // as the output argument, which must create a file of that name and print
    // no help. Each runs in its own temp dir so the file lands there.
    for flag in ["-h", "-v", "--version", "--"] {
        let tmp = TempDir::new("flag-as-path");
        let output = run_in_dir(&[flag], tmp.path());
        assert_eq!(
            output.status.code(),
            Some(0),
            "`{flag}` as output path must not trigger help or error in a writable dir"
        );
        assert!(
            output.stdout.is_empty(),
            "`{flag}` must not print help text (got stdout: {:?})",
            String::from_utf8_lossy(&output.stdout)
        );
        assert!(
            tmp.file(flag).exists(),
            "`{flag}` must be treated as an output file path and created"
        );
    }
}

#[test]
fn cli_output_overwrites_existing_file() {
    // REQ-CLI-F-001 + §3.1: output file is truncated on open — pre-existing
    // content is replaced by the extraction result.
    let tmp = TempDir::new("overwrite");
    let src = tmp.write("test.rs", "//// Fresh\n");
    let out = tmp.file("out.md");
    fs::write(&out, "stale content that must be truncated\n").unwrap();
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, src.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(read_str(&out), "Fresh\n", "stale content must be truncated");
}

#[test]
fn cli_crlf_line_endings_preserved() {
    // REQ-CLI-F-017 analog (§9.2): the CLI passes line endings through
    // transparently — CRLF input yields CRLF output.
    let tmp = TempDir::new("crlf");
    let src = tmp.write("crlf.rs", "//// First\r\n//// Second\r\nlet x = 1;\r\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, src.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    let bytes = fs::read(&out).unwrap();
    assert_eq!(
        String::from_utf8_lossy(&bytes),
        "First\r\nSecond\r\n",
        "CRLF endings must be preserved verbatim"
    );
}

#[test]
fn cli_empty_doc_line_produces_verbatim_blank_line() {
    // §2 (AGENTS.md): `////` alone produces a verbatim blank line inside the
    // block — the line is a doc line, not a block separator.
    let tmp = TempDir::new("empty-doc-line");
    let src = tmp.write("blank.rs", "//// First\n////\n//// Second\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, src.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    assert_eq!(
        read_str(&out),
        "First\n\nSecond\n",
        "//// must emit a verbatim blank line inside the block"
    );
}

#[test]
fn cli_no_whitespace_doc_line_ignored() {
    // §2 (AGENTS.md): `////Text` (no whitespace after the slashes) is
    // silently ignored — it contributes nothing to the output.
    let tmp = TempDir::new("no-whitespace");
    let src = tmp.write("bad.rs", "////Text\n//// Kept\n");
    let out = tmp.file("out.md");
    let out_str = out.to_str().unwrap();

    let output = run(&[out_str, src.to_str().unwrap()]);
    assert_eq!(output.status.code(), Some(0));
    let extracted = read_str(&out);
    assert_eq!(extracted, "Kept\n");
    assert!(
        !extracted.contains("Text"),
        "////Text must be silently ignored"
    );
}