diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-09-29 14:36:40 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-09-29 14:36:40 +0200 |
| commit | 1f44aafa41174e7e8442179c526ed313d09e0bda (patch) | |
| tree | b95219dedb6c9a0ced532c144a0c52aa1ff8ac4b | |
| parent | 0ebdd46766744d649c93f4023d7f20cbfde51c1e (diff) | |
| download | ele-1f44aafa41174e7e8442179c526ed313d09e0bda.tar.gz ele-1f44aafa41174e7e8442179c526ed313d09e0bda.zip | |
Correct CLI information flags and reject unknown long options
| -rw-r--r-- | README.md | 3 | ||||
| -rw-r--r-- | src/main.rs | 29 | ||||
| -rw-r--r-- | tests/cli_tests.rs | 49 |
3 files changed, 79 insertions, 2 deletions
@@ -16,6 +16,8 @@ cargo install --path . usage: aip-filter [-p|--print] [--max-record-bytes N] [--] <expr> [file...] ``` +* `--help` and `--version` print information and exit successfully without reading input. +* Unknown long options fail. Use `--` before an expression that starts with `--`, including filter comments. * `--print` prints the parsed expression instead of evaluating it. * If no files are given, reads from stdin. * Input is newline-delimited JSON, with one value per line. Matching lines are preserved, with a newline inserted between records when a preceding input file has no trailing newline. A final unterminated record is otherwise left unchanged. @@ -23,6 +25,7 @@ usage: aip-filter [-p|--print] [--max-record-bytes N] [--] <expr> [file...] * Invalid JSON lines are reported and skipped. Any invalid JSON or input/output error causes a nonzero exit status. * Records are limited to 8 MiB by default, including the newline. `--max-record-bytes N` sets a positive byte limit. Oversized records are reported and skipped without buffering the rest of the line; later records are still processed and the exit status indicates failure. The limit does not apply to an empty filter, which copies bytes directly. * Memory depends on the largest allowed record and its parsed JSON values, not on the total number of records. The record limit is not a process-memory limit. +* Exit status is 0 for successful processing, even with no matches; 1 for filter, data, or I/O errors; and 2 for invalid command-line usage. ### Matching rules diff --git a/src/main.rs b/src/main.rs index ca62416..900ff88 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ use std::{ }; const DEFAULT_MAX_RECORD_BYTES: usize = 8 * 1024 * 1024; +const USAGE: &str = "[-p|--print] [--max-record-bytes N] [--] <expr> [file...]"; struct RecordOutput<W> { writer: W, @@ -70,10 +71,18 @@ fn filter_lines( } fn usage(program: &str) -> ! { - eprintln!("usage: {program} [-p|--print] [--max-record-bytes N] [--] <expr> [file...]"); + eprintln!("usage: {program} {USAGE}"); process::exit(2); } +fn print_info(program: &str, message: &str) { + let mut out = io::stdout().lock(); + if let Err(error) = writeln!(out, "{message}").and_then(|()| out.flush()) { + eprintln!("{program}: {error}"); + process::exit(1); + } +} + fn main() { let mut args = std::env::args(); let program = args.next().unwrap(); @@ -90,7 +99,23 @@ fn main() { .unwrap_or_else(|| usage(&program)); } "--" => break args.next().unwrap_or_else(|| usage(&program)), - "-h" | "--help" => usage(&program), + "-h" | "--help" => { + return print_info(&program, &format!( + "usage: {program} {USAGE}\n\n\ + -p, --print Print the parsed expression.\n\ + --max-record-bytes N Limit each record, including its newline (default: {DEFAULT_MAX_RECORD_BYTES}).\n\ + -h, --help Print help without reading input.\n\ + -V, --version Print the version without reading input.\n\ + -- End option parsing." + )); + } + "-V" | "--version" => { + return print_info(&program, concat!("aip-filter ", env!("CARGO_PKG_VERSION"))); + } + _ if arg.starts_with("--") => { + eprintln!("{program}: unknown option: {arg}; use -- before a literal expression"); + usage(&program); + } _ => break arg, } }; diff --git a/tests/cli_tests.rs b/tests/cli_tests.rs index c283e19..c195c5c 100644 --- a/tests/cli_tests.rs +++ b/tests/cli_tests.rs @@ -154,6 +154,43 @@ fn empty_filter_and_print_mode() { } #[test] +fn information_flags_succeed_and_unknown_long_options_fail() { + for flag in ["--help", "-h", "--version", "-V"] { + let output = Command::new(env!("CARGO_BIN_EXE_aip-filter")) + .arg(flag) + .stdin(Stdio::null()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(0), "{flag}"); + assert!(output.stderr.is_empty()); + let text = String::from_utf8(output.stdout).unwrap(); + if matches!(flag, "--help" | "-h") { + assert!(text.contains("usage:")); + assert!(text.contains("--max-record-bytes")); + assert!(text.contains("--version")); + } else { + assert_eq!(text, format!("aip-filter {}\n", env!("CARGO_PKG_VERSION"))); + } + } + for flag in ["--verison", "--unknown", "--print=invalid"] { + let output = Command::new(env!("CARGO_BIN_EXE_aip-filter")) + .arg(flag) + .stdin(Stdio::null()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(2), "{flag}"); + assert!(output.stdout.is_empty()); + assert!(String::from_utf8_lossy(&output.stderr).contains("unknown option")); + } + let output = run("-- literal comment", "raw input\n", &["--"]); + assert!(output.status.success()); + assert_eq!(output.stdout, b"raw input\n"); + let output = run("-p", "\"unrelated\"\n", &["--"]); + assert!(output.status.success()); + assert_eq!(output.stdout, b"\"unrelated\"\n"); +} + +#[test] fn invalid_json_is_reported_and_returns_failure() { let output = run("foobar", "not json\n{\"msg\":\"foobar\"}\n", &[]); assert!(!output.status.success()); @@ -305,4 +342,16 @@ fn output_flush_errors_are_reported() { .write_all(b"{\"msg\":\"foobar\"}\n") .unwrap(); assert!(!child.wait_with_output().unwrap().status.success()); + for flag in ["--help", "--version"] { + let (writer, reader) = UnixStream::pair().unwrap(); + drop(reader); + let output = Command::new(env!("CARGO_BIN_EXE_aip-filter")) + .arg(flag) + .stdin(Stdio::null()) + .stdout(Stdio::from(OwnedFd::from(writer))) + .stderr(Stdio::piped()) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + } } |
