#![deny(missing_docs)]
use self::Name::*;
use self::HasArg::*;
use self::Occur::*;
use self::Fail::*;
use self::Optval::*;
use self::SplitWithinState::*;
use self::Whitespace::*;
use self::LengthLimit::*;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt;
use std::iter::{repeat, IntoIterator};
use std::result;
pub struct Options {
grps: Vec<OptGroup>,
}
impl Default for Options {
fn default() -> Self {
Self {
grps: Vec::new(),
}
}
}
impl Options {
pub fn new() -> Options {
Self::default()
}
pub fn opt(&mut self, short_name: &str, long_name: &str, desc: &str,
hint: &str, hasarg: HasArg, occur: Occur) -> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: hint.to_string(),
desc: desc.to_string(),
hasarg,
occur
});
self
}
pub fn optflag(&mut self, short_name: &str, long_name: &str, desc: &str)
-> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: "".to_string(),
desc: desc.to_string(),
hasarg: No,
occur: Optional
});
self
}
pub fn optflagmulti(&mut self, short_name: &str, long_name: &str, desc: &str)
-> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: "".to_string(),
desc: desc.to_string(),
hasarg: No,
occur: Multi
});
self
}
pub fn optflagopt(&mut self, short_name: &str, long_name: &str, desc: &str,
hint: &str) -> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: hint.to_string(),
desc: desc.to_string(),
hasarg: Maybe,
occur: Optional
});
self
}
pub fn optmulti(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str)
-> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: hint.to_string(),
desc: desc.to_string(),
hasarg: Yes,
occur: Multi
});
self
}
pub fn optopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str)
-> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: hint.to_string(),
desc: desc.to_string(),
hasarg: Yes,
occur: Optional
});
self
}
pub fn reqopt(&mut self, short_name: &str, long_name: &str, desc: &str, hint: &str)
-> &mut Options {
validate_names(short_name, long_name);
self.grps.push(OptGroup {
short_name: short_name.to_string(),
long_name: long_name.to_string(),
hint: hint.to_string(),
desc: desc.to_string(),
hasarg: Yes,
occur: Req
});
self
}
pub fn parse<C: IntoIterator>(&self, args: C) -> Result
where C::Item: AsRef<OsStr>
{
let opts: Vec<Opt> = self.grps.iter().map(|x| x.long_to_short()).collect();
let mut vals = (0 .. opts.len()).map(|_| Vec::new()).collect::<Vec<Vec<Optval>>>();
let mut free: Vec<String> = Vec::new();
let args = args.into_iter().map(|i| {
i.as_ref().to_str().ok_or_else(|| {
Fail::UnrecognizedOption(format!("{:?}", i.as_ref()))
}).map(|s| s.to_owned())
}).collect::<::std::result::Result<Vec<_>,_>>()?;
let mut args = args.into_iter().peekable();
while let Some(cur) = args.next() {
if !is_arg(&cur) {
free.push(cur);
} else if cur == "--" {
free.extend(args);
break;
} else {
let mut names;
let mut i_arg = None;
let mut was_long = true;
if cur.as_bytes()[1] == b'-' {
let tail = &cur[2..];
let mut parts = tail.splitn(2, '=');
names = vec![Name::from_str(parts.next().unwrap())];
if let Some(rest) = parts.next() {
i_arg = Some(rest.to_string());
}
} else {
was_long = false;
names = Vec::new();
for (j, ch) in cur.char_indices().skip(1) {
let opt = Short(ch);
let opt_id = match find_opt(&opts, &opt) {
Some(id) => id,
None => return Err(UnrecognizedOption(opt.to_string()))
};
names.push(opt);
let arg_follows = match opts[opt_id].hasarg {
Yes | Maybe => true,
No => false
};
if arg_follows {
let next = j + ch.len_utf8();
if next < cur.len() {
i_arg = Some(cur[next..].to_string());
break;
}
}
}
}
let mut name_pos = 0;
for nm in &names {
name_pos += 1;
let optid = match find_opt(&opts, &nm) {
Some(id) => id,
None => return Err(UnrecognizedOption(nm.to_string()))
};
match opts[optid].hasarg {
No => {
if name_pos == names.len() && i_arg.is_some() {
return Err(UnexpectedArgument(nm.to_string()));
}
vals[optid].push(Given);
}
Maybe => {
if let Some(i_arg) = i_arg.take() {
vals[optid].push(Val(i_arg));
} else if was_long || name_pos < names.len() || args.peek().map_or(true, |n| is_arg(&n)) {
vals[optid].push(Given);
} else {
vals[optid].push(Val(args.next().unwrap()));
}
}
Yes => {
if let Some(i_arg) = i_arg.take() {
vals[optid].push(Val(i_arg));
} else if let Some(n) = args.next() {
vals[optid].push(Val(n));
} else {
return Err(ArgumentMissing(nm.to_string()));
}
}
}
}
}
}
debug_assert_eq!(vals.len(), opts.len());
for (vals, opt) in vals.iter().zip(opts.iter()) {
if opt.occur == Req && vals.is_empty() {
return Err(OptionMissing(opt.name.to_string()));
}
if opt.occur != Multi && vals.len() > 1 {
return Err(OptionDuplicated(opt.name.to_string()));
}
}
Ok(Matches {
opts,
vals,
free
})
}
pub fn short_usage(&self, program_name: &str) -> String {
let mut line = format!("Usage: {} ", program_name);
line.push_str(&self.grps.iter()
.map(format_option)
.collect::<Vec<String>>()
.join(" "));
line
}
pub fn usage(&self, brief: &str) -> String {
self.usage_with_format(|opts|
format!("{}\n\nOptions:\n{}\n", brief, opts.collect::<Vec<String>>().join("\n")))
}
pub fn usage_with_format<F: FnMut(&mut dyn Iterator<Item=String>) -> String>(&self, mut formatter: F) -> String {
formatter(&mut self.usage_items())
}
fn usage_items<'a>(&'a self) -> Box<dyn Iterator<Item=String> + 'a> {
let desc_sep = format!("\n{}", repeat(" ").take(24).collect::<String>());
let any_short = self.grps.iter().any(|optref| {
!optref.short_name.is_empty()
});
let rows = self.grps.iter().map(move |optref| {
let OptGroup{short_name,
long_name,
hint,
desc,
hasarg,
..} = (*optref).clone();
let mut row = " ".to_string();
match short_name.len() {
0 => {
if any_short {
row.push_str(" ");
}
}
1 => {
row.push('-');
row.push_str(&short_name);
if !long_name.is_empty() {
row.push_str(", ");
} else {
row.push(' ');
}
}
_ => panic!("the short name should only be 1 ascii char long"),
}
match long_name.len() {
0 => {}
_ => {
row.push_str("--");
row.push_str(&long_name);
row.push(' ');
}
}
match hasarg {
No => {}
Yes => row.push_str(&hint),
Maybe => {
row.push('[');
row.push_str(&hint);
row.push(']');
}
}
let rowlen = row.chars().count();
if rowlen < 24 {
for _ in 0 .. 24 - rowlen {
row.push(' ');
}
} else {
row.push_str(&desc_sep)
}
let mut desc_normalized_whitespace = String::new();
for word in desc.split(|c: char| c.is_whitespace())
.filter(|s| !s.is_empty()) {
desc_normalized_whitespace.push_str(word);
desc_normalized_whitespace.push(' ');
}
let mut desc_rows = Vec::new();
each_split_within(&desc_normalized_whitespace,
54,
|substr| {
desc_rows.push(substr.to_string());
true
});
row.push_str(&desc_rows.join(&desc_sep));
row
});
Box::new(rows)
}
}
fn validate_names(short_name: &str, long_name: &str) {
let len = short_name.len();
assert!(len == 1 || len == 0,
"the short_name (first argument) should be a single character, \
or an empty string for none");
let len = long_name.len();
assert!(len == 0 || len > 1,
"the long_name (second argument) should be longer than a single \
character, or an empty string for none");
}
#[derive(Clone, PartialEq, Eq)]
enum Name {
Long(String),
Short(char),
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum HasArg {
Yes,
No,
Maybe,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Occur {
Req,
Optional,
Multi,
}
#[derive(Clone, PartialEq, Eq)]
struct Opt {
name: Name,
hasarg: HasArg,
occur: Occur,
aliases: Vec<Opt>,
}
#[derive(Clone, PartialEq, Eq)]
struct OptGroup {
short_name: String,
long_name: String,
hint: String,
desc: String,
hasarg: HasArg,
occur: Occur
}
#[derive(Clone, PartialEq, Eq)]
enum Optval {
Val(String),
Given,
}
#[derive(Clone, PartialEq, Eq)]
pub struct Matches {
opts: Vec<Opt>,
vals: Vec<Vec<Optval>>,
pub free: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Fail {
ArgumentMissing(String),
UnrecognizedOption(String),
OptionMissing(String),
OptionDuplicated(String),
UnexpectedArgument(String),
}
impl Error for Fail {
fn description(&self) -> &str {
match *self {
ArgumentMissing(_) => "missing argument",
UnrecognizedOption(_) => "unrecognized option",
OptionMissing(_) => "missing option",
OptionDuplicated(_) => "duplicated option",
UnexpectedArgument(_) => "unexpected argument",
}
}
}
pub type Result = result::Result<Matches, Fail>;
impl Name {
fn from_str(nm: &str) -> Name {
if nm.len() == 1 {
Short(nm.as_bytes()[0] as char)
} else {
Long(nm.to_string())
}
}
fn to_string(&self) -> String {
match *self {
Short(ch) => ch.to_string(),
Long(ref s) => s.to_string()
}
}
}
impl OptGroup {
fn long_to_short(&self) -> Opt {
let OptGroup {
short_name,
long_name,
hasarg,
occur,
..
} = (*self).clone();
match (short_name.len(), long_name.len()) {
(0,0) => panic!("this long-format option was given no name"),
(0,_) => Opt {
name: Long(long_name),
hasarg,
occur,
aliases: Vec::new()
},
(1,0) => Opt {
name: Short(short_name.as_bytes()[0] as char),
hasarg,
occur,
aliases: Vec::new()
},
(1,_) => Opt {
name: Long(long_name),
hasarg,
occur,
aliases: vec!(
Opt {
name: Short(short_name.as_bytes()[0] as char),
hasarg: hasarg,
occur: occur,
aliases: Vec::new()
}
)
},
(_,_) => panic!("something is wrong with the long-form opt")
}
}
}
impl Matches {
fn opt_vals(&self, nm: &str) -> Vec<Optval> {
match find_opt(&self.opts, &Name::from_str(nm)) {
Some(id) => self.vals[id].clone(),
None => panic!("No option '{}' defined", nm)
}
}
fn opt_val(&self, nm: &str) -> Option<Optval> {
self.opt_vals(nm).into_iter().next()
}
pub fn opt_defined(&self, nm: &str) -> bool {
find_opt(&self.opts, &Name::from_str(nm)).is_some()
}
pub fn opt_present(&self, nm: &str) -> bool {
!self.opt_vals(nm).is_empty()
}
pub fn opt_count(&self, nm: &str) -> usize {
self.opt_vals(nm).len()
}
pub fn opts_present(&self, names: &[String]) -> bool {
names.iter().any(|nm| {
match find_opt(&self.opts, &Name::from_str(&nm)) {
Some(id) if !self.vals[id].is_empty() => true,
_ => false,
}
})
}
pub fn opts_str(&self, names: &[String]) -> Option<String> {
names.iter().filter_map(|nm| {
match self.opt_val(&nm) {
Some(Val(s)) => Some(s),
_ => None,
}
}).next()
}
pub fn opt_strs(&self, nm: &str) -> Vec<String> {
self.opt_vals(nm).into_iter().filter_map(|v| {
match v {
Val(s) => Some(s),
_ => None,
}
}).collect()
}
pub fn opt_str(&self, nm: &str) -> Option<String> {
match self.opt_val(nm) {
Some(Val(s)) => Some(s),
_ => None,
}
}
pub fn opt_default(&self, nm: &str, def: &str) -> Option<String> {
match self.opt_val(nm) {
Some(Val(s)) => Some(s),
Some(_) => Some(def.to_string()),
None => None,
}
}
}
fn is_arg(arg: &str) -> bool {
arg.as_bytes().get(0) == Some(&b'-') && arg.len() > 1
}
fn find_opt(opts: &[Opt], nm: &Name) -> Option<usize> {
let pos = opts.iter().position(|opt| &opt.name == nm);
if pos.is_some() {
return pos
}
for candidate in opts.iter() {
if candidate.aliases.iter().any(|opt| &opt.name == nm) {
return opts.iter().position(|opt| opt.name == candidate.name);
}
}
None
}
impl fmt::Display for Fail {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ArgumentMissing(ref nm) => {
write!(f, "Argument to option '{}' missing", *nm)
}
UnrecognizedOption(ref nm) => {
write!(f, "Unrecognized option: '{}'", *nm)
}
OptionMissing(ref nm) => {
write!(f, "Required option '{}' missing", *nm)
}
OptionDuplicated(ref nm) => {
write!(f, "Option '{}' given more than once", *nm)
}
UnexpectedArgument(ref nm) => {
write!(f, "Option '{}' does not take an argument", *nm)
}
}
}
}
fn format_option(opt: &OptGroup) -> String {
let mut line = String::new();
if opt.occur != Req {
line.push('[');
}
if !opt.short_name.is_empty() {
line.push('-');
line.push_str(&opt.short_name);
} else {
line.push_str("--");
line.push_str(&opt.long_name);
}
if opt.hasarg != No {
line.push(' ');
if opt.hasarg == Maybe {
line.push('[');
}
line.push_str(&opt.hint);
if opt.hasarg == Maybe {
line.push(']');
}
}
if opt.occur != Req {
line.push(']');
}
if opt.occur == Multi {
line.push_str("..");
}
line
}
#[derive(Clone, Copy)]
enum SplitWithinState {
A,
B,
C,
}
#[derive(Clone, Copy)]
enum Whitespace {
Ws,
Cr
}
#[derive(Clone, Copy)]
enum LengthLimit {
UnderLim,
OverLim
}
fn each_split_within<'a, F>(ss: &'a str, lim: usize, mut it: F)
-> bool where F: FnMut(&'a str) -> bool {
let mut slice_start = 0;
let mut last_start = 0;
let mut last_end = 0;
let mut state = A;
let mut fake_i = ss.len();
let mut lim = lim;
let mut cont = true;
if lim >= fake_i {
lim = fake_i;
}
let mut machine = |cont: &mut bool, state: &mut SplitWithinState, (i, c): (usize, char)| {
let whitespace = if c.is_whitespace() { Ws } else { Cr };
let limit = if (i - slice_start + 1) <= lim { UnderLim } else { OverLim };
*state = match (*state, whitespace, limit) {
(A, Ws, _) => { A }
(A, Cr, _) => { slice_start = i; last_start = i; B }
(B, Cr, UnderLim) => { B }
(B, Cr, OverLim) if (i - last_start + 1) > lim => {
B
}
(B, Cr, OverLim) => {
*cont = it(&ss[slice_start..last_end]);
slice_start = last_start;
B
}
(B, Ws, UnderLim) => {
last_end = i;
C
}
(B, Ws, OverLim) => {
last_end = i;
*cont = it(&ss[slice_start..last_end]);
A
}
(C, Cr, UnderLim) => {
last_start = i;
B
}
(C, Cr, OverLim) => {
*cont = it(&ss[slice_start..last_end]);
slice_start = i;
last_start = i;
last_end = i;
B
}
(C, Ws, OverLim) => {
*cont = it(&ss[slice_start..last_end]);
A
}
(C, Ws, UnderLim) => {
C
}
};
*cont
};
ss.char_indices().all(|x| machine(&mut cont, &mut state, x));
while cont && match state { B | C => true, A => false } {
machine(&mut cont, &mut state, (fake_i, ' '));
fake_i += 1;
}
cont
}
#[test]
fn test_split_within() {
fn t(s: &str, i: usize, u: &[String]) {
let mut v = Vec::new();
each_split_within(s, i, |s| { v.push(s.to_string()); true });
assert!(v.iter().zip(u.iter()).all(|(a,b)| a == b));
}
t("", 0, &[]);
t("", 15, &[]);
t("hello", 15, &["hello".to_string()]);
t("\nMary had a little lamb\nLittle lamb\n", 15, &[
"Mary had a".to_string(),
"little lamb".to_string(),
"Little lamb".to_string()
]);
t("\nMary had a little lamb\nLittle lamb\n", ::std::usize::MAX,
&["Mary had a little lamb\nLittle lamb".to_string()]);
}
#[cfg(test)]
mod tests {
use super::{HasArg, Name, Occur, Opt, Options};
#[test]
fn test_long_to_short() {
let mut short = Opt {
name: Name::Long("banana".to_string()),
hasarg: HasArg::Yes,
occur: Occur::Req,
aliases: Vec::new(),
};
short.aliases = vec!(Opt { name: Name::Short('b'),
hasarg: HasArg::Yes,
occur: Occur::Req,
aliases: Vec::new() });
let mut opts = Options::new();
opts.reqopt("b", "banana", "some bananas", "VAL");
let verbose = &opts.grps[0];
assert!(verbose.long_to_short() == short);
}
}