use clap::ArgMatches;
use std::env;
use std::error::Error;
pub const ARG_COL: &str = "cols";
pub const ARG_LEN: &str = "len";
pub const ARG_FMT: &str = "format";
pub const ARG_INP: &str = "INPUTFILE";
pub const ARG_CLR: &str = "color";
pub const ARG_ARR: &str = "array";
pub const ARG_FNC: &str = "func";
pub const ARG_PLC: &str = "places";
pub const ARG_PFX: &str = "prefix";
const ARGS: [&str; 9] = [
ARG_COL, ARG_LEN, ARG_FMT, ARG_INP, ARG_CLR, ARG_ARR, ARG_FNC, ARG_PLC, ARG_PFX,
];
#[allow(clippy::absurd_extreme_comparisons)]
pub fn is_stdin(matches: ArgMatches) -> Result<bool, Box<dyn Error>> {
let mut is_stdin = false;
if let Some(_file) = matches.get_one::<String>(ARG_INP) {
is_stdin = false;
} else if !matches.args_present() {
is_stdin = true;
} else if let Some(_nth1) = env::args().nth(1) {
is_stdin = ARGS.iter().any(|arg| {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
matches.contains_id(arg) && matches.index_of(arg) == Some(2)
}))
.unwrap_or(false)
});
}
Ok(is_stdin)
}
#[cfg(test)]
mod tests {
use super::*;
use clap::{Arg, Command};
fn create_test_app() -> Command {
Command::new("test")
.arg(Arg::new(ARG_INP).index(1))
.arg(Arg::new(ARG_COL).short('c').long(ARG_COL))
.arg(Arg::new(ARG_LEN).short('l').long(ARG_LEN))
}
#[test]
fn test_is_stdin_with_file() {
let app = create_test_app();
let matches = app.try_get_matches_from(vec!["test", "file.txt"]).unwrap();
let result = is_stdin(matches).unwrap();
assert!(!result);
}
#[test]
fn test_is_stdin_no_args() {
let app = create_test_app();
let matches = app.try_get_matches_from(vec!["test"]).unwrap();
let result = is_stdin(matches).unwrap();
assert!(result);
}
#[test]
fn test_is_stdin_with_flags() {
let app = create_test_app();
let matches = app.try_get_matches_from(vec!["test", "-c", "10"]).unwrap();
let result = is_stdin(matches);
assert!(result.is_ok());
}
#[test]
fn test_arg_constants() {
assert_eq!(ARG_COL, "cols");
assert_eq!(ARG_LEN, "len");
assert_eq!(ARG_FMT, "format");
assert_eq!(ARG_INP, "INPUTFILE");
assert_eq!(ARG_CLR, "color");
assert_eq!(ARG_ARR, "array");
assert_eq!(ARG_FNC, "func");
assert_eq!(ARG_PLC, "places");
assert_eq!(ARG_PFX, "prefix");
}
}