use std::ffi::CString;
use std::io::{self, Write};
use crate::error::{Error, Result};
pub struct CommandLineParser {
app_name: String,
app_version: String,
options: Vec<Box<CommandLineOption>>,
positionals: Vec<Box<CommandLinePositionalArgument>>,
}
impl CommandLineParser {
pub fn new() -> Self {
Self {
app_name: "quercus".to_string(),
app_version: String::new(),
options: Vec::new(),
positionals: Vec::new(),
}
}
pub fn set_app_info(&mut self, name: &str, version: &str) {
self.app_name = name.to_string();
self.app_version = version.to_string();
}
pub fn add_option(
&mut self,
names: &[CString],
description: &str,
takes_arg: bool,
arg_placeholder: &str,
hidden: bool,
) -> Result<()> {
let mut strings = Vec::with_capacity(names.len());
for n in names {
strings.push(n.to_str().map_err(|_| Error::Invalid)?.to_string());
}
self.options.push(Box::new(CommandLineOption {
names: strings,
description: description.to_string(),
takes_arg,
arg_placeholder: arg_placeholder.to_string(),
hidden,
is_set: false,
setting: None,
}));
Ok(())
}
pub fn add_positional_argument(
&mut self,
name: &str,
description: &str,
required: bool,
) -> Result<()> {
self.positionals
.push(Box::new(CommandLinePositionalArgument {
name: name.to_string(),
description: description.to_string(),
required,
setting: None,
}));
Ok(())
}
pub fn process(&mut self, argv: &[CString]) -> Result<()> {
let mut positional_index = 0usize;
let mut i = 1usize;
while i < argv.len() {
let arg_str = match argv[i].to_str() {
Ok(s) => s.to_string(),
Err(_) => {
eprintln!("Unknown parameter: {}", argv[i].to_string_lossy());
i += 1;
continue;
}
};
if !arg_str.is_empty() && arg_str.starts_with('-') {
let arg_basename = &arg_str[1..];
let mut matched_known = false;
let mut consume_next = false;
'find: for opt in self.options.iter_mut() {
for name in &opt.names {
if name.eq_ignore_ascii_case(arg_basename) {
opt.is_set = true;
if opt.takes_arg && i + 1 < argv.len() {
opt.setting = argv[i + 1].to_str().ok().map(str::to_owned);
consume_next = true;
}
matched_known = true;
break 'find;
}
}
}
if !matched_known {
eprintln!("Unknown parameter: {}", arg_str);
}
i += if consume_next { 2 } else { 1 };
} else {
if positional_index < self.positionals.len() {
self.positionals[positional_index].setting = Some(arg_str);
positional_index += 1;
} else {
eprintln!("Unknown parameter: {}", arg_str);
}
i += 1;
}
}
Ok(())
}
pub fn print_help(&self, filename: &str) -> Result<()> {
let stdout = io::stdout();
let mut out = stdout.lock();
self.write_help(&mut out, filename)
}
fn write_help<W: Write>(&self, out: &mut W, filename: &str) -> Result<()> {
let r = (|| -> io::Result<()> {
writeln!(out, "{} {}", self.app_name, self.app_version)?;
writeln!(out, "Copyright (C) 2018-2022 Quercus Video Editor Team")?;
let mut positional_args = String::new();
for (i, p) in self.positionals.iter().enumerate() {
if i > 0 {
positional_args.push(' ');
}
positional_args.push('[');
positional_args.push_str(&p.name);
positional_args.push(']');
}
let basename = match filename.rfind('/') {
Some(pos) => &filename[pos + 1..],
None => filename,
};
writeln!(out, "Usage: {} [options] {}\n", basename, positional_args)?;
for opt in &self.options {
if opt.hidden {
continue;
}
let mut all_args = String::new();
for (i, name) in opt.names.iter().enumerate() {
if i > 0 {
all_args.push_str(", ");
}
all_args.push('-');
all_args.push_str(name);
}
if opt.arg_placeholder.is_empty() {
writeln!(out, " {}", all_args)?;
} else {
writeln!(out, " {} <{}>", all_args, opt.arg_placeholder)?;
}
writeln!(out, " {}\n", opt.description)?;
}
writeln!(out)?;
Ok(())
})();
r.map_err(|e| Error::Failed(e.to_string()))
}
#[allow(dead_code)]
pub(crate) fn option_count(&self) -> usize {
self.options.len()
}
#[allow(dead_code)]
pub(crate) fn option(&self, index: usize) -> Option<&CommandLineOption> {
self.options.get(index).map(|b| b.as_ref())
}
#[allow(dead_code)]
pub(crate) fn option_mut(&mut self, index: usize) -> Option<&mut CommandLineOption> {
self.options.get_mut(index).map(|b| b.as_mut())
}
#[allow(dead_code)]
pub(crate) fn positional_count(&self) -> usize {
self.positionals.len()
}
#[allow(dead_code)]
pub(crate) fn positional(&self, index: usize) -> Option<&CommandLinePositionalArgument> {
self.positionals.get(index).map(|b| b.as_ref())
}
#[allow(dead_code)]
pub(crate) fn positional_mut(
&mut self,
index: usize,
) -> Option<&mut CommandLinePositionalArgument> {
self.positionals.get_mut(index).map(|b| b.as_mut())
}
}
impl Default for CommandLineParser {
fn default() -> Self {
Self::new()
}
}
pub struct CommandLineOption {
names: Vec<String>,
description: String,
takes_arg: bool,
arg_placeholder: String,
hidden: bool,
is_set: bool,
setting: Option<String>,
}
impl CommandLineOption {
pub fn is_set(&self) -> bool {
self.is_set
}
pub fn get_setting(&self) -> Result<&str> {
match &self.setting {
Some(v) => Ok(v.as_str()),
None => Ok(""),
}
}
pub fn set_setting(&mut self, value: &str) -> Result<()> {
self.setting = Some(value.to_string());
Ok(())
}
}
pub struct CommandLinePositionalArgument {
name: String,
#[allow(dead_code)] description: String,
#[allow(dead_code)] required: bool,
setting: Option<String>,
}
impl CommandLinePositionalArgument {
pub fn get_setting(&self) -> Result<&str> {
match &self.setting {
Some(v) => Ok(v.as_str()),
None => Ok(""),
}
}
pub fn set_setting(&mut self, value: &str) -> Result<()> {
self.setting = Some(value.to_string());
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cstr(s: &str) -> CString {
CString::new(s).unwrap()
}
#[test]
fn defaults() {
let p = CommandLineParser::new();
assert_eq!(p.app_name, "quercus");
assert_eq!(p.app_version, "");
assert_eq!(p.option_count(), 0);
assert_eq!(p.positional_count(), 0);
}
#[test]
fn set_app_info() {
let mut p = CommandLineParser::new();
p.set_app_info("myapp", "2.5");
assert_eq!(p.app_name, "myapp");
assert_eq!(p.app_version, "2.5");
}
#[test]
fn add_registers() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("h"), cstr("help")], "show help", false, "", false)
.unwrap();
p.add_option(&[cstr("o")], "output", true, "FILE", false)
.unwrap();
p.add_option(&[cstr("secret")], "hidden opt", false, "", true)
.unwrap();
p.add_positional_argument("input", "input file", true)
.unwrap();
p.add_positional_argument("output", "output file", false)
.unwrap();
assert_eq!(p.option_count(), 3);
assert_eq!(p.positional_count(), 2);
let opt = p.option(0).unwrap();
assert_eq!(opt.names, vec!["h".to_string(), "help".to_string()]);
assert!(!opt.takes_arg);
assert!(!opt.hidden);
assert!(!opt.is_set());
assert_eq!(opt.get_setting().unwrap(), "");
let opt = p.option(1).unwrap();
assert!(opt.takes_arg);
assert_eq!(opt.arg_placeholder, "FILE");
let opt = p.option(2).unwrap();
assert!(opt.hidden);
let pos = p.positional(0).unwrap();
assert_eq!(pos.name, "input");
assert!(pos.required);
assert_eq!(pos.get_setting().unwrap(), "");
}
#[test]
fn add_option_rejects_non_utf8_name() {
let mut p = CommandLineParser::new();
let bad = CString::new(vec![b'x', 0xFF, 0xFE]).unwrap();
assert!(matches!(
p.add_option(&[bad], "", false, "", false),
Err(Error::Invalid)
));
assert_eq!(p.option_count(), 0);
}
#[test]
fn option_setting_roundtrip() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
let opt = p.option_mut(0).unwrap();
assert_eq!(opt.get_setting().unwrap(), "");
opt.set_setting("value").unwrap();
assert_eq!(opt.get_setting().unwrap(), "value");
}
#[test]
fn positional_setting_roundtrip() {
let mut p = CommandLineParser::new();
p.add_positional_argument("in", "", true).unwrap();
let pos = p.positional_mut(0).unwrap();
assert_eq!(pos.get_setting().unwrap(), "");
pos.set_setting("file.mp4").unwrap();
assert_eq!(pos.get_setting().unwrap(), "file.mp4");
}
#[test]
fn process_flags_and_values() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("h"), cstr("help")], "", false, "", false)
.unwrap();
p.add_option(&[cstr("o")], "", true, "FILE", false).unwrap();
p.add_option(&[cstr("V")], "", false, "", false).unwrap();
p.add_positional_argument("input", "", true).unwrap();
let argv = [
cstr("prog"),
cstr("-help"),
cstr("-o"),
cstr("out.mov"),
cstr("-v"),
cstr("in.mp4"),
];
p.process(&argv).unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "");
assert!(p.option(1).unwrap().is_set());
assert_eq!(p.option(1).unwrap().get_setting().unwrap(), "out.mov");
assert!(p.option(2).unwrap().is_set());
assert_eq!(p.positional(0).unwrap().get_setting().unwrap(), "in.mp4");
}
#[test]
fn process_skips_program_name() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("x")], "", false, "", false).unwrap();
let argv = [cstr("prog"), cstr("-x")];
p.process(&argv).unwrap();
assert!(p.option(0).unwrap().is_set());
let argv = [cstr("prog")];
p.process(&argv).unwrap();
}
#[test]
fn process_takes_arg_at_end() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "FILE", false).unwrap();
let argv = [cstr("prog"), cstr("-o")];
p.process(&argv).unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "");
}
#[test]
fn process_accumulates_state() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
p.process(&[cstr("p"), cstr("-o"), cstr("a")]).unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "a");
p.process(&[cstr("p")]).unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "a");
}
#[test]
fn process_strips_single_dash() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
p.process(&[cstr("p"), cstr("--o"), cstr("v")]).unwrap();
assert!(!p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "");
}
#[test]
fn print_help_exact() {
let mut p = CommandLineParser::new();
p.set_app_info("quercus", "1.2.3");
p.add_option(
&[cstr("h"), cstr("help")],
"Show this help message.",
false,
"",
false,
)
.unwrap();
p.add_option(&[cstr("o")], "Output file.", true, "FILE", true)
.unwrap(); p.add_option(&[cstr("t")], "Time.", true, "SEC", false)
.unwrap();
p.add_positional_argument("input", "Input file", true)
.unwrap();
let mut buf = Vec::new();
p.write_help(&mut buf, "/usr/local/bin/quercus").unwrap();
let text = String::from_utf8(buf).unwrap();
let expected = "\
quercus 1.2.3
Copyright (C) 2018-2022 Quercus Video Editor Team
Usage: quercus [options] [input]
-h, -help
Show this help message.
-t <SEC>
Time.
";
assert_eq!(text, expected);
}
#[test]
fn print_help_bare_filename_and_default_version() {
let p = CommandLineParser::new();
let mut buf = Vec::new();
p.write_help(&mut buf, "quercus").unwrap();
let text = String::from_utf8(buf).unwrap();
assert!(text.starts_with("quercus \n"), "header was {:?}", &text[..12]);
assert!(text.contains("Usage: quercus [options] \n"));
}
#[test]
fn option_address_is_stable() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("a")], "", false, "", false).unwrap();
let first = p.option(0).unwrap() as *const CommandLineOption;
for i in 0..100 {
p.add_option(&[cstr(&format!("x{}", i))], "", false, "", false)
.unwrap();
}
assert_eq!(first, p.option(0).unwrap() as *const CommandLineOption);
}
#[test]
fn process_matches_any_registered_name() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("h"), cstr("help"), cstr("?")], "", false, "", false)
.unwrap();
p.process(&[cstr("p"), cstr("-?")]).unwrap();
assert!(p.option(0).unwrap().is_set());
}
#[test]
fn process_case_insensitive_full_name() {
for arg in ["-fullscreen", "-FULLSCREEN", "-Fullscreen"] {
let mut q = CommandLineParser::new();
q.add_option(&[cstr("FullScreen")], "", false, "", false)
.unwrap();
q.process(&[cstr("p"), cstr(arg)]).unwrap();
assert!(q.option(0).unwrap().is_set(), "arg {:?} did not match", arg);
}
}
#[test]
fn process_takes_arg_consumes_dash_value() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
p.add_option(&[cstr("h")], "", false, "", false).unwrap();
p.process(&[cstr("p"), cstr("-o"), cstr("-h")]).unwrap();
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "-h");
assert!(!p.option(1).unwrap().is_set());
}
#[test]
fn process_flag_does_not_consume_next() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("f")], "", false, "", false).unwrap();
p.add_positional_argument("input", "", true).unwrap();
p.process(&[cstr("p"), cstr("-f"), cstr("in.mp4")]).unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.positional(0).unwrap().get_setting().unwrap(), "in.mp4");
}
#[test]
fn process_duplicate_option_last_value_wins() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
p.process(&[cstr("p"), cstr("-o"), cstr("a"), cstr("-o"), cstr("b")])
.unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "b");
}
#[test]
fn process_positional_overflow_is_unknown() {
let mut p = CommandLineParser::new();
p.add_positional_argument("first", "", true).unwrap();
p.add_positional_argument("second", "", false).unwrap();
p.process(&[cstr("p"), cstr("1"), cstr("2"), cstr("3"), cstr("-x")])
.unwrap();
assert_eq!(p.positional(0).unwrap().get_setting().unwrap(), "1");
assert_eq!(p.positional(1).unwrap().get_setting().unwrap(), "2");
}
#[test]
fn process_empty_string_is_positional() {
let mut p = CommandLineParser::new();
p.add_positional_argument("input", "", false).unwrap();
p.process(&[cstr("p"), cstr("")]).unwrap();
assert_eq!(p.positional(0).unwrap().get_setting().unwrap(), "");
}
#[test]
fn process_bare_dash_is_unknown() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", false, "", false).unwrap();
p.add_positional_argument("input", "", false).unwrap();
p.process(&[cstr("p"), cstr("-")]).unwrap();
assert!(!p.option(0).unwrap().is_set());
assert_eq!(p.positional(0).unwrap().get_setting().unwrap(), "");
}
#[test]
fn process_no_double_dash_or_equals_syntax() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
p.process(&[cstr("p"), cstr("--o=v")]).unwrap();
assert!(!p.option(0).unwrap().is_set());
let mut q = CommandLineParser::new();
q.add_option(&[cstr("o")], "", true, "F", false).unwrap();
q.add_positional_argument("in", "", false).unwrap();
q.process(&[cstr("p"), cstr("--"), cstr("x")]).unwrap();
assert_eq!(q.positional(0).unwrap().get_setting().unwrap(), "x");
}
#[test]
fn process_first_matching_option_wins() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("x")], "", false, "", false).unwrap();
p.add_option(&[cstr("x")], "", false, "", false).unwrap();
p.process(&[cstr("p"), cstr("-x")]).unwrap();
assert!(p.option(0).unwrap().is_set());
assert!(!p.option(1).unwrap().is_set());
}
#[test]
fn unset_option_state() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
let opt = p.option(0).unwrap();
assert!(!opt.is_set());
assert_eq!(opt.get_setting().unwrap(), "");
}
#[test]
fn set_setting_does_not_mark_is_set() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
{
let opt = p.option_mut(0).unwrap();
opt.set_setting("v").unwrap();
}
let opt = p.option(0).unwrap();
assert!(!opt.is_set());
assert_eq!(opt.get_setting().unwrap(), "v");
}
#[test]
fn process_is_set_and_setting_combinations() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("f")], "", false, "", false).unwrap();
p.add_option(&[cstr("o")], "", true, "F", false).unwrap();
p.process(&[cstr("p"), cstr("-f"), cstr("-o"), cstr("v")])
.unwrap();
assert!(p.option(0).unwrap().is_set());
assert_eq!(p.option(0).unwrap().get_setting().unwrap(), "");
assert!(p.option(1).unwrap().is_set());
assert_eq!(p.option(1).unwrap().get_setting().unwrap(), "v");
}
#[test]
fn print_help_smoke() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("h")], "help", false, "", false)
.unwrap();
p.print_help("quercus").unwrap();
}
#[test]
fn print_help_placeholder_rules() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("a")], "arg without placeholder", true, "", false)
.unwrap();
p.add_option(&[cstr("b")], "placeholder without arg", false, "P", false)
.unwrap();
let mut buf = Vec::new();
p.write_help(&mut buf, "quercus").unwrap();
let text = String::from_utf8(buf).unwrap();
assert!(text.contains(" -a\n"), "{}", text);
assert!(text.contains(" -b <P>\n"), "{}", text);
}
#[test]
fn print_help_multiple_positionals() {
let mut p = CommandLineParser::new();
p.add_positional_argument("in", "", true).unwrap();
p.add_positional_argument("out", "", false).unwrap();
let mut buf = Vec::new();
p.write_help(&mut buf, "quercus").unwrap();
let text = String::from_utf8(buf).unwrap();
assert!(
text.contains("Usage: quercus [options] [in] [out]\n"),
"{}",
text
);
}
#[test]
fn hidden_option_parses_but_hidden_from_help() {
let mut p = CommandLineParser::new();
p.add_option(&[cstr("secret")], "shh", false, "", true)
.unwrap();
let mut buf = Vec::new();
p.write_help(&mut buf, "quercus").unwrap();
let text = String::from_utf8(buf).unwrap();
assert!(!text.contains("secret"), "{}", text);
p.process(&[cstr("p"), cstr("-secret")]).unwrap();
assert!(p.option(0).unwrap().is_set());
}
#[test]
fn index_accessors_out_of_range() {
let p = CommandLineParser::new();
assert!(p.option(0).is_none());
assert!(p.positional(0).is_none());
}
#[test]
fn add_option_empty_names_never_matches() {
let mut p = CommandLineParser::new();
p.add_option(&[], "no names", false, "", false).unwrap();
assert_eq!(p.option_count(), 1);
p.process(&[cstr("p"), cstr("-anything")]).unwrap();
assert!(!p.option(0).unwrap().is_set());
}
}