#![allow(clippy::unwrap_used)]
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
const BIN: &str = env!("CARGO_BIN_EXE_cargo-docextract");
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.
";
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()
}
fn run(args: &[&str]) -> Output {
Command::new(BIN)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.unwrap()
}
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()
}
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()
}
#[test]
fn cli_zero_args_prints_help_and_exits_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() {
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() {
let tmp = TempDir::new("help-anywhere");
let out = tmp.file("out.md");
let out_str = out.to_str().unwrap();
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"
);
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());
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
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() {
let tmp = TempDir::new("stdout-flush-error");
let src = tmp.write("eof.rs", "//// Hello"); 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() {
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() {
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() {
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() {
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() {
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() {
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, ""); let result = std::fs::read_to_string(&out).unwrap();
assert_eq!(result, "Once\n"); assert!(String::from_utf8_lossy(&output.stderr).is_empty());
}
#[test]
fn cli_help_text_matches_spec_exactly() {
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");
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() {
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() {
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() {
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() {
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() {
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"
);
}