diff options
Diffstat (limited to 'clap/src/app')
-rw-r--r-- | clap/src/app/help.rs | 1028 | ||||
-rw-r--r-- | clap/src/app/meta.rs | 33 | ||||
-rw-r--r-- | clap/src/app/mod.rs | 1839 | ||||
-rw-r--r-- | clap/src/app/parser.rs | 2167 | ||||
-rw-r--r-- | clap/src/app/settings.rs | 1174 | ||||
-rw-r--r-- | clap/src/app/usage.rs | 479 | ||||
-rw-r--r-- | clap/src/app/validator.rs | 573 |
7 files changed, 7293 insertions, 0 deletions
diff --git a/clap/src/app/help.rs b/clap/src/app/help.rs new file mode 100644 index 0000000..34f97ac --- /dev/null +++ b/clap/src/app/help.rs @@ -0,0 +1,1028 @@ +// Std +use std::borrow::Cow; +use std::cmp; +use std::collections::BTreeMap; +use std::fmt::Display; +use std::io::{self, Cursor, Read, Write}; +use std::usize; + +// Internal +use app::parser::Parser; +use app::usage; +use app::{App, AppSettings}; +use args::{AnyArg, ArgSettings, DispOrder}; +use errors::{Error, Result as ClapResult}; +use fmt::{Colorizer, ColorizerOption, Format}; +use map::VecMap; +use INTERNAL_ERROR_MSG; + +// Third Party +#[cfg(feature = "wrap_help")] +use term_size; +use textwrap; +use unicode_width::UnicodeWidthStr; + +#[cfg(not(feature = "wrap_help"))] +mod term_size { + pub fn dimensions() -> Option<(usize, usize)> { + None + } +} + +fn str_width(s: &str) -> usize { + UnicodeWidthStr::width(s) +} + +const TAB: &'static str = " "; + +// These are just convenient traits to make the code easier to read. +trait ArgWithDisplay<'b, 'c>: AnyArg<'b, 'c> + Display {} +impl<'b, 'c, T> ArgWithDisplay<'b, 'c> for T +where + T: AnyArg<'b, 'c> + Display, +{ +} + +trait ArgWithOrder<'b, 'c>: ArgWithDisplay<'b, 'c> + DispOrder { + fn as_base(&self) -> &ArgWithDisplay<'b, 'c>; +} +impl<'b, 'c, T> ArgWithOrder<'b, 'c> for T +where + T: ArgWithDisplay<'b, 'c> + DispOrder, +{ + fn as_base(&self) -> &ArgWithDisplay<'b, 'c> { + self + } +} + +fn as_arg_trait<'a, 'b, T: ArgWithOrder<'a, 'b>>(x: &T) -> &ArgWithOrder<'a, 'b> { + x +} + +impl<'b, 'c> DispOrder for App<'b, 'c> { + fn disp_ord(&self) -> usize { + 999 + } +} + +macro_rules! color { + ($_self:ident, $s:expr, $c:ident) => { + if $_self.color { + write!($_self.writer, "{}", $_self.cizer.$c($s)) + } else { + write!($_self.writer, "{}", $s) + } + }; + ($_self:ident, $fmt_s:expr, $v:expr, $c:ident) => { + if $_self.color { + write!($_self.writer, "{}", $_self.cizer.$c(format!($fmt_s, $v))) + } else { + write!($_self.writer, $fmt_s, $v) + } + }; +} + +/// `clap` Help Writer. +/// +/// Wraps a writer stream providing different methods to generate help for `clap` objects. +pub struct Help<'a> { + writer: &'a mut Write, + next_line_help: bool, + hide_pv: bool, + term_w: usize, + color: bool, + cizer: Colorizer, + longest: usize, + force_next_line: bool, + use_long: bool, +} + +// Public Functions +impl<'a> Help<'a> { + /// Create a new `Help` instance. + #[cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))] + pub fn new( + w: &'a mut Write, + next_line_help: bool, + hide_pv: bool, + color: bool, + cizer: Colorizer, + term_w: Option<usize>, + max_w: Option<usize>, + use_long: bool, + ) -> Self { + debugln!("Help::new;"); + Help { + writer: w, + next_line_help: next_line_help, + hide_pv: hide_pv, + term_w: match term_w { + Some(width) => if width == 0 { + usize::MAX + } else { + width + }, + None => cmp::min( + term_size::dimensions().map_or(120, |(w, _)| w), + match max_w { + None | Some(0) => usize::MAX, + Some(mw) => mw, + }, + ), + }, + color: color, + cizer: cizer, + longest: 0, + force_next_line: false, + use_long: use_long, + } + } + + /// Reads help settings from an App + /// and write its help to the wrapped stream. + pub fn write_app_help(w: &'a mut Write, app: &App, use_long: bool) -> ClapResult<()> { + debugln!("Help::write_app_help;"); + Self::write_parser_help(w, &app.p, use_long) + } + + /// Reads help settings from a Parser + /// and write its help to the wrapped stream. + pub fn write_parser_help(w: &'a mut Write, parser: &Parser, use_long: bool) -> ClapResult<()> { + debugln!("Help::write_parser_help;"); + Self::_write_parser_help(w, parser, false, use_long) + } + + /// Reads help settings from a Parser + /// and write its help to the wrapped stream which will be stderr. This method prevents + /// formatting when required. + pub fn write_parser_help_to_stderr(w: &'a mut Write, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_parser_help;"); + Self::_write_parser_help(w, parser, true, false) + } + + #[doc(hidden)] + pub fn _write_parser_help( + w: &'a mut Write, + parser: &Parser, + stderr: bool, + use_long: bool, + ) -> ClapResult<()> { + debugln!("Help::write_parser_help;"); + let nlh = parser.is_set(AppSettings::NextLineHelp); + let hide_v = parser.is_set(AppSettings::HidePossibleValuesInHelp); + let color = parser.is_set(AppSettings::ColoredHelp); + let cizer = Colorizer::new(ColorizerOption { + use_stderr: stderr, + when: parser.color(), + }); + Self::new( + w, + nlh, + hide_v, + color, + cizer, + parser.meta.term_w, + parser.meta.max_w, + use_long, + ).write_help(parser) + } + + /// Writes the parser help to the wrapped stream. + pub fn write_help(&mut self, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_help;"); + if let Some(h) = parser.meta.help_str { + write!(self.writer, "{}", h).map_err(Error::from)?; + } else if let Some(tmpl) = parser.meta.template { + self.write_templated_help(parser, tmpl)?; + } else { + self.write_default_help(parser)?; + } + Ok(()) + } +} + +// Methods to write AnyArg help. +impl<'a> Help<'a> { + /// Writes help for each argument in the order they were declared to the wrapped stream. + fn write_args_unsorted<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()> + where + I: Iterator<Item = &'d ArgWithOrder<'b, 'c>>, + { + debugln!("Help::write_args_unsorted;"); + // The shortest an arg can legally be is 2 (i.e. '-x') + self.longest = 2; + let mut arg_v = Vec::with_capacity(10); + let use_long = self.use_long; + for arg in args.filter(|arg| should_show_arg(use_long, *arg)) { + if arg.longest_filter() { + self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); + } + arg_v.push(arg) + } + let mut first = true; + for arg in arg_v { + if first { + first = false; + } else { + self.writer.write_all(b"\n")?; + } + self.write_arg(arg.as_base())?; + } + Ok(()) + } + + /// Sorts arguments by length and display order and write their help to the wrapped stream. + fn write_args<'b: 'd, 'c: 'd, 'd, I: 'd>(&mut self, args: I) -> io::Result<()> + where + I: Iterator<Item = &'d ArgWithOrder<'b, 'c>>, + { + debugln!("Help::write_args;"); + // The shortest an arg can legally be is 2 (i.e. '-x') + self.longest = 2; + let mut ord_m = VecMap::new(); + let use_long = self.use_long; + // Determine the longest + for arg in args.filter(|arg| { + // If it's NextLineHelp, but we don't care to compute how long because it may be + // NextLineHelp on purpose *because* it's so long and would throw off all other + // args alignment + should_show_arg(use_long, *arg) + }) { + if arg.longest_filter() { + debugln!("Help::write_args: Current Longest...{}", self.longest); + self.longest = cmp::max(self.longest, str_width(arg.to_string().as_str())); + debugln!("Help::write_args: New Longest...{}", self.longest); + } + let btm = ord_m.entry(arg.disp_ord()).or_insert(BTreeMap::new()); + btm.insert(arg.name(), arg); + } + let mut first = true; + for btm in ord_m.values() { + for arg in btm.values() { + if first { + first = false; + } else { + self.writer.write_all(b"\n")?; + } + self.write_arg(arg.as_base())?; + } + } + Ok(()) + } + + /// Writes help for an argument to the wrapped stream. + fn write_arg<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { + debugln!("Help::write_arg;"); + self.short(arg)?; + self.long(arg)?; + let spec_vals = self.val(arg)?; + self.help(arg, &*spec_vals)?; + Ok(()) + } + + /// Writes argument's short command to the wrapped stream. + fn short<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { + debugln!("Help::short;"); + write!(self.writer, "{}", TAB)?; + if let Some(s) = arg.short() { + color!(self, "-{}", s, good) + } else if arg.has_switch() { + write!(self.writer, "{}", TAB) + } else { + Ok(()) + } + } + + /// Writes argument's long command to the wrapped stream. + fn long<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> io::Result<()> { + debugln!("Help::long;"); + if !arg.has_switch() { + return Ok(()); + } + if arg.takes_value() { + if let Some(l) = arg.long() { + if arg.short().is_some() { + write!(self.writer, ", ")?; + } + color!(self, "--{}", l, good)? + } + + let sep = if arg.is_set(ArgSettings::RequireEquals) { + "=" + } else { + " " + }; + write!(self.writer, "{}", sep)?; + } else if let Some(l) = arg.long() { + if arg.short().is_some() { + write!(self.writer, ", ")?; + } + color!(self, "--{}", l, good)?; + } + Ok(()) + } + + /// Writes argument's possible values to the wrapped stream. + fn val<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>) -> Result<String, io::Error> { + debugln!("Help::val: arg={}", arg); + if arg.takes_value() { + let delim = if arg.is_set(ArgSettings::RequireDelimiter) { + arg.val_delim().expect(INTERNAL_ERROR_MSG) + } else { + ' ' + }; + if let Some(vec) = arg.val_names() { + let mut it = vec.iter().peekable(); + while let Some((_, val)) = it.next() { + color!(self, "<{}>", val, good)?; + if it.peek().is_some() { + write!(self.writer, "{}", delim)?; + } + } + let num = vec.len(); + if arg.is_set(ArgSettings::Multiple) && num == 1 { + color!(self, "...", good)?; + } + } else if let Some(num) = arg.num_vals() { + let mut it = (0..num).peekable(); + while let Some(_) = it.next() { + color!(self, "<{}>", arg.name(), good)?; + if it.peek().is_some() { + write!(self.writer, "{}", delim)?; + } + } + if arg.is_set(ArgSettings::Multiple) && num == 1 { + color!(self, "...", good)?; + } + } else if arg.has_switch() { + color!(self, "<{}>", arg.name(), good)?; + if arg.is_set(ArgSettings::Multiple) { + color!(self, "...", good)?; + } + } else { + color!(self, "{}", arg, good)?; + } + } + + let spec_vals = self.spec_vals(arg); + let h = arg.help().unwrap_or(""); + let h_w = str_width(h) + str_width(&*spec_vals); + let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp); + let taken = self.longest + 12; + self.force_next_line = !nlh && self.term_w >= taken + && (taken as f32 / self.term_w as f32) > 0.40 + && h_w > (self.term_w - taken); + + debug!("Help::val: Has switch..."); + if arg.has_switch() { + sdebugln!("Yes"); + debugln!("Help::val: force_next_line...{:?}", self.force_next_line); + debugln!("Help::val: nlh...{:?}", nlh); + debugln!("Help::val: taken...{}", taken); + debugln!( + "Help::val: help_width > (width - taken)...{} > ({} - {})", + h_w, + self.term_w, + taken + ); + debugln!("Help::val: longest...{}", self.longest); + debug!("Help::val: next_line..."); + if !(nlh || self.force_next_line) { + sdebugln!("No"); + let self_len = str_width(arg.to_string().as_str()); + // subtract ourself + let mut spcs = self.longest - self_len; + // Since we're writing spaces from the tab point we first need to know if we + // had a long and short, or just short + if arg.long().is_some() { + // Only account 4 after the val + spcs += 4; + } else { + // Only account for ', --' + 4 after the val + spcs += 8; + } + + write_nspaces!(self.writer, spcs); + } else { + sdebugln!("Yes"); + } + } else if !(nlh || self.force_next_line) { + sdebugln!("No, and not next_line"); + write_nspaces!( + self.writer, + self.longest + 4 - (str_width(arg.to_string().as_str())) + ); + } else { + sdebugln!("No"); + } + Ok(spec_vals) + } + + fn write_before_after_help(&mut self, h: &str) -> io::Result<()> { + debugln!("Help::write_before_after_help;"); + let mut help = String::from(h); + // determine if our help fits or needs to wrap + debugln!( + "Help::write_before_after_help: Term width...{}", + self.term_w + ); + let too_long = str_width(h) >= self.term_w; + + debug!("Help::write_before_after_help: Too long..."); + if too_long || h.contains("{n}") { + sdebugln!("Yes"); + debugln!("Help::write_before_after_help: help: {}", help); + debugln!( + "Help::write_before_after_help: help width: {}", + str_width(&*help) + ); + // Determine how many newlines we need to insert + debugln!( + "Help::write_before_after_help: Usable space: {}", + self.term_w + ); + help = wrap_help(&help.replace("{n}", "\n"), self.term_w); + } else { + sdebugln!("No"); + } + write!(self.writer, "{}", help)?; + Ok(()) + } + + /// Writes argument's help to the wrapped stream. + fn help<'b, 'c>(&mut self, arg: &ArgWithDisplay<'b, 'c>, spec_vals: &str) -> io::Result<()> { + debugln!("Help::help;"); + let h = if self.use_long && arg.name() != "" { + arg.long_help().unwrap_or_else(|| arg.help().unwrap_or("")) + } else { + arg.help().unwrap_or_else(|| arg.long_help().unwrap_or("")) + }; + let mut help = String::from(h) + spec_vals; + let nlh = self.next_line_help || arg.is_set(ArgSettings::NextLineHelp) || (self.use_long && arg.name() != ""); + debugln!("Help::help: Next Line...{:?}", nlh); + + let spcs = if nlh || self.force_next_line { + 12 // "tab" * 3 + } else { + self.longest + 12 + }; + + let too_long = spcs + str_width(h) + str_width(&*spec_vals) >= self.term_w; + + // Is help on next line, if so then indent + if nlh || self.force_next_line { + write!(self.writer, "\n{}{}{}", TAB, TAB, TAB)?; + } + + debug!("Help::help: Too long..."); + if too_long && spcs <= self.term_w || h.contains("{n}") { + sdebugln!("Yes"); + debugln!("Help::help: help...{}", help); + debugln!("Help::help: help width...{}", str_width(&*help)); + // Determine how many newlines we need to insert + let avail_chars = self.term_w - spcs; + debugln!("Help::help: Usable space...{}", avail_chars); + help = wrap_help(&help.replace("{n}", "\n"), avail_chars); + } else { + sdebugln!("No"); + } + if let Some(part) = help.lines().next() { + write!(self.writer, "{}", part)?; + } + for part in help.lines().skip(1) { + write!(self.writer, "\n")?; + if nlh || self.force_next_line { + write!(self.writer, "{}{}{}", TAB, TAB, TAB)?; + } else if arg.has_switch() { + write_nspaces!(self.writer, self.longest + 12); + } else { + write_nspaces!(self.writer, self.longest + 8); + } + write!(self.writer, "{}", part)?; + } + if !help.contains('\n') && (nlh || self.force_next_line) { + write!(self.writer, "\n")?; + } + Ok(()) + } + + fn spec_vals(&self, a: &ArgWithDisplay) -> String { + debugln!("Help::spec_vals: a={}", a); + let mut spec_vals = vec![]; + if let Some(ref env) = a.env() { + debugln!( + "Help::spec_vals: Found environment variable...[{:?}:{:?}]", + env.0, + env.1 + ); + let env_val = if !a.is_set(ArgSettings::HideEnvValues) { + format!( + "={}", + env.1.map_or(Cow::Borrowed(""), |val| val.to_string_lossy()) + ) + } else { + String::new() + }; + let env_info = format!(" [env: {}{}]", env.0.to_string_lossy(), env_val); + spec_vals.push(env_info); + } + if !a.is_set(ArgSettings::HideDefaultValue) { + if let Some(pv) = a.default_val() { + debugln!("Help::spec_vals: Found default value...[{:?}]", pv); + spec_vals.push(format!( + " [default: {}]", + if self.color { + self.cizer.good(pv.to_string_lossy()) + } else { + Format::None(pv.to_string_lossy()) + } + )); + } + } + if let Some(ref aliases) = a.aliases() { + debugln!("Help::spec_vals: Found aliases...{:?}", aliases); + spec_vals.push(format!( + " [aliases: {}]", + if self.color { + aliases + .iter() + .map(|v| format!("{}", self.cizer.good(v))) + .collect::<Vec<_>>() + .join(", ") + } else { + aliases.join(", ") + } + )); + } + if !self.hide_pv && !a.is_set(ArgSettings::HidePossibleValues) { + if let Some(pv) = a.possible_vals() { + debugln!("Help::spec_vals: Found possible vals...{:?}", pv); + spec_vals.push(if self.color { + format!( + " [possible values: {}]", + pv.iter() + .map(|v| format!("{}", self.cizer.good(v))) + .collect::<Vec<_>>() + .join(", ") + ) + } else { + format!(" [possible values: {}]", pv.join(", ")) + }); + } + } + spec_vals.join(" ") + } +} + +fn should_show_arg(use_long: bool, arg: &ArgWithOrder) -> bool { + if arg.is_set(ArgSettings::Hidden) { + return false; + } + + (!arg.is_set(ArgSettings::HiddenLongHelp) && use_long) + || (!arg.is_set(ArgSettings::HiddenShortHelp) && !use_long) + || arg.is_set(ArgSettings::NextLineHelp) +} + +// Methods to write Parser help. +impl<'a> Help<'a> { + /// Writes help for all arguments (options, flags, args, subcommands) + /// including titles of a Parser Object to the wrapped stream. + #[cfg_attr(feature = "lints", allow(useless_let_if_seq))] + #[cfg_attr(feature = "cargo-clippy", allow(useless_let_if_seq))] + pub fn write_all_args(&mut self, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_all_args;"); + let flags = parser.has_flags(); + let pos = parser + .positionals() + .filter(|arg| !arg.is_set(ArgSettings::Hidden)) + .count() > 0; + let opts = parser.has_opts(); + let subcmds = parser.has_visible_subcommands(); + + let unified_help = parser.is_set(AppSettings::UnifiedHelpMessage); + + let mut first = true; + + if unified_help && (flags || opts) { + let opts_flags = parser + .flags() + .map(as_arg_trait) + .chain(parser.opts().map(as_arg_trait)); + color!(self, "OPTIONS:\n", warning)?; + self.write_args(opts_flags)?; + first = false; + } else { + if flags { + color!(self, "FLAGS:\n", warning)?; + self.write_args(parser.flags().map(as_arg_trait))?; + first = false; + } + if opts { + if !first { + self.writer.write_all(b"\n\n")?; + } + color!(self, "OPTIONS:\n", warning)?; + self.write_args(parser.opts().map(as_arg_trait))?; + first = false; + } + } + + if pos { + if !first { + self.writer.write_all(b"\n\n")?; + } + color!(self, "ARGS:\n", warning)?; + self.write_args_unsorted(parser.positionals().map(as_arg_trait))?; + first = false; + } + + if subcmds { + if !first { + self.writer.write_all(b"\n\n")?; + } + color!(self, "SUBCOMMANDS:\n", warning)?; + self.write_subcommands(parser)?; + } + + Ok(()) + } + + /// Writes help for subcommands of a Parser Object to the wrapped stream. + fn write_subcommands(&mut self, parser: &Parser) -> io::Result<()> { + debugln!("Help::write_subcommands;"); + // The shortest an arg can legally be is 2 (i.e. '-x') + self.longest = 2; + let mut ord_m = VecMap::new(); + for sc in parser + .subcommands + .iter() + .filter(|s| !s.p.is_set(AppSettings::Hidden)) + { + let btm = ord_m.entry(sc.p.meta.disp_ord).or_insert(BTreeMap::new()); + self.longest = cmp::max(self.longest, str_width(sc.p.meta.name.as_str())); + //self.longest = cmp::max(self.longest, sc.p.meta.name.len()); + btm.insert(sc.p.meta.name.clone(), sc.clone()); + } + + let mut first = true; + for btm in ord_m.values() { + for sc in btm.values() { + if first { + first = false; + } else { + self.writer.write_all(b"\n")?; + } + self.write_arg(sc)?; + } + } + Ok(()) + } + + /// Writes version of a Parser Object to the wrapped stream. + fn write_version(&mut self, parser: &Parser) -> io::Result<()> { + debugln!("Help::write_version;"); + write!(self.writer, "{}", parser.meta.version.unwrap_or(""))?; + Ok(()) + } + + /// Writes binary name of a Parser Object to the wrapped stream. + fn write_bin_name(&mut self, parser: &Parser) -> io::Result<()> { + debugln!("Help::write_bin_name;"); + macro_rules! write_name { + () => {{ + let mut name = parser.meta.name.clone(); + name = name.replace("{n}", "\n"); + color!(self, wrap_help(&name, self.term_w), good)?; + }}; + } + if let Some(bn) = parser.meta.bin_name.as_ref() { + if bn.contains(' ') { + // Incase we're dealing with subcommands i.e. git mv is translated to git-mv + color!(self, bn.replace(" ", "-"), good)? + } else { + write_name!(); + } + } else { + write_name!(); + } + Ok(()) + } + + /// Writes default help for a Parser Object to the wrapped stream. + pub fn write_default_help(&mut self, parser: &Parser) -> ClapResult<()> { + debugln!("Help::write_default_help;"); + if let Some(h) = parser.meta.pre_help { + self.write_before_after_help(h)?; + self.writer.write_all(b"\n\n")?; + } + + macro_rules! write_thing { + ($thing:expr) => {{ + let mut owned_thing = $thing.to_owned(); + owned_thing = owned_thing.replace("{n}", "\n"); + write!(self.writer, "{}\n", wrap_help(&owned_thing, self.term_w))? + }}; + } + // Print the version + self.write_bin_name(parser)?; + self.writer.write_all(b" ")?; + self.write_version(parser)?; + self.writer.write_all(b"\n")?; + if let Some(author) = parser.meta.author { + write_thing!(author) + } + // if self.use_long { + // if let Some(about) = parser.meta.long_about { + // debugln!("Help::write_default_help: writing long about"); + // write_thing!(about) + // } else if let Some(about) = parser.meta.about { + // debugln!("Help::write_default_help: writing about"); + // write_thing!(about) + // } + // } else + if let Some(about) = parser.meta.long_about { + debugln!("Help::write_default_help: writing long about"); + write_thing!(about) + } else if let Some(about) = parser.meta.about { + debugln!("Help::write_default_help: writing about"); + write_thing!(about) + } + + color!(self, "\nUSAGE:", warning)?; + write!( + self.writer, + "\n{}{}\n\n", + TAB, + usage::create_usage_no_title(parser, &[]) + )?; + + let flags = parser.has_flags(); + let pos = parser.has_positionals(); + let opts = parser.has_opts(); + let subcmds = parser.has_subcommands(); + + if flags || opts || pos || subcmds { + self.write_all_args(parser)?; + } + + if let Some(h) = parser.meta.more_help { + if flags || opts || pos || subcmds { + self.writer.write_all(b"\n\n")?; + } + self.write_before_after_help(h)?; + } + + self.writer.flush().map_err(Error::from) + } +} + +/// Possible results for a copying function that stops when a given +/// byte was found. +enum CopyUntilResult { + DelimiterFound(usize), + DelimiterNotFound(usize), + ReaderEmpty, + ReadError(io::Error), + WriteError(io::Error), +} + +/// Copies the contents of a reader into a writer until a delimiter byte is found. +/// On success, the total number of bytes that were +/// copied from reader to writer is returned. +fn copy_until<R: Read, W: Write>(r: &mut R, w: &mut W, delimiter_byte: u8) -> CopyUntilResult { + debugln!("copy_until;"); + + let mut count = 0; + for wb in r.bytes() { + match wb { + Ok(b) => { + if b == delimiter_byte { + return CopyUntilResult::DelimiterFound(count); + } + match w.write(&[b]) { + Ok(c) => count += c, + Err(e) => return CopyUntilResult::WriteError(e), + } + } + Err(e) => return CopyUntilResult::ReadError(e), + } + } + if count > 0 { + CopyUntilResult::DelimiterNotFound(count) + } else { + CopyUntilResult::ReaderEmpty + } +} + +/// Copies the contents of a reader into a writer until a {tag} is found, +/// copying the tag content to a buffer and returning its size. +/// In addition to errors, there are three possible outputs: +/// - `None`: The reader was consumed. +/// - `Some(Ok(0))`: No tag was captured but the reader still contains data. +/// - `Some(Ok(length>0))`: a tag with `length` was captured to the `tag_buffer`. +fn copy_and_capture<R: Read, W: Write>( + r: &mut R, + w: &mut W, + tag_buffer: &mut Cursor<Vec<u8>>, +) -> Option<io::Result<usize>> { + use self::CopyUntilResult::*; + debugln!("copy_and_capture;"); + + // Find the opening byte. + match copy_until(r, w, b'{') { + // The end of the reader was reached without finding the opening tag. + // (either with or without having copied data to the writer) + // Return None indicating that we are done. + ReaderEmpty | DelimiterNotFound(_) => None, + + // Something went wrong. + ReadError(e) | WriteError(e) => Some(Err(e)), + + // The opening byte was found. + // (either with or without having copied data to the writer) + DelimiterFound(_) => { + // Lets reset the buffer first and find out how long it is. + tag_buffer.set_position(0); + let buffer_size = tag_buffer.get_ref().len(); + + // Find the closing byte,limiting the reader to the length of the buffer. + let mut rb = r.take(buffer_size as u64); + match copy_until(&mut rb, tag_buffer, b'}') { + // We were already at the end of the reader. + // Return None indicating that we are done. + ReaderEmpty => None, + + // The closing tag was found. + // Return the tag_length. + DelimiterFound(tag_length) => Some(Ok(tag_length)), + + // The end of the reader was found without finding the closing tag. + // Write the opening byte and captured text to the writer. + // Return 0 indicating that nothing was captured but the reader still contains data. + DelimiterNotFound(not_tag_length) => match w.write(b"{") { + Err(e) => Some(Err(e)), + _ => match w.write(&tag_buffer.get_ref()[0..not_tag_length]) { + Err(e) => Some(Err(e)), + _ => Some(Ok(0)), + }, + }, + + ReadError(e) | WriteError(e) => Some(Err(e)), + } + } + } +} + +// Methods to write Parser help using templates. +impl<'a> Help<'a> { + /// Write help to stream for the parser in the format defined by the template. + /// + /// Tags arg given inside curly brackets: + /// Valid tags are: + /// * `{bin}` - Binary name. + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments, + /// and subcommands) including titles. + /// * `{unified}` - Unified help for options and flags. + /// * `{flags}` - Help for flags. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positionals arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{after-help}` - Info to be displayed after the help message. + /// * `{before-help}` - Info to be displayed before the help message. + /// + /// The template system is, on purpose, very simple. Therefore the tags have to written + /// in the lowercase and without spacing. + fn write_templated_help(&mut self, parser: &Parser, template: &str) -> ClapResult<()> { + debugln!("Help::write_templated_help;"); + let mut tmplr = Cursor::new(&template); + let mut tag_buf = Cursor::new(vec![0u8; 15]); + + // The strategy is to copy the template from the reader to wrapped stream + // until a tag is found. Depending on its value, the appropriate content is copied + // to the wrapped stream. + // The copy from template is then resumed, repeating this sequence until reading + // the complete template. + + loop { + let tag_length = match copy_and_capture(&mut tmplr, &mut self.writer, &mut tag_buf) { + None => return Ok(()), + Some(Err(e)) => return Err(Error::from(e)), + Some(Ok(val)) if val > 0 => val, + _ => continue, + }; + + debugln!("Help::write_template_help:iter: tag_buf={};", unsafe { + String::from_utf8_unchecked( + tag_buf.get_ref()[0..tag_length] + .iter() + .map(|&i| i) + .collect::<Vec<_>>(), + ) + }); + match &tag_buf.get_ref()[0..tag_length] { + b"?" => { + self.writer.write_all(b"Could not decode tag name")?; + } + b"bin" => { + self.write_bin_name(parser)?; + } + b"version" => { + write!( + self.writer, + "{}", + parser.meta.version.unwrap_or("unknown version") + )?; + } + b"author" => { + write!( + self.writer, + "{}", + parser.meta.author.unwrap_or("unknown author") + )?; + } + b"about" => { + write!( + self.writer, + "{}", + parser.meta.about.unwrap_or("unknown about") + )?; + } + b"long-about" => { + write!( + self.writer, + "{}", + parser.meta.long_about.unwrap_or("unknown about") + )?; + } + b"usage" => { + write!(self.writer, "{}", usage::create_usage_no_title(parser, &[]))?; + } + b"all-args" => { + self.write_all_args(parser)?; + } + b"unified" => { + let opts_flags = parser + .flags() + .map(as_arg_trait) + .chain(parser.opts().map(as_arg_trait)); + self.write_args(opts_flags)?; + } + b"flags" => { + self.write_args(parser.flags().map(as_arg_trait))?; + } + b"options" => { + self.write_args(parser.opts().map(as_arg_trait))?; + } + b"positionals" => { + self.write_args(parser.positionals().map(as_arg_trait))?; + } + b"subcommands" => { + self.write_subcommands(parser)?; + } + b"after-help" => { + write!( + self.writer, + "{}", + parser.meta.more_help.unwrap_or("unknown after-help") + )?; + } + b"before-help" => { + write!( + self.writer, + "{}", + parser.meta.pre_help.unwrap_or("unknown before-help") + )?; + } + // Unknown tag, write it back. + r => { + self.writer.write_all(b"{")?; + self.writer.write_all(r)?; + self.writer.write_all(b"}")?; + } + } + } + } +} + +fn wrap_help(help: &str, avail_chars: usize) -> String { + let wrapper = textwrap::Wrapper::new(avail_chars).break_words(false); + help.lines() + .map(|line| wrapper.fill(line)) + .collect::<Vec<String>>() + .join("\n") +} + +#[cfg(test)] +mod test { + use super::wrap_help; + + #[test] + fn wrap_help_last_word() { + let help = String::from("foo bar baz"); + assert_eq!(wrap_help(&help, 5), "foo\nbar\nbaz"); + } +} diff --git a/clap/src/app/meta.rs b/clap/src/app/meta.rs new file mode 100644 index 0000000..c7f128f --- /dev/null +++ b/clap/src/app/meta.rs @@ -0,0 +1,33 @@ +#[doc(hidden)] +#[allow(missing_debug_implementations)] +#[derive(Default, Clone)] +pub struct AppMeta<'b> { + pub name: String, + pub bin_name: Option<String>, + pub author: Option<&'b str>, + pub version: Option<&'b str>, + pub long_version: Option<&'b str>, + pub about: Option<&'b str>, + pub long_about: Option<&'b str>, + pub more_help: Option<&'b str>, + pub pre_help: Option<&'b str>, + pub aliases: Option<Vec<(&'b str, bool)>>, // (name, visible) + pub usage_str: Option<&'b str>, + pub usage: Option<String>, + pub help_str: Option<&'b str>, + pub disp_ord: usize, + pub term_w: Option<usize>, + pub max_w: Option<usize>, + pub template: Option<&'b str>, +} + +impl<'b> AppMeta<'b> { + pub fn new() -> Self { Default::default() } + pub fn with_name(s: String) -> Self { + AppMeta { + name: s, + disp_ord: 999, + ..Default::default() + } + } +} diff --git a/clap/src/app/mod.rs b/clap/src/app/mod.rs new file mode 100644 index 0000000..3a1a383 --- /dev/null +++ b/clap/src/app/mod.rs @@ -0,0 +1,1839 @@ +mod settings; +pub mod parser; +mod meta; +mod help; +mod validator; +mod usage; + +// Std +use std::env; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io::{self, BufRead, BufWriter, Write}; +use std::path::Path; +use std::process; +use std::rc::Rc; +use std::result::Result as StdResult; + +// Third Party +#[cfg(feature = "yaml")] +use yaml_rust::Yaml; + +// Internal +use app::help::Help; +use app::parser::Parser; +use args::{AnyArg, Arg, ArgGroup, ArgMatcher, ArgMatches, ArgSettings}; +use errors::Result as ClapResult; +pub use self::settings::AppSettings; +use completions::Shell; +use map::{self, VecMap}; + +/// Used to create a representation of a command line program and all possible command line +/// arguments. Application settings are set using the "builder pattern" with the +/// [`App::get_matches`] family of methods being the terminal methods that starts the +/// runtime-parsing process. These methods then return information about the user supplied +/// arguments (or lack there of). +/// +/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may +/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method +/// called). +/// +/// # Examples +/// +/// ```no_run +/// # use clap::{App, Arg}; +/// let m = App::new("My Program") +/// .author("Me, me@mail.com") +/// .version("1.0.2") +/// .about("Explains in brief what the program does") +/// .arg( +/// Arg::with_name("in_file").index(1) +/// ) +/// .after_help("Longer explanation to appear after the options when \ +/// displaying the help information from --help or -h") +/// .get_matches(); +/// +/// // Your program logic starts here... +/// ``` +/// [`App::get_matches`]: ./struct.App.html#method.get_matches +#[allow(missing_debug_implementations)] +pub struct App<'a, 'b> +where + 'a: 'b, +{ + #[doc(hidden)] pub p: Parser<'a, 'b>, +} + + +impl<'a, 'b> App<'a, 'b> { + /// Creates a new instance of an application requiring a name. The name may be, but doesn't + /// have to be same as the binary. The name will be displayed to the user when they request to + /// print version or help and usage information. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let prog = App::new("My Program") + /// # ; + /// ``` + pub fn new<S: Into<String>>(n: S) -> Self { + App { + p: Parser::with_name(n.into()), + } + } + + /// Get the name of the app + pub fn get_name(&self) -> &str { &self.p.meta.name } + + /// Get the name of the binary + pub fn get_bin_name(&self) -> Option<&str> { self.p.meta.bin_name.as_ref().map(|s| s.as_str()) } + + /// Creates a new instance of an application requiring a name, but uses the [`crate_authors!`] + /// and [`crate_version!`] macros to fill in the [`App::author`] and [`App::version`] fields. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let prog = App::with_defaults("My Program") + /// # ; + /// ``` + /// [`crate_authors!`]: ./macro.crate_authors!.html + /// [`crate_version!`]: ./macro.crate_version!.html + /// [`App::author`]: ./struct.App.html#method.author + /// [`App::version`]: ./struct.App.html#method.author + #[deprecated(since="2.14.1", note="Can never work; use explicit App::author() and App::version() calls instead")] + pub fn with_defaults<S: Into<String>>(n: S) -> Self { + let mut a = App { + p: Parser::with_name(n.into()), + }; + a.p.meta.author = Some("Kevin K. <kbknapp@gmail.com>"); + a.p.meta.version = Some("2.19.2"); + a + } + + /// Creates a new instance of [`App`] from a .yml (YAML) file. A full example of supported YAML + /// objects can be found in [`examples/17_yaml.rs`] and [`examples/17_yaml.yml`]. One great use + /// for using YAML is when supporting multiple languages and dialects, as each language could + /// be a distinct YAML file and determined at compiletime via `cargo` "features" in your + /// `Cargo.toml` + /// + /// In order to use this function you must compile `clap` with the `features = ["yaml"]` in + /// your settings for the `[dependencies.clap]` table of your `Cargo.toml` + /// + /// **NOTE:** Due to how the YAML objects are built there is a convenience macro for loading + /// the YAML file at compile time (relative to the current file, like modules work). That YAML + /// object can then be passed to this function. + /// + /// # Panics + /// + /// The YAML file must be properly formatted or this function will [`panic!`]. A good way to + /// ensure this doesn't happen is to run your program with the `--help` switch. If this passes + /// without error, you needn't worry because the YAML is properly formatted. + /// + /// # Examples + /// + /// The following example shows how to load a properly formatted YAML file to build an instance + /// of an [`App`] struct. + /// + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::App; + /// # fn main() { + /// let yml = load_yaml!("app.yml"); + /// let app = App::from_yaml(yml); + /// + /// // continued logic goes here, such as `app.get_matches()` etc. + /// # } + /// ``` + /// [`App`]: ./struct.App.html + /// [`examples/17_yaml.rs`]: https://github.com/clap-rs/clap/blob/master/examples/17_yaml.rs + /// [`examples/17_yaml.yml`]: https://github.com/clap-rs/clap/blob/master/examples/17_yaml.yml + /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html + #[cfg(feature = "yaml")] + pub fn from_yaml(yaml: &'a Yaml) -> App<'a, 'a> { App::from(yaml) } + + /// Sets a string of author(s) that will be displayed to the user when they + /// request the help information with `--help` or `-h`. + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to automatically set your + /// application's author(s) to the same thing as your crate at compile time. See the [`examples/`] + /// directory for more information + /// + /// See the [`examples/`] + /// directory for more information + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .author("Me, me@mymain.com") + /// # ; + /// ``` + /// [`crate_authors!`]: ./macro.crate_authors!.html + /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples + pub fn author<S: Into<&'b str>>(mut self, author: S) -> Self { + self.p.meta.author = Some(author.into()); + self + } + + /// Overrides the system-determined binary name. This should only be used when absolutely + /// necessary, such as when the binary name for your application is misleading, or perhaps + /// *not* how the user should invoke your program. + /// + /// **Pro-tip:** When building things such as third party `cargo` subcommands, this setting + /// **should** be used! + /// + /// **NOTE:** This command **should not** be used for [`SubCommand`]s. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("My Program") + /// .bin_name("my_binary") + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self { + self.p.meta.bin_name = Some(name.into()); + self + } + + /// Sets a string describing what the program does. This will be displayed when displaying help + /// information with `-h`. + /// + /// **NOTE:** If only `about` is provided, and not [`App::long_about`] but the user requests + /// `--help` clap will still display the contents of `about` appropriately + /// + /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be + /// concise + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .about("Does really amazing things to great people") + /// # ; + /// ``` + /// [`App::long_about`]: ./struct.App.html#method.long_about + pub fn about<S: Into<&'b str>>(mut self, about: S) -> Self { + self.p.meta.about = Some(about.into()); + self + } + + /// Sets a string describing what the program does. This will be displayed when displaying help + /// information. + /// + /// **NOTE:** If only `long_about` is provided, and not [`App::about`] but the user requests + /// `-h` clap will still display the contents of `long_about` appropriately + /// + /// **NOTE:** Only [`App::about`] is used in completion script generation in order to be + /// concise + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .long_about( + /// "Does really amazing things to great people. Now let's talk a little + /// more in depth about how this subcommand really works. It may take about + /// a few lines of text, but that's ok!") + /// # ; + /// ``` + /// [`App::about`]: ./struct.App.html#method.about + pub fn long_about<S: Into<&'b str>>(mut self, about: S) -> Self { + self.p.meta.long_about = Some(about.into()); + self + } + + /// Sets the program's name. This will be displayed when displaying help information. + /// + /// **Pro-top:** This function is particularly useful when configuring a program via + /// [`App::from_yaml`] in conjunction with the [`crate_name!`] macro to derive the program's + /// name from its `Cargo.toml`. + /// + /// # Examples + /// ```ignore + /// # #[macro_use] + /// # extern crate clap; + /// # use clap::App; + /// # fn main() { + /// let yml = load_yaml!("app.yml"); + /// let app = App::from_yaml(yml) + /// .name(crate_name!()); + /// + /// // continued logic goes here, such as `app.get_matches()` etc. + /// # } + /// ``` + /// + /// [`App::from_yaml`]: ./struct.App.html#method.from_yaml + /// [`crate_name!`]: ./macro.crate_name.html + pub fn name<S: Into<String>>(mut self, name: S) -> Self { + self.p.meta.name = name.into(); + self + } + + /// Adds additional help information to be displayed in addition to auto-generated help. This + /// information is displayed **after** the auto-generated help information. This is often used + /// to describe how to use the arguments, or caveats to be noted. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .after_help("Does really amazing things to great people...but be careful with -R") + /// # ; + /// ``` + pub fn after_help<S: Into<&'b str>>(mut self, help: S) -> Self { + self.p.meta.more_help = Some(help.into()); + self + } + + /// Adds additional help information to be displayed in addition to auto-generated help. This + /// information is displayed **before** the auto-generated help information. This is often used + /// for header information. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .before_help("Some info I'd like to appear before the help info") + /// # ; + /// ``` + pub fn before_help<S: Into<&'b str>>(mut self, help: S) -> Self { + self.p.meta.pre_help = Some(help.into()); + self + } + + /// Sets a string of the version number to be displayed when displaying version or help + /// information with `-V`. + /// + /// **NOTE:** If only `version` is provided, and not [`App::long_version`] but the user + /// requests `--version` clap will still display the contents of `version` appropriately + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your + /// application's version to the same thing as your crate at compile time. See the [`examples/`] + /// directory for more information + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version("v0.1.24") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples + /// [`App::long_version`]: ./struct.App.html#method.long_version + pub fn version<S: Into<&'b str>>(mut self, ver: S) -> Self { + self.p.meta.version = Some(ver.into()); + self + } + + /// Sets a string of the version number to be displayed when displaying version or help + /// information with `--version`. + /// + /// **NOTE:** If only `long_version` is provided, and not [`App::version`] but the user + /// requests `-V` clap will still display the contents of `long_version` appropriately + /// + /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to automatically set your + /// application's version to the same thing as your crate at compile time. See the [`examples/`] + /// directory for more information + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .long_version( + /// "v0.1.24 + /// commit: abcdef89726d + /// revision: 123 + /// release: 2 + /// binary: myprog") + /// # ; + /// ``` + /// [`crate_version!`]: ./macro.crate_version!.html + /// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples + /// [`App::version`]: ./struct.App.html#method.version + pub fn long_version<S: Into<&'b str>>(mut self, ver: S) -> Self { + self.p.meta.long_version = Some(ver.into()); + self + } + + /// Sets a custom usage string to override the auto-generated usage string. + /// + /// This will be displayed to the user when errors are found in argument parsing, or when you + /// call [`ArgMatches::usage`] + /// + /// **CAUTION:** Using this setting disables `clap`s "context-aware" usage strings. After this + /// setting is set, this will be the only usage string displayed to the user! + /// + /// **NOTE:** You do not need to specify the "USAGE: \n\t" portion, as that will + /// still be applied by `clap`, you only need to specify the portion starting + /// with the binary name. + /// + /// **NOTE:** This will not replace the entire help message, *only* the portion + /// showing the usage. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .usage("myapp [-clDas] <some_file>") + /// # ; + /// ``` + /// [`ArgMatches::usage`]: ./struct.ArgMatches.html#method.usage + pub fn usage<S: Into<&'b str>>(mut self, usage: S) -> Self { + self.p.meta.usage_str = Some(usage.into()); + self + } + + /// Sets a custom help message and overrides the auto-generated one. This should only be used + /// when the auto-generated message does not suffice. + /// + /// This will be displayed to the user when they use `--help` or `-h` + /// + /// **NOTE:** This replaces the **entire** help message, so nothing will be auto-generated. + /// + /// **NOTE:** This **only** replaces the help message for the current command, meaning if you + /// are using subcommands, those help messages will still be auto-generated unless you + /// specify a [`Arg::help`] for them as well. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myapp") + /// .help("myapp v1.0\n\ + /// Does awesome things\n\ + /// (C) me@mail.com\n\n\ + /// + /// USAGE: myapp <opts> <command>\n\n\ + /// + /// Options:\n\ + /// -h, --help Display this message\n\ + /// -V, --version Display version info\n\ + /// -s <stuff> Do something with stuff\n\ + /// -v Be verbose\n\n\ + /// + /// Commmands:\n\ + /// help Prints this message\n\ + /// work Do some work") + /// # ; + /// ``` + /// [`Arg::help`]: ./struct.Arg.html#method.help + pub fn help<S: Into<&'b str>>(mut self, help: S) -> Self { + self.p.meta.help_str = Some(help.into()); + self + } + + /// Sets the [`short`] for the auto-generated `help` argument. + /// + /// By default `clap` automatically assigns `h`, but this can be overridden if you have a + /// different argument which you'd prefer to use the `-h` short with. This can be done by + /// defining your own argument with a lowercase `h` as the [`short`]. + /// + /// `clap` lazily generates these `help` arguments **after** you've defined any arguments of + /// your own. + /// + /// **NOTE:** Any leading `-` characters will be stripped, and only the first + /// non `-` character will be used as the [`short`] version + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .help_short("H") // Using an uppercase `H` instead of the default lowercase `h` + /// # ; + /// ``` + /// [`short`]: ./struct.Arg.html#method.short + pub fn help_short<S: AsRef<str> + 'b>(mut self, s: S) -> Self { + self.p.help_short(s.as_ref()); + self + } + + /// Sets the [`short`] for the auto-generated `version` argument. + /// + /// By default `clap` automatically assigns `V`, but this can be overridden if you have a + /// different argument which you'd prefer to use the `-V` short with. This can be done by + /// defining your own argument with an uppercase `V` as the [`short`]. + /// + /// `clap` lazily generates these `version` arguments **after** you've defined any arguments of + /// your own. + /// + /// **NOTE:** Any leading `-` characters will be stripped, and only the first + /// non `-` character will be used as the `short` version + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version_short("v") // Using a lowercase `v` instead of the default capital `V` + /// # ; + /// ``` + /// [`short`]: ./struct.Arg.html#method.short + pub fn version_short<S: AsRef<str>>(mut self, s: S) -> Self { + self.p.version_short(s.as_ref()); + self + } + + /// Sets the help text for the auto-generated `help` argument. + /// + /// By default `clap` sets this to `"Prints help information"`, but if you're using a + /// different convention for your help messages and would prefer a different phrasing you can + /// override it. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .help_message("Print help information") // Perhaps you want imperative help messages + /// + /// # ; + /// ``` + pub fn help_message<S: Into<&'a str>>(mut self, s: S) -> Self { + self.p.help_message = Some(s.into()); + self + } + + /// Sets the help text for the auto-generated `version` argument. + /// + /// By default `clap` sets this to `"Prints version information"`, but if you're using a + /// different convention for your help messages and would prefer a different phrasing then you + /// can change it. + /// + /// # Examples + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version_message("Print version information") // Perhaps you want imperative help messages + /// # ; + /// ``` + pub fn version_message<S: Into<&'a str>>(mut self, s: S) -> Self { + self.p.version_message = Some(s.into()); + self + } + + /// Sets the help template to be used, overriding the default format. + /// + /// Tags arg given inside curly brackets. + /// + /// Valid tags are: + /// + /// * `{bin}` - Binary name. + /// * `{version}` - Version number. + /// * `{author}` - Author information. + /// * `{about}` - General description (from [`App::about`]) + /// * `{usage}` - Automatically generated or given usage string. + /// * `{all-args}` - Help for all arguments (options, flags, positionals arguments, + /// and subcommands) including titles. + /// * `{unified}` - Unified help for options and flags. Note, you must *also* set + /// [`AppSettings::UnifiedHelpMessage`] to fully merge both options and + /// flags, otherwise the ordering is "best effort" + /// * `{flags}` - Help for flags. + /// * `{options}` - Help for options. + /// * `{positionals}` - Help for positionals arguments. + /// * `{subcommands}` - Help for subcommands. + /// * `{after-help}` - Help from [`App::after_help`] + /// * `{before-help}` - Help from [`App::before_help`] + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .version("1.0") + /// .template("{bin} ({version}) - {usage}") + /// # ; + /// ``` + /// **NOTE:** The template system is, on purpose, very simple. Therefore the tags have to be + /// written in lowercase and without spacing. + /// + /// [`App::about`]: ./struct.App.html#method.about + /// [`App::after_help`]: ./struct.App.html#method.after_help + /// [`App::before_help`]: ./struct.App.html#method.before_help + /// [`AppSettings::UnifiedHelpMessage`]: ./enum.AppSettings.html#variant.UnifiedHelpMessage + pub fn template<S: Into<&'b str>>(mut self, s: S) -> Self { + self.p.meta.template = Some(s.into()); + self + } + + /// Enables a single command, or [`SubCommand`], level settings. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .setting(AppSettings::WaitOnError) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn setting(mut self, setting: AppSettings) -> Self { + self.p.set(setting); + self + } + + /// Enables multiple command, or [`SubCommand`], level settings + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .settings(&[AppSettings::SubcommandRequired, + /// AppSettings::WaitOnError]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.p.set(*s); + } + self + } + + /// Enables a single setting that is propagated down through all child [`SubCommand`]s. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_setting(AppSettings::SubcommandRequired) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn global_setting(mut self, setting: AppSettings) -> Self { + self.p.set(setting); + self.p.g_settings.set(setting); + self + } + + /// Enables multiple settings which are propagated *down* through all child [`SubCommand`]s. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// **NOTE**: The setting is *only* propagated *down* and not up through parent commands. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .global_settings(&[AppSettings::SubcommandRequired, + /// AppSettings::ColoredHelp]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn global_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.p.set(*s); + self.p.g_settings.set(*s) + } + self + } + + /// Disables a single command, or [`SubCommand`], level setting. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .unset_setting(AppSettings::ColorAuto) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn unset_setting(mut self, setting: AppSettings) -> Self { + self.p.unset(setting); + self + } + + /// Disables multiple command, or [`SubCommand`], level settings. + /// + /// See [`AppSettings`] for a full list of possibilities and examples. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .unset_settings(&[AppSettings::ColorAuto, + /// AppSettings::AllowInvalidUtf8]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings`]: ./enum.AppSettings.html + pub fn unset_settings(mut self, settings: &[AppSettings]) -> Self { + for s in settings { + self.p.unset(*s); + } + self + } + + /// Sets the terminal width at which to wrap help messages. Defaults to `120`. Using `0` will + /// ignore terminal widths and use source formatting. + /// + /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows + /// if the `wrap_help` cargo "feature" has been used while compiling. If the terminal width + /// cannot be determined, `clap` defaults to `120`. + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// **NOTE:** This setting must be set **before** any subcommands are added! + /// + /// # Platform Specific + /// + /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width. + /// Even on those platforms, this setting is useful if for any reason the terminal width + /// cannot be determined. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .set_term_width(80) + /// # ; + /// ``` + pub fn set_term_width(mut self, width: usize) -> Self { + self.p.meta.term_w = Some(width); + self + } + + /// Sets the max terminal width at which to wrap help messages. Using `0` will ignore terminal + /// widths and use source formatting. + /// + /// `clap` automatically tries to determine the terminal width on Unix, Linux, macOS and Windows + /// if the `wrap_help` cargo "feature" has been used while compiling, but one might want to + /// limit the size (e.g. when the terminal is running fullscreen). + /// + /// **NOTE:** This setting applies globally and *not* on a per-command basis. + /// + /// **NOTE:** This setting must be set **before** any subcommands are added! + /// + /// # Platform Specific + /// + /// Only Unix, Linux, macOS and Windows support automatic determination of terminal width. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::App; + /// App::new("myprog") + /// .max_term_width(100) + /// # ; + /// ``` + pub fn max_term_width(mut self, w: usize) -> Self { + self.p.meta.max_w = Some(w); + self + } + + /// Adds an [argument] to the list of valid possibilities. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// // Adding a single "flag" argument with a short and help text, using Arg::with_name() + /// .arg( + /// Arg::with_name("debug") + /// .short("d") + /// .help("turns on debugging mode") + /// ) + /// // Adding a single "option" argument with a short, a long, and help text using the less + /// // verbose Arg::from_usage() + /// .arg( + /// Arg::from_usage("-c --config=[CONFIG] 'Optionally sets a config file to use'") + /// ) + /// # ; + /// ``` + /// [argument]: ./struct.Arg.html + pub fn arg<A: Into<Arg<'a, 'b>>>(mut self, a: A) -> Self { + self.p.add_arg(a.into()); + self + } + + /// Adds multiple [arguments] to the list of valid possibilities + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .args( + /// &[Arg::from_usage("[debug] -d 'turns on debugging info'"), + /// Arg::with_name("input").index(1).help("the input file to use")] + /// ) + /// # ; + /// ``` + /// [arguments]: ./struct.Arg.html + pub fn args(mut self, args: &[Arg<'a, 'b>]) -> Self { + for arg in args { + self.p.add_arg_ref(arg); + } + self + } + + /// A convenience method for adding a single [argument] from a usage type string. The string + /// used follows the same rules and syntax as [`Arg::from_usage`] + /// + /// **NOTE:** The downside to using this method is that you can not set any additional + /// properties of the [`Arg`] other than what [`Arg::from_usage`] supports. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .arg_from_usage("-c --config=<FILE> 'Sets a configuration file to use'") + /// # ; + /// ``` + /// [argument]: ./struct.Arg.html + /// [`Arg`]: ./struct.Arg.html + /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage + pub fn arg_from_usage(mut self, usage: &'a str) -> Self { + self.p.add_arg(Arg::from_usage(usage)); + self + } + + /// Adds multiple [arguments] at once from a usage string, one per line. See + /// [`Arg::from_usage`] for details on the syntax and rules supported. + /// + /// **NOTE:** Like [`App::arg_from_usage`] the downside is you only set properties for the + /// [`Arg`]s which [`Arg::from_usage`] supports. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// App::new("myprog") + /// .args_from_usage( + /// "-c --config=[FILE] 'Sets a configuration file to use' + /// [debug]... -d 'Sets the debugging level' + /// <FILE> 'The input file to use'" + /// ) + /// # ; + /// ``` + /// [arguments]: ./struct.Arg.html + /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage + /// [`App::arg_from_usage`]: ./struct.App.html#method.arg_from_usage + /// [`Arg`]: ./struct.Arg.html + pub fn args_from_usage(mut self, usage: &'a str) -> Self { + for line in usage.lines() { + let l = line.trim(); + if l.is_empty() { + continue; + } + self.p.add_arg(Arg::from_usage(l)); + } + self + } + + /// Allows adding a [`SubCommand`] alias, which function as "hidden" subcommands that + /// automatically dispatch as if this subcommand was used. This is more efficient, and easier + /// than creating multiple hidden subcommands as one only needs to check for the existence of + /// this command, and not all variants. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + als.push((name.into(), false)); + } else { + self.p.meta.aliases = Some(vec![(name.into(), false)]); + } + self + } + + /// Allows adding [`SubCommand`] aliases, which function as "hidden" subcommands that + /// automatically dispatch as if this subcommand was used. This is more efficient, and easier + /// than creating multiple hidden subcommands as one only needs to check for the existence of + /// this command, and not all variants. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .aliases(&["do-stuff", "do-tests", "tests"])) + /// .arg(Arg::with_name("input") + /// .help("the file to add") + /// .index(1) + /// .required(false)) + /// .get_matches_from(vec!["myprog", "do-tests"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn aliases(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + for n in names { + als.push((n, false)); + } + } else { + self.p.meta.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>()); + } + self + } + + /// Allows adding a [`SubCommand`] alias that functions exactly like those defined with + /// [`App::alias`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .visible_alias("do-stuff")) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App::alias`]: ./struct.App.html#method.alias + pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + als.push((name.into(), true)); + } else { + self.p.meta.aliases = Some(vec![(name.into(), true)]); + } + self + } + + /// Allows adding multiple [`SubCommand`] aliases that functions exactly like those defined + /// with [`App::aliases`], except that they are visible inside the help message. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// let m = App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .visible_aliases(&["do-stuff", "tests"])) + /// .get_matches_from(vec!["myprog", "do-stuff"]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App::aliases`]: ./struct.App.html#method.aliases + pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { + if let Some(ref mut als) = self.p.meta.aliases { + for n in names { + als.push((n, true)); + } + } else { + self.p.meta.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>()); + } + self + } + + /// Adds an [`ArgGroup`] to the application. [`ArgGroup`]s are a family of related arguments. + /// By placing them in a logical group, you can build easier requirement and exclusion rules. + /// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only* + /// one) argument from that group must be present at runtime. + /// + /// You can also do things such as name an [`ArgGroup`] as a conflict to another argument. + /// Meaning any of the arguments that belong to that group will cause a failure if present with + /// the conflicting argument. + /// + /// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead + /// of determining exactly which argument was used. + /// + /// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common + /// use + /// + /// # Examples + /// + /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one, + /// of the arguments from the specified group is present at runtime. + /// + /// ```no_run + /// # use clap::{App, ArgGroup}; + /// App::new("app") + /// .args_from_usage( + /// "--set-ver [ver] 'set the version manually' + /// --major 'auto increase major' + /// --minor 'auto increase minor' + /// --patch 'auto increase patch'") + /// .group(ArgGroup::with_name("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true)) + /// # ; + /// ``` + /// [`ArgGroup`]: ./struct.ArgGroup.html + pub fn group(mut self, group: ArgGroup<'a>) -> Self { + self.p.add_group(group); + self + } + + /// Adds multiple [`ArgGroup`]s to the [`App`] at once. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, ArgGroup}; + /// App::new("app") + /// .args_from_usage( + /// "--set-ver [ver] 'set the version manually' + /// --major 'auto increase major' + /// --minor 'auto increase minor' + /// --patch 'auto increase patch' + /// -c [FILE] 'a config file' + /// -i [IFACE] 'an interface'") + /// .groups(&[ + /// ArgGroup::with_name("vers") + /// .args(&["set-ver", "major", "minor","patch"]) + /// .required(true), + /// ArgGroup::with_name("input") + /// .args(&["c", "i"]) + /// ]) + /// # ; + /// ``` + /// [`ArgGroup`]: ./struct.ArgGroup.html + /// [`App`]: ./struct.App.html + pub fn groups(mut self, groups: &[ArgGroup<'a>]) -> Self { + for g in groups { + self = self.group(g.into()); + } + self + } + + /// Adds a [`SubCommand`] to the list of valid possibilities. Subcommands are effectively + /// sub-[`App`]s, because they can contain their own arguments, subcommands, version, usage, + /// etc. They also function just like [`App`]s, in that they get their own auto generated help, + /// version, and usage. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand}; + /// App::new("myprog") + /// .subcommand(SubCommand::with_name("config") + /// .about("Controls configuration features") + /// .arg_from_usage("<config> 'Required configuration file to use'")) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + pub fn subcommand(mut self, subcmd: App<'a, 'b>) -> Self { + self.p.add_subcommand(subcmd); + self + } + + /// Adds multiple subcommands to the list of valid possibilities by iterating over an + /// [`IntoIterator`] of [`SubCommand`]s + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, SubCommand}; + /// # App::new("myprog") + /// .subcommands( vec![ + /// SubCommand::with_name("config").about("Controls configuration functionality") + /// .arg(Arg::with_name("config_file").index(1)), + /// SubCommand::with_name("debug").about("Controls debug functionality")]) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`IntoIterator`]: https://doc.rust-lang.org/std/iter/trait.IntoIterator.html + pub fn subcommands<I>(mut self, subcmds: I) -> Self + where + I: IntoIterator<Item = App<'a, 'b>>, + { + for subcmd in subcmds { + self.p.add_subcommand(subcmd); + } + self + } + + /// Allows custom ordering of [`SubCommand`]s within the help message. Subcommands with a lower + /// value will be displayed first in the help message. This is helpful when one would like to + /// emphasise frequently used subcommands, or prioritize those towards the top of the list. + /// Duplicate values **are** allowed. Subcommands with duplicate display orders will be + /// displayed in alphabetical order. + /// + /// **NOTE:** The default is 999 for all subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, SubCommand}; + /// let m = App::new("cust-ord") + /// .subcommand(SubCommand::with_name("alpha") // typically subcommands are grouped + /// // alphabetically by name. Subcommands + /// // without a display_order have a value of + /// // 999 and are displayed alphabetically with + /// // all other 999 subcommands + /// .about("Some help and text")) + /// .subcommand(SubCommand::with_name("beta") + /// .display_order(1) // In order to force this subcommand to appear *first* + /// // all we have to do is give it a value lower than 999. + /// // Any other subcommands with a value of 1 will be displayed + /// // alphabetically with this one...then 2 values, then 3, etc. + /// .about("I should be first!")) + /// .get_matches_from(vec![ + /// "cust-ord", "--help" + /// ]); + /// ``` + /// + /// The above example displays the following help message + /// + /// ```text + /// cust-ord + /// + /// USAGE: + /// cust-ord [FLAGS] [OPTIONS] + /// + /// FLAGS: + /// -h, --help Prints help information + /// -V, --version Prints version information + /// + /// SUBCOMMANDS: + /// beta I should be first! + /// alpha Some help and text + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + pub fn display_order(mut self, ord: usize) -> Self { + self.p.meta.disp_ord = ord; + self + } + + /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same + /// method as if someone ran `-h` to request the help message + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// let mut app = App::new("myprog"); + /// app.print_help(); + /// ``` + /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html + /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn print_help(&mut self) -> ClapResult<()> { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self.p.propagate_globals(); + self.p.propagate_settings(); + self.p.derive_display_order(); + + self.p.create_help_and_version(); + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + self.write_help(&mut buf_w) + } + + /// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same + /// method as if someone ran `--help` to request the help message + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// let mut app = App::new("myprog"); + /// app.print_long_help(); + /// ``` + /// [`io::stdout()`]: https://doc.rust-lang.org/std/io/fn.stdout.html + /// [`BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn print_long_help(&mut self) -> ClapResult<()> { + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + self.write_long_help(&mut buf_w) + } + + /// Writes the full help message to the user to a [`io::Write`] object in the same method as if + /// the user ran `-h` + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// **NOTE:** There is a known bug where this method does not write propagated global arguments + /// or autogenerated arguments (i.e. the default help/version args). Prefer + /// [`App::write_long_help`] instead if possible! + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()> { + // PENDING ISSUE: 808 + // https://github.com/clap-rs/clap/issues/808 + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + // self.p.propagate_globals(); + // self.p.propagate_settings(); + // self.p.derive_display_order(); + // self.p.create_help_and_version(); + + Help::write_app_help(w, self, false) + } + + /// Writes the full help message to the user to a [`io::Write`] object in the same method as if + /// the user ran `--help` + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages + /// depending on if the user ran [`-h` (short)] or [`--help` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_long_help(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-h` (short)]: ./struct.Arg.html#method.help + /// [`--help` (long)]: ./struct.Arg.html#method.long_help + pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> ClapResult<()> { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + self.p.propagate_globals(); + self.p.propagate_settings(); + self.p.derive_display_order(); + self.p.create_help_and_version(); + + Help::write_app_help(w, self, true) + } + + /// Writes the version message to the user to a [`io::Write`] object as if the user ran `-V`. + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages + /// depending on if the user ran [`-V` (short)] or [`--version` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_version(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-V` (short)]: ./struct.App.html#method.version + /// [`--version` (long)]: ./struct.App.html#method.long_version + pub fn write_version<W: Write>(&self, w: &mut W) -> ClapResult<()> { + self.p.write_version(w, false).map_err(From::from) + } + + /// Writes the version message to the user to a [`io::Write`] object + /// + /// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages + /// depending on if the user ran [`-V` (short)] or [`--version` (long)] + /// + /// # Examples + /// + /// ```rust + /// # use clap::App; + /// use std::io; + /// let mut app = App::new("myprog"); + /// let mut out = io::stdout(); + /// app.write_long_version(&mut out).expect("failed to write to stdout"); + /// ``` + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + /// [`-V` (short)]: ./struct.App.html#method.version + /// [`--version` (long)]: ./struct.App.html#method.long_version + pub fn write_long_version<W: Write>(&self, w: &mut W) -> ClapResult<()> { + self.p.write_version(w, true).map_err(From::from) + } + + /// Generate a completions file for a specified shell at compile time. + /// + /// **NOTE:** to generate the file at compile time you must use a `build.rs` "Build Script" + /// + /// # Examples + /// + /// The following example generates a bash completion script via a `build.rs` script. In this + /// simple example, we'll demo a very small application with only a single subcommand and two + /// args. Real applications could be many multiple levels deep in subcommands, and have tens or + /// potentially hundreds of arguments. + /// + /// First, it helps if we separate out our `App` definition into a separate file. Whether you + /// do this as a function, or bare App definition is a matter of personal preference. + /// + /// ``` + /// // src/cli.rs + /// + /// use clap::{App, Arg, SubCommand}; + /// + /// pub fn build_cli() -> App<'static, 'static> { + /// App::new("compl") + /// .about("Tests completions") + /// .arg(Arg::with_name("file") + /// .help("some input file")) + /// .subcommand(SubCommand::with_name("test") + /// .about("tests things") + /// .arg(Arg::with_name("case") + /// .long("case") + /// .takes_value(true) + /// .help("the case to test"))) + /// } + /// ``` + /// + /// In our regular code, we can simply call this `build_cli()` function, then call + /// `get_matches()`, or any of the other normal methods directly after. For example: + /// + /// ```ignore + /// // src/main.rs + /// + /// mod cli; + /// + /// fn main() { + /// let m = cli::build_cli().get_matches(); + /// + /// // normal logic continues... + /// } + /// ``` + /// + /// Next, we set up our `Cargo.toml` to use a `build.rs` build script. + /// + /// ```toml + /// # Cargo.toml + /// build = "build.rs" + /// + /// [build-dependencies] + /// clap = "2.23" + /// ``` + /// + /// Next, we place a `build.rs` in our project root. + /// + /// ```ignore + /// extern crate clap; + /// + /// use clap::Shell; + /// + /// include!("src/cli.rs"); + /// + /// fn main() { + /// let outdir = match env::var_os("OUT_DIR") { + /// None => return, + /// Some(outdir) => outdir, + /// }; + /// let mut app = build_cli(); + /// app.gen_completions("myapp", // We need to specify the bin name manually + /// Shell::Bash, // Then say which shell to build completions for + /// outdir); // Then say where write the completions to + /// } + /// ``` + /// Now, once we compile there will be a `{bin_name}.bash` file in the directory. + /// Assuming we compiled with debug mode, it would be somewhere similar to + /// `<project>/target/debug/build/myapp-<hash>/out/myapp.bash`. + /// + /// Fish shell completions will use the file format `{bin_name}.fish` + pub fn gen_completions<T: Into<OsString>, S: Into<String>>( + &mut self, + bin_name: S, + for_shell: Shell, + out_dir: T, + ) { + self.p.meta.bin_name = Some(bin_name.into()); + self.p.gen_completions(for_shell, out_dir.into()); + } + + + /// Generate a completions file for a specified shell at runtime. Until `cargo install` can + /// install extra files like a completion script, this may be used e.g. in a command that + /// outputs the contents of the completion script, to be redirected into a file by the user. + /// + /// # Examples + /// + /// Assuming a separate `cli.rs` like the [example above](./struct.App.html#method.gen_completions), + /// we can let users generate a completion script using a command: + /// + /// ```ignore + /// // src/main.rs + /// + /// mod cli; + /// use std::io; + /// + /// fn main() { + /// let matches = cli::build_cli().get_matches(); + /// + /// if matches.is_present("generate-bash-completions") { + /// cli::build_cli().gen_completions_to("myapp", Shell::Bash, &mut io::stdout()); + /// } + /// + /// // normal logic continues... + /// } + /// + /// ``` + /// + /// Usage: + /// + /// ```shell + /// $ myapp generate-bash-completions > /usr/share/bash-completion/completions/myapp.bash + /// ``` + pub fn gen_completions_to<W: Write, S: Into<String>>( + &mut self, + bin_name: S, + for_shell: Shell, + buf: &mut W, + ) { + self.p.meta.bin_name = Some(bin_name.into()); + self.p.gen_completions_to(for_shell, buf); + } + + /// Starts the parsing process, upon a failed parse an error will be displayed to the user and + /// the process will exit with the appropriate error code. By default this method gets all user + /// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points, + /// which are legal on many platforms. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches(); + /// ``` + /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html + pub fn get_matches(self) -> ArgMatches<'a> { self.get_matches_from(&mut env::args_os()) } + + /// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting + /// the process on failed parse. By default this method gets matches from [`env::args_os`] + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a + /// [`ErrorKind::HelpDisplayed`] or [`ErrorKind::VersionDisplayed`] respectively. You must call + /// [`Error::exit`] or perform a [`std::process::exit`]. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_safe() + /// .unwrap_or_else( |e| e.exit() ); + /// ``` + /// [`env::args_os`]: https://doc.rust-lang.org/std/env/fn.args_os.html + /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed + /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed + /// [`Error::exit`]: ./struct.Error.html#method.exit + /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html + /// [`clap::Result`]: ./type.Result.html + /// [`clap::Error`]: ./struct.Error.html + /// [`kind`]: ./struct.Error.html + pub fn get_matches_safe(self) -> ClapResult<ArgMatches<'a>> { + // Start the parsing + self.get_matches_from_safe(&mut env::args_os()) + } + + /// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`] + /// and will automatically exit with an error message. This method, however, lets you specify + /// what iterator to use when performing matches, such as a [`Vec`] of your making. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`AppSettings::NoBinaryName`] is used + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_from(arg_vec); + /// ``` + /// [`App::get_matches`]: ./struct.App.html#method.get_matches + /// [`clap::Result`]: ./type.Result.html + /// [`Vec`]: https://doc.rust-lang.org/std/vec/struct.Vec.html + /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName + pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches<'a> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + self.get_matches_from_safe_borrow(itr).unwrap_or_else(|e| { + // Otherwise, write to stderr and exit + if e.use_stderr() { + wlnerr!("{}", e.message); + if self.p.is_set(AppSettings::WaitOnError) { + wlnerr!("\nPress [ENTER] / [RETURN] to continue..."); + let mut s = String::new(); + let i = io::stdin(); + i.lock().read_line(&mut s).unwrap(); + } + drop(self); + drop(e); + process::exit(1); + } + + drop(self); + e.exit() + }) + } + + /// Starts the parsing process. A combination of [`App::get_matches_from`], and + /// [`App::get_matches_safe`] + /// + /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are + /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::HelpDisplayed`] + /// or [`ErrorKind::VersionDisplayed`] respectively. You must call [`Error::exit`] or + /// perform a [`std::process::exit`] yourself. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`AppSettings::NoBinaryName`] is used + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let matches = App::new("myprog") + /// // Args and options go here... + /// .get_matches_from_safe(arg_vec) + /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) }); + /// ``` + /// [`App::get_matches_from`]: ./struct.App.html#method.get_matches_from + /// [`App::get_matches_safe`]: ./struct.App.html#method.get_matches_safe + /// [`ErrorKind::HelpDisplayed`]: ./enum.ErrorKind.html#variant.HelpDisplayed + /// [`ErrorKind::VersionDisplayed`]: ./enum.ErrorKind.html#variant.VersionDisplayed + /// [`Error::exit`]: ./struct.Error.html#method.exit + /// [`std::process::exit`]: https://doc.rust-lang.org/std/process/fn.exit.html + /// [`clap::Error`]: ./struct.Error.html + /// [`Error::exit`]: ./struct.Error.html#method.exit + /// [`kind`]: ./struct.Error.html + /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName + pub fn get_matches_from_safe<I, T>(mut self, itr: I) -> ClapResult<ArgMatches<'a>> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + self.get_matches_from_safe_borrow(itr) + } + + /// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not + /// the desired functionality, instead prefer [`App::get_matches_from_safe`] which *does* + /// consume `self`. + /// + /// **NOTE:** The first argument will be parsed as the binary name unless + /// [`AppSettings::NoBinaryName`] is used + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg}; + /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"]; + /// + /// let mut app = App::new("myprog"); + /// // Args and options go here... + /// let matches = app.get_matches_from_safe_borrow(arg_vec) + /// .unwrap_or_else( |e| { panic!("An error occurs: {}", e) }); + /// ``` + /// [`App`]: ./struct.App.html + /// [`App::get_matches_from_safe`]: ./struct.App.html#method.get_matches_from_safe + /// [`AppSettings::NoBinaryName`]: ./enum.AppSettings.html#variant.NoBinaryName + pub fn get_matches_from_safe_borrow<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches<'a>> + where + I: IntoIterator<Item = T>, + T: Into<OsString> + Clone, + { + // If there are global arguments, or settings we need to propagate them down to subcommands + // before parsing incase we run into a subcommand + if !self.p.is_set(AppSettings::Propagated) { + self.p.propagate_globals(); + self.p.propagate_settings(); + self.p.derive_display_order(); + self.p.set(AppSettings::Propagated); + } + + let mut matcher = ArgMatcher::new(); + + let mut it = itr.into_iter(); + // Get the name of the program (argument 1 of env::args()) and determine the + // actual file + // that was used to execute the program. This is because a program called + // ./target/release/my_prog -a + // will have two arguments, './target/release/my_prog', '-a' but we don't want + // to display + // the full path when displaying help messages and such + if !self.p.is_set(AppSettings::NoBinaryName) { + if let Some(name) = it.next() { + let bn_os = name.into(); + let p = Path::new(&*bn_os); + if let Some(f) = p.file_name() { + if let Some(s) = f.to_os_string().to_str() { + if self.p.meta.bin_name.is_none() { + self.p.meta.bin_name = Some(s.to_owned()); + } + } + } + } + } + + // do the real parsing + if let Err(e) = self.p.get_matches_with(&mut matcher, &mut it.peekable()) { + return Err(e); + } + + let global_arg_vec: Vec<&str> = (&self).p.global_args.iter().map(|ga| ga.b.name).collect(); + matcher.propagate_globals(&global_arg_vec); + + Ok(matcher.into()) + } +} + +#[cfg(feature = "yaml")] +impl<'a> From<&'a Yaml> for App<'a, 'a> { + fn from(mut yaml: &'a Yaml) -> Self { + use args::SubCommand; + // We WANT this to panic on error...so expect() is good. + let mut is_sc = None; + let mut a = if let Some(name) = yaml["name"].as_str() { + App::new(name) + } else { + let yaml_hash = yaml.as_hash().unwrap(); + let sc_key = yaml_hash.keys().nth(0).unwrap(); + is_sc = Some(yaml_hash.get(sc_key).unwrap()); + App::new(sc_key.as_str().unwrap()) + }; + yaml = if let Some(sc) = is_sc { sc } else { yaml }; + + macro_rules! yaml_str { + ($a:ident, $y:ident, $i:ident) => { + if let Some(v) = $y[stringify!($i)].as_str() { + $a = $a.$i(v); + } else if $y[stringify!($i)] != Yaml::BadValue { + panic!("Failed to convert YAML value {:?} to a string", $y[stringify!($i)]); + } + }; + } + + yaml_str!(a, yaml, version); + yaml_str!(a, yaml, long_version); + yaml_str!(a, yaml, author); + yaml_str!(a, yaml, bin_name); + yaml_str!(a, yaml, about); + yaml_str!(a, yaml, long_about); + yaml_str!(a, yaml, before_help); + yaml_str!(a, yaml, after_help); + yaml_str!(a, yaml, template); + yaml_str!(a, yaml, usage); + yaml_str!(a, yaml, help); + yaml_str!(a, yaml, help_short); + yaml_str!(a, yaml, version_short); + yaml_str!(a, yaml, help_message); + yaml_str!(a, yaml, version_message); + yaml_str!(a, yaml, alias); + yaml_str!(a, yaml, visible_alias); + + if let Some(v) = yaml["display_order"].as_i64() { + a = a.display_order(v as usize); + } else if yaml["display_order"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a u64", + yaml["display_order"] + ); + } + if let Some(v) = yaml["setting"].as_str() { + a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["setting"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to an AppSetting", + yaml["setting"] + ); + } + if let Some(v) = yaml["settings"].as_vec() { + for ys in v { + if let Some(s) = ys.as_str() { + a = a.setting(s.parse().expect("unknown AppSetting found in YAML file")); + } + } + } else if let Some(v) = yaml["settings"].as_str() { + a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["settings"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a string", + yaml["settings"] + ); + } + if let Some(v) = yaml["global_setting"].as_str() { + a = a.setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["global_setting"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to an AppSetting", + yaml["setting"] + ); + } + if let Some(v) = yaml["global_settings"].as_vec() { + for ys in v { + if let Some(s) = ys.as_str() { + a = a.global_setting(s.parse().expect("unknown AppSetting found in YAML file")); + } + } + } else if let Some(v) = yaml["global_settings"].as_str() { + a = a.global_setting(v.parse().expect("unknown AppSetting found in YAML file")); + } else if yaml["global_settings"] != Yaml::BadValue { + panic!( + "Failed to convert YAML value {:?} to a string", + yaml["global_settings"] + ); + } + + macro_rules! vec_or_str { + ($a:ident, $y:ident, $as_vec:ident, $as_single:ident) => {{ + let maybe_vec = $y[stringify!($as_vec)].as_vec(); + if let Some(vec) = maybe_vec { + for ys in vec { + if let Some(s) = ys.as_str() { + $a = $a.$as_single(s); + } else { + panic!("Failed to convert YAML value {:?} to a string", ys); + } + } + } else { + if let Some(s) = $y[stringify!($as_vec)].as_str() { + $a = $a.$as_single(s); + } else if $y[stringify!($as_vec)] != Yaml::BadValue { + panic!("Failed to convert YAML value {:?} to either a vec or string", $y[stringify!($as_vec)]); + } + } + $a + } + }; + } + + a = vec_or_str!(a, yaml, aliases, alias); + a = vec_or_str!(a, yaml, visible_aliases, visible_alias); + + if let Some(v) = yaml["args"].as_vec() { + for arg_yaml in v { + a = a.arg(Arg::from_yaml(arg_yaml.as_hash().unwrap())); + } + } + if let Some(v) = yaml["subcommands"].as_vec() { + for sc_yaml in v { + a = a.subcommand(SubCommand::from_yaml(sc_yaml)); + } + } + if let Some(v) = yaml["groups"].as_vec() { + for ag_yaml in v { + a = a.group(ArgGroup::from(ag_yaml.as_hash().unwrap())); + } + } + + a + } +} + +impl<'a, 'b> Clone for App<'a, 'b> { + fn clone(&self) -> Self { App { p: self.p.clone() } } +} + +impl<'n, 'e> AnyArg<'n, 'e> for App<'n, 'e> { + fn name(&self) -> &'n str { + "" + } + fn overrides(&self) -> Option<&[&'e str]> { None } + fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { None } + fn blacklist(&self) -> Option<&[&'e str]> { None } + fn required_unless(&self) -> Option<&[&'e str]> { None } + fn val_names(&self) -> Option<&VecMap<&'e str>> { None } + fn is_set(&self, _: ArgSettings) -> bool { false } + fn val_terminator(&self) -> Option<&'e str> { None } + fn set(&mut self, _: ArgSettings) { + unreachable!("App struct does not support AnyArg::set, this is a bug!") + } + fn has_switch(&self) -> bool { false } + fn max_vals(&self) -> Option<u64> { None } + fn num_vals(&self) -> Option<u64> { None } + fn possible_vals(&self) -> Option<&[&'e str]> { None } + fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { None } + fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> { None } + fn min_vals(&self) -> Option<u64> { None } + fn short(&self) -> Option<char> { None } + fn long(&self) -> Option<&'e str> { None } + fn val_delim(&self) -> Option<char> { None } + fn takes_value(&self) -> bool { true } + fn help(&self) -> Option<&'e str> { self.p.meta.about } + fn long_help(&self) -> Option<&'e str> { self.p.meta.long_about } + fn default_val(&self) -> Option<&'e OsStr> { None } + fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> { + None + } + fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { None } + fn longest_filter(&self) -> bool { true } + fn aliases(&self) -> Option<Vec<&'e str>> { + if let Some(ref aliases) = self.p.meta.aliases { + let vis_aliases: Vec<_> = aliases + .iter() + .filter_map(|&(n, v)| if v { Some(n) } else { None }) + .collect(); + if vis_aliases.is_empty() { + None + } else { + Some(vis_aliases) + } + } else { + None + } + } +} + +impl<'n, 'e> fmt::Display for App<'n, 'e> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.p.meta.name) } +} diff --git a/clap/src/app/parser.rs b/clap/src/app/parser.rs new file mode 100644 index 0000000..decfde4 --- /dev/null +++ b/clap/src/app/parser.rs @@ -0,0 +1,2167 @@ +// Std +use std::ffi::{OsStr, OsString}; +use std::fmt::Display; +use std::fs::File; +use std::io::{self, BufWriter, Write}; +#[cfg(all(feature = "debug", not(any(target_os = "windows", target_arch = "wasm32"))))] +use std::os::unix::ffi::OsStrExt; +#[cfg(all(feature = "debug", any(target_os = "windows", target_arch = "wasm32")))] +use osstringext::OsStrExt3; +use std::path::PathBuf; +use std::slice::Iter; +use std::iter::Peekable; +use std::cell::Cell; + +// Internal +use INTERNAL_ERROR_MSG; +use INVALID_UTF8; +use SubCommand; +use app::App; +use app::help::Help; +use app::meta::AppMeta; +use app::settings::AppFlags; +use args::{AnyArg, Arg, ArgGroup, ArgMatcher, Base, FlagBuilder, OptBuilder, PosBuilder, Switched}; +use args::settings::ArgSettings; +use completions::ComplGen; +use errors::{Error, ErrorKind}; +use errors::Result as ClapResult; +use fmt::ColorWhen; +use osstringext::OsStrExt2; +use completions::Shell; +use suggestions; +use app::settings::AppSettings as AS; +use app::validator::Validator; +use app::usage; +use map::{self, VecMap}; + +#[derive(Debug, PartialEq, Copy, Clone)] +#[doc(hidden)] +pub enum ParseResult<'a> { + Flag, + Opt(&'a str), + Pos(&'a str), + MaybeHyphenValue, + MaybeNegNum, + NotFound, + ValuesDone, +} + +#[allow(missing_debug_implementations)] +#[doc(hidden)] +#[derive(Clone, Default)] +pub struct Parser<'a, 'b> +where + 'a: 'b, +{ + pub meta: AppMeta<'b>, + settings: AppFlags, + pub g_settings: AppFlags, + pub flags: Vec<FlagBuilder<'a, 'b>>, + pub opts: Vec<OptBuilder<'a, 'b>>, + pub positionals: VecMap<PosBuilder<'a, 'b>>, + pub subcommands: Vec<App<'a, 'b>>, + pub groups: Vec<ArgGroup<'a>>, + pub global_args: Vec<Arg<'a, 'b>>, + pub required: Vec<&'a str>, + pub r_ifs: Vec<(&'a str, &'b str, &'a str)>, + pub overrides: Vec<(&'b str, &'a str)>, + help_short: Option<char>, + version_short: Option<char>, + cache: Option<&'a str>, + pub help_message: Option<&'a str>, + pub version_message: Option<&'a str>, + cur_idx: Cell<usize>, +} + +impl<'a, 'b> Parser<'a, 'b> +where + 'a: 'b, +{ + pub fn with_name(n: String) -> Self { + Parser { + meta: AppMeta::with_name(n), + g_settings: AppFlags::zeroed(), + cur_idx: Cell::new(0), + ..Default::default() + } + } + + pub fn help_short(&mut self, s: &str) { + let c = s.trim_left_matches(|c| c == '-') + .chars() + .nth(0) + .unwrap_or('h'); + self.help_short = Some(c); + } + + pub fn version_short(&mut self, s: &str) { + let c = s.trim_left_matches(|c| c == '-') + .chars() + .nth(0) + .unwrap_or('V'); + self.version_short = Some(c); + } + + pub fn gen_completions_to<W: Write>(&mut self, for_shell: Shell, buf: &mut W) { + if !self.is_set(AS::Propagated) { + self.propagate_help_version(); + self.build_bin_names(); + self.propagate_globals(); + self.propagate_settings(); + self.set(AS::Propagated); + } + + ComplGen::new(self).generate(for_shell, buf) + } + + pub fn gen_completions(&mut self, for_shell: Shell, od: OsString) { + use std::error::Error; + + let out_dir = PathBuf::from(od); + let name = &*self.meta.bin_name.as_ref().unwrap().clone(); + let file_name = match for_shell { + Shell::Bash => format!("{}.bash", name), + Shell::Fish => format!("{}.fish", name), + Shell::Zsh => format!("_{}", name), + Shell::PowerShell => format!("_{}.ps1", name), + Shell::Elvish => format!("{}.elv", name), + }; + + let mut file = match File::create(out_dir.join(file_name)) { + Err(why) => panic!("couldn't create completion file: {}", why.description()), + Ok(file) => file, + }; + self.gen_completions_to(for_shell, &mut file) + } + + #[inline] + fn app_debug_asserts(&self) -> bool { + assert!(self.verify_positionals()); + let should_err = self.groups.iter().all(|g| { + g.args.iter().all(|arg| { + (self.flags.iter().any(|f| &f.b.name == arg) + || self.opts.iter().any(|o| &o.b.name == arg) + || self.positionals.values().any(|p| &p.b.name == arg) + || self.groups.iter().any(|g| &g.name == arg)) + }) + }); + let g = self.groups.iter().find(|g| { + g.args.iter().any(|arg| { + !(self.flags.iter().any(|f| &f.b.name == arg) + || self.opts.iter().any(|o| &o.b.name == arg) + || self.positionals.values().any(|p| &p.b.name == arg) + || self.groups.iter().any(|g| &g.name == arg)) + }) + }); + assert!( + should_err, + "The group '{}' contains the arg '{}' that doesn't actually exist.", + g.unwrap().name, + g.unwrap() + .args + .iter() + .find(|arg| !(self.flags.iter().any(|f| &&f.b.name == arg) + || self.opts.iter().any(|o| &&o.b.name == arg) + || self.positionals.values().any(|p| &&p.b.name == arg) + || self.groups.iter().any(|g| &&g.name == arg))) + .unwrap() + ); + true + } + + #[inline] + fn debug_asserts(&self, a: &Arg) -> bool { + assert!( + !arg_names!(self).any(|name| name == a.b.name), + format!("Non-unique argument name: {} is already in use", a.b.name) + ); + if let Some(l) = a.s.long { + assert!( + !self.contains_long(l), + "Argument long must be unique\n\n\t--{} is already in use", + l + ); + } + if let Some(s) = a.s.short { + assert!( + !self.contains_short(s), + "Argument short must be unique\n\n\t-{} is already in use", + s + ); + } + let i = if a.index.is_none() { + (self.positionals.len() + 1) + } else { + a.index.unwrap() as usize + }; + assert!( + !self.positionals.contains_key(i), + "Argument \"{}\" has the same index as another positional \ + argument\n\n\tPerhaps try .multiple(true) to allow one positional argument \ + to take multiple values", + a.b.name + ); + assert!( + !(a.is_set(ArgSettings::Required) && a.is_set(ArgSettings::Global)), + "Global arguments cannot be required.\n\n\t'{}' is marked as \ + global and required", + a.b.name + ); + if a.b.is_set(ArgSettings::Last) { + assert!( + !self.positionals + .values() + .any(|p| p.b.is_set(ArgSettings::Last)), + "Only one positional argument may have last(true) set. Found two." + ); + assert!(a.s.long.is_none(), + "Flags or Options may not have last(true) set. {} has both a long and last(true) set.", + a.b.name); + assert!(a.s.short.is_none(), + "Flags or Options may not have last(true) set. {} has both a short and last(true) set.", + a.b.name); + } + true + } + + #[inline] + fn add_conditional_reqs(&mut self, a: &Arg<'a, 'b>) { + if let Some(ref r_ifs) = a.r_ifs { + for &(arg, val) in r_ifs { + self.r_ifs.push((arg, val, a.b.name)); + } + } + } + + #[inline] + fn add_arg_groups(&mut self, a: &Arg<'a, 'b>) { + if let Some(ref grps) = a.b.groups { + for g in grps { + let mut found = false; + if let Some(ref mut ag) = self.groups.iter_mut().find(|grp| &grp.name == g) { + ag.args.push(a.b.name); + found = true; + } + if !found { + let mut ag = ArgGroup::with_name(g); + ag.args.push(a.b.name); + self.groups.push(ag); + } + } + } + } + + #[inline] + fn add_reqs(&mut self, a: &Arg<'a, 'b>) { + if a.is_set(ArgSettings::Required) { + // If the arg is required, add all it's requirements to master required list + self.required.push(a.b.name); + if let Some(ref areqs) = a.b.requires { + for name in areqs + .iter() + .filter(|&&(val, _)| val.is_none()) + .map(|&(_, name)| name) + { + self.required.push(name); + } + } + } + } + + #[inline] + fn implied_settings(&mut self, a: &Arg<'a, 'b>) { + if a.is_set(ArgSettings::Last) { + // if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args + // in the usage string don't get confused or left out. + self.set(AS::DontCollapseArgsInUsage); + self.set(AS::ContainsLast); + } + if let Some(l) = a.s.long { + if l == "version" { + self.unset(AS::NeedsLongVersion); + } else if l == "help" { + self.unset(AS::NeedsLongHelp); + } + } + } + + // actually adds the arguments + pub fn add_arg(&mut self, a: Arg<'a, 'b>) { + // if it's global we have to clone anyways + if a.is_set(ArgSettings::Global) { + return self.add_arg_ref(&a); + } + debug_assert!(self.debug_asserts(&a)); + self.add_conditional_reqs(&a); + self.add_arg_groups(&a); + self.add_reqs(&a); + self.implied_settings(&a); + if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) { + let i = if a.index.is_none() { + (self.positionals.len() + 1) + } else { + a.index.unwrap() as usize + }; + self.positionals + .insert(i, PosBuilder::from_arg(a, i as u64)); + } else if a.is_set(ArgSettings::TakesValue) { + let mut ob = OptBuilder::from(a); + ob.s.unified_ord = self.flags.len() + self.opts.len(); + self.opts.push(ob); + } else { + let mut fb = FlagBuilder::from(a); + fb.s.unified_ord = self.flags.len() + self.opts.len(); + self.flags.push(fb); + } + } + // actually adds the arguments but from a borrow (which means we have to do some cloning) + pub fn add_arg_ref(&mut self, a: &Arg<'a, 'b>) { + debug_assert!(self.debug_asserts(a)); + self.add_conditional_reqs(a); + self.add_arg_groups(a); + self.add_reqs(a); + self.implied_settings(a); + if a.index.is_some() || (a.s.short.is_none() && a.s.long.is_none()) { + let i = if a.index.is_none() { + (self.positionals.len() + 1) + } else { + a.index.unwrap() as usize + }; + let pb = PosBuilder::from_arg_ref(a, i as u64); + self.positionals.insert(i, pb); + } else if a.is_set(ArgSettings::TakesValue) { + let mut ob = OptBuilder::from(a); + ob.s.unified_ord = self.flags.len() + self.opts.len(); + self.opts.push(ob); + } else { + let mut fb = FlagBuilder::from(a); + fb.s.unified_ord = self.flags.len() + self.opts.len(); + self.flags.push(fb); + } + if a.is_set(ArgSettings::Global) { + self.global_args.push(a.into()); + } + } + + pub fn add_group(&mut self, group: ArgGroup<'a>) { + if group.required { + self.required.push(group.name); + if let Some(ref reqs) = group.requires { + self.required.extend_from_slice(reqs); + } + // if let Some(ref bl) = group.conflicts { + // self.blacklist.extend_from_slice(bl); + // } + } + if self.groups.iter().any(|g| g.name == group.name) { + let grp = self.groups + .iter_mut() + .find(|g| g.name == group.name) + .expect(INTERNAL_ERROR_MSG); + grp.args.extend_from_slice(&group.args); + grp.requires = group.requires.clone(); + grp.conflicts = group.conflicts.clone(); + grp.required = group.required; + } else { + self.groups.push(group); + } + } + + pub fn add_subcommand(&mut self, mut subcmd: App<'a, 'b>) { + debugln!( + "Parser::add_subcommand: term_w={:?}, name={}", + self.meta.term_w, + subcmd.p.meta.name + ); + subcmd.p.meta.term_w = self.meta.term_w; + if subcmd.p.meta.name == "help" { + self.unset(AS::NeedsSubcommandHelp); + } + + self.subcommands.push(subcmd); + } + + pub fn propagate_settings(&mut self) { + debugln!( + "Parser::propagate_settings: self={}, g_settings={:#?}", + self.meta.name, + self.g_settings + ); + for sc in &mut self.subcommands { + debugln!( + "Parser::propagate_settings: sc={}, settings={:#?}, g_settings={:#?}", + sc.p.meta.name, + sc.p.settings, + sc.p.g_settings + ); + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + let vsc = self.settings.is_set(AS::VersionlessSubcommands); + let gv = self.settings.is_set(AS::GlobalVersion); + + if vsc { + sc.p.set(AS::DisableVersion); + } + if gv && sc.p.meta.version.is_none() && self.meta.version.is_some() { + sc.p.set(AS::GlobalVersion); + sc.p.meta.version = Some(self.meta.version.unwrap()); + } + sc.p.settings = sc.p.settings | self.g_settings; + sc.p.g_settings = sc.p.g_settings | self.g_settings; + sc.p.meta.term_w = self.meta.term_w; + sc.p.meta.max_w = self.meta.max_w; + } + sc.p.propagate_settings(); + } + } + + #[cfg_attr(feature = "lints", allow(needless_borrow))] + pub fn derive_display_order(&mut self) { + if self.is_set(AS::DeriveDisplayOrder) { + let unified = self.is_set(AS::UnifiedHelpMessage); + for (i, o) in self.opts + .iter_mut() + .enumerate() + .filter(|&(_, ref o)| o.s.disp_ord == 999) + { + o.s.disp_ord = if unified { o.s.unified_ord } else { i }; + } + for (i, f) in self.flags + .iter_mut() + .enumerate() + .filter(|&(_, ref f)| f.s.disp_ord == 999) + { + f.s.disp_ord = if unified { f.s.unified_ord } else { i }; + } + for (i, sc) in &mut self.subcommands + .iter_mut() + .enumerate() + .filter(|&(_, ref sc)| sc.p.meta.disp_ord == 999) + { + sc.p.meta.disp_ord = i; + } + } + for sc in &mut self.subcommands { + sc.p.derive_display_order(); + } + } + + pub fn required(&self) -> Iter<&str> { self.required.iter() } + + #[cfg_attr(feature = "lints", allow(needless_borrow))] + #[inline] + pub fn has_args(&self) -> bool { + !(self.flags.is_empty() && self.opts.is_empty() && self.positionals.is_empty()) + } + + #[inline] + pub fn has_opts(&self) -> bool { !self.opts.is_empty() } + + #[inline] + pub fn has_flags(&self) -> bool { !self.flags.is_empty() } + + #[inline] + pub fn has_positionals(&self) -> bool { !self.positionals.is_empty() } + + #[inline] + pub fn has_subcommands(&self) -> bool { !self.subcommands.is_empty() } + + #[inline] + pub fn has_visible_opts(&self) -> bool { + if self.opts.is_empty() { + return false; + } + self.opts.iter().any(|o| !o.is_set(ArgSettings::Hidden)) + } + + #[inline] + pub fn has_visible_flags(&self) -> bool { + if self.flags.is_empty() { + return false; + } + self.flags.iter().any(|f| !f.is_set(ArgSettings::Hidden)) + } + + #[inline] + pub fn has_visible_positionals(&self) -> bool { + if self.positionals.is_empty() { + return false; + } + self.positionals + .values() + .any(|p| !p.is_set(ArgSettings::Hidden)) + } + + #[inline] + pub fn has_visible_subcommands(&self) -> bool { + self.has_subcommands() + && self.subcommands + .iter() + .filter(|sc| sc.p.meta.name != "help") + .any(|sc| !sc.p.is_set(AS::Hidden)) + } + + #[inline] + pub fn is_set(&self, s: AS) -> bool { self.settings.is_set(s) } + + #[inline] + pub fn set(&mut self, s: AS) { self.settings.set(s) } + + #[inline] + pub fn unset(&mut self, s: AS) { self.settings.unset(s) } + + #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))] + pub fn verify_positionals(&self) -> bool { + // Because you must wait until all arguments have been supplied, this is the first chance + // to make assertions on positional argument indexes + // + // First we verify that the index highest supplied index, is equal to the number of + // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3 + // but no 2) + if let Some((idx, p)) = self.positionals.iter().rev().next() { + assert!( + !(idx != self.positionals.len()), + "Found positional argument \"{}\" whose index is {} but there \ + are only {} positional arguments defined", + p.b.name, + idx, + self.positionals.len() + ); + } + + // Next we verify that only the highest index has a .multiple(true) (if any) + if self.positionals.values().any(|a| { + a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) + }) { + let mut it = self.positionals.values().rev(); + let last = it.next().unwrap(); + let second_to_last = it.next().unwrap(); + // Either the final positional is required + // Or the second to last has a terminator or .last(true) set + let ok = last.is_set(ArgSettings::Required) + || (second_to_last.v.terminator.is_some() + || second_to_last.b.is_set(ArgSettings::Last)) + || last.is_set(ArgSettings::Last); + assert!( + ok, + "When using a positional argument with .multiple(true) that is *not the \ + last* positional argument, the last positional argument (i.e the one \ + with the highest index) *must* have .required(true) or .last(true) set." + ); + let ok = second_to_last.is_set(ArgSettings::Multiple) || last.is_set(ArgSettings::Last); + assert!( + ok, + "Only the last positional argument, or second to last positional \ + argument may be set to .multiple(true)" + ); + + let count = self.positionals + .values() + .filter(|p| p.b.settings.is_set(ArgSettings::Multiple) && p.v.num_vals.is_none()) + .count(); + let ok = count <= 1 + || (last.is_set(ArgSettings::Last) && last.is_set(ArgSettings::Multiple) + && second_to_last.is_set(ArgSettings::Multiple) + && count == 2); + assert!( + ok, + "Only one positional argument with .multiple(true) set is allowed per \ + command, unless the second one also has .last(true) set" + ); + } + + if self.is_set(AS::AllowMissingPositional) { + // Check that if a required positional argument is found, all positions with a lower + // index are also required. + let mut found = false; + let mut foundx2 = false; + for p in self.positionals.values().rev() { + if foundx2 && !p.b.settings.is_set(ArgSettings::Required) { + assert!( + p.b.is_set(ArgSettings::Required), + "Found positional argument which is not required with a lower \ + index than a required positional argument by two or more: {:?} \ + index {}", + p.b.name, + p.index + ); + } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog <req1> [opt1] -- <req2> + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + if found { + foundx2 = true; + continue; + } + found = true; + continue; + } else { + found = false; + } + } + } else { + // Check that if a required positional argument is found, all positions with a lower + // index are also required + let mut found = false; + for p in self.positionals.values().rev() { + if found { + assert!( + p.b.is_set(ArgSettings::Required), + "Found positional argument which is not required with a lower \ + index than a required positional argument: {:?} index {}", + p.b.name, + p.index + ); + } else if p.b.is_set(ArgSettings::Required) && !p.b.is_set(ArgSettings::Last) { + // Args that .last(true) don't count since they can be required and have + // positionals with a lower index that aren't required + // Imagine: prog <req1> [opt1] -- <req2> + // Both of these are valid invocations: + // $ prog r1 -- r2 + // $ prog r1 o1 -- r2 + found = true; + continue; + } + } + } + if self.positionals + .values() + .any(|p| p.b.is_set(ArgSettings::Last) && p.b.is_set(ArgSettings::Required)) + && self.has_subcommands() && !self.is_set(AS::SubcommandsNegateReqs) + { + panic!( + "Having a required positional argument with .last(true) set *and* child \ + subcommands without setting SubcommandsNegateReqs isn't compatible." + ); + } + + true + } + + pub fn propagate_globals(&mut self) { + for sc in &mut self.subcommands { + // We have to create a new scope in order to tell rustc the borrow of `sc` is + // done and to recursively call this method + { + for a in &self.global_args { + sc.p.add_arg_ref(a); + } + } + sc.p.propagate_globals(); + } + } + + // Checks if the arg matches a subcommand name, or any of it's aliases (if defined) + fn possible_subcommand(&self, arg_os: &OsStr) -> (bool, Option<&str>) { + #[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] + use std::os::unix::ffi::OsStrExt; + #[cfg(any(target_os = "windows", target_arch = "wasm32"))] + use osstringext::OsStrExt3; + debugln!("Parser::possible_subcommand: arg={:?}", arg_os); + fn starts(h: &str, n: &OsStr) -> bool { + let n_bytes = n.as_bytes(); + let h_bytes = OsStr::new(h).as_bytes(); + + h_bytes.starts_with(n_bytes) + } + + if self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound) { + return (false, None); + } + if !self.is_set(AS::InferSubcommands) { + if let Some(sc) = find_subcmd!(self, arg_os) { + return (true, Some(&sc.p.meta.name)); + } + } else { + let v = self.subcommands + .iter() + .filter(|s| { + starts(&s.p.meta.name[..], &*arg_os) + || (s.p.meta.aliases.is_some() + && s.p + .meta + .aliases + .as_ref() + .unwrap() + .iter() + .filter(|&&(a, _)| starts(a, &*arg_os)) + .count() == 1) + }) + .map(|sc| &sc.p.meta.name) + .collect::<Vec<_>>(); + + for sc in &v { + if OsStr::new(sc) == arg_os { + return (true, Some(sc)); + } + } + + if v.len() == 1 { + return (true, Some(v[0])); + } + } + (false, None) + } + + fn parse_help_subcommand<I, T>(&self, it: &mut I) -> ClapResult<ParseResult<'a>> + where + I: Iterator<Item = T>, + T: Into<OsString>, + { + debugln!("Parser::parse_help_subcommand;"); + let cmds: Vec<OsString> = it.map(|c| c.into()).collect(); + let mut help_help = false; + let mut bin_name = self.meta + .bin_name + .as_ref() + .unwrap_or(&self.meta.name) + .clone(); + let mut sc = { + let mut sc: &Parser = self; + for (i, cmd) in cmds.iter().enumerate() { + if &*cmd.to_string_lossy() == "help" { + // cmd help help + help_help = true; + } + if let Some(c) = sc.subcommands + .iter() + .find(|s| &*s.p.meta.name == cmd) + .map(|sc| &sc.p) + { + sc = c; + if i == cmds.len() - 1 { + break; + } + } else if let Some(c) = sc.subcommands + .iter() + .find(|s| { + if let Some(ref als) = s.p.meta.aliases { + als.iter().any(|&(a, _)| a == &*cmd.to_string_lossy()) + } else { + false + } + }) + .map(|sc| &sc.p) + { + sc = c; + if i == cmds.len() - 1 { + break; + } + } else { + return Err(Error::unrecognized_subcommand( + cmd.to_string_lossy().into_owned(), + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + self.color(), + )); + } + bin_name = format!("{} {}", bin_name, &*sc.meta.name); + } + sc.clone() + }; + if help_help { + let mut pb = PosBuilder::new("subcommand", 1); + pb.b.help = Some("The subcommand whose help message to display"); + pb.set(ArgSettings::Multiple); + sc.positionals.insert(1, pb); + sc.settings = sc.settings | self.g_settings; + } else { + sc.create_help_and_version(); + } + if sc.meta.bin_name != self.meta.bin_name { + sc.meta.bin_name = Some(format!("{} {}", bin_name, sc.meta.name)); + } + Err(sc._help(false)) + } + + // allow wrong self convention due to self.valid_neg_num = true and it's a private method + #[cfg_attr(feature = "lints", allow(wrong_self_convention))] + fn is_new_arg(&mut self, arg_os: &OsStr, needs_val_of: ParseResult) -> bool { + debugln!("Parser::is_new_arg:{:?}:{:?}", arg_os, needs_val_of); + let app_wide_settings = if self.is_set(AS::AllowLeadingHyphen) { + true + } else if self.is_set(AS::AllowNegativeNumbers) { + let a = arg_os.to_string_lossy(); + if a.parse::<i64>().is_ok() || a.parse::<f64>().is_ok() { + self.set(AS::ValidNegNumFound); + true + } else { + false + } + } else { + false + }; + let arg_allows_tac = match needs_val_of { + ParseResult::Opt(name) => { + let o = self.opts + .iter() + .find(|o| o.b.name == name) + .expect(INTERNAL_ERROR_MSG); + (o.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings) + } + ParseResult::Pos(name) => { + let p = self.positionals + .values() + .find(|p| p.b.name == name) + .expect(INTERNAL_ERROR_MSG); + (p.is_set(ArgSettings::AllowLeadingHyphen) || app_wide_settings) + } + ParseResult::ValuesDone => return true, + _ => false, + }; + debugln!("Parser::is_new_arg: arg_allows_tac={:?}", arg_allows_tac); + + // Is this a new argument, or values from a previous option? + let mut ret = if arg_os.starts_with(b"--") { + debugln!("Parser::is_new_arg: -- found"); + if arg_os.len() == 2 && !arg_allows_tac { + return true; // We have to return true so override everything else + } else if arg_allows_tac { + return false; + } + true + } else if arg_os.starts_with(b"-") { + debugln!("Parser::is_new_arg: - found"); + // a singe '-' by itself is a value and typically means "stdin" on unix systems + !(arg_os.len() == 1) + } else { + debugln!("Parser::is_new_arg: probably value"); + false + }; + + ret = ret && !arg_allows_tac; + + debugln!("Parser::is_new_arg: starts_new_arg={:?}", ret); + ret + } + + // The actual parsing function + #[cfg_attr(feature = "lints", allow(while_let_on_iterator, collapsible_if))] + pub fn get_matches_with<I, T>( + &mut self, + matcher: &mut ArgMatcher<'a>, + it: &mut Peekable<I>, + ) -> ClapResult<()> + where + I: Iterator<Item = T>, + T: Into<OsString> + Clone, + { + debugln!("Parser::get_matches_with;"); + // Verify all positional assertions pass + debug_assert!(self.app_debug_asserts()); + if self.positionals.values().any(|a| { + a.b.is_set(ArgSettings::Multiple) && (a.index as usize != self.positionals.len()) + }) + && self.positionals + .values() + .last() + .map_or(false, |p| !p.is_set(ArgSettings::Last)) + { + self.settings.set(AS::LowIndexMultiplePositional); + } + let has_args = self.has_args(); + + // Next we create the `--help` and `--version` arguments and add them if + // necessary + self.create_help_and_version(); + + let mut subcmd_name: Option<String> = None; + let mut needs_val_of: ParseResult<'a> = ParseResult::NotFound; + let mut pos_counter = 1; + let mut sc_is_external = false; + while let Some(arg) = it.next() { + let arg_os = arg.into(); + debugln!( + "Parser::get_matches_with: Begin parsing '{:?}' ({:?})", + arg_os, + &*arg_os.as_bytes() + ); + + self.unset(AS::ValidNegNumFound); + // Is this a new argument, or values from a previous option? + let starts_new_arg = self.is_new_arg(&arg_os, needs_val_of); + if !self.is_set(AS::TrailingValues) && arg_os.starts_with(b"--") && arg_os.len() == 2 + && starts_new_arg + { + debugln!("Parser::get_matches_with: setting TrailingVals=true"); + self.set(AS::TrailingValues); + continue; + } + + // Has the user already passed '--'? Meaning only positional args follow + if !self.is_set(AS::TrailingValues) { + // Does the arg match a subcommand name, or any of it's aliases (if defined) + { + match needs_val_of { + ParseResult::Opt(_) | ParseResult::Pos(_) => (), + _ => { + let (is_match, sc_name) = self.possible_subcommand(&arg_os); + debugln!( + "Parser::get_matches_with: possible_sc={:?}, sc={:?}", + is_match, + sc_name + ); + if is_match { + let sc_name = sc_name.expect(INTERNAL_ERROR_MSG); + if sc_name == "help" && self.is_set(AS::NeedsSubcommandHelp) { + self.parse_help_subcommand(it)?; + } + subcmd_name = Some(sc_name.to_owned()); + break; + } + } + } + } + + if starts_new_arg { + let check_all = self.is_set(AS::AllArgsOverrideSelf); + { + let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); + matcher.process_arg_overrides( + any_arg, + &mut self.overrides, + &mut self.required, + check_all, + ); + } + + if arg_os.starts_with(b"--") { + needs_val_of = self.parse_long_arg(matcher, &arg_os, it)?; + debugln!( + "Parser:get_matches_with: After parse_long_arg {:?}", + needs_val_of + ); + match needs_val_of { + ParseResult::Flag | ParseResult::Opt(..) | ParseResult::ValuesDone => { + continue + } + _ => (), + } + } else if arg_os.starts_with(b"-") && arg_os.len() != 1 { + // Try to parse short args like normal, if AllowLeadingHyphen or + // AllowNegativeNumbers is set, parse_short_arg will *not* throw + // an error, and instead return Ok(None) + needs_val_of = self.parse_short_arg(matcher, &arg_os)?; + // If it's None, we then check if one of those two AppSettings was set + debugln!( + "Parser:get_matches_with: After parse_short_arg {:?}", + needs_val_of + ); + match needs_val_of { + ParseResult::MaybeNegNum => { + if !(arg_os.to_string_lossy().parse::<i64>().is_ok() + || arg_os.to_string_lossy().parse::<f64>().is_ok()) + { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + ParseResult::Opt(..) | ParseResult::Flag | ParseResult::ValuesDone => { + continue + } + _ => (), + } + } + } else { + if let ParseResult::Opt(name) = needs_val_of { + // Check to see if parsing a value from a previous arg + let arg = self.opts + .iter() + .find(|o| o.b.name == name) + .expect(INTERNAL_ERROR_MSG); + // get the OptBuilder so we can check the settings + needs_val_of = self.add_val_to_arg(arg, &arg_os, matcher)?; + // get the next value from the iterator + continue; + } + } + } + + if !(self.is_set(AS::ArgsNegateSubcommands) && self.is_set(AS::ValidArgFound)) + && !self.is_set(AS::InferSubcommands) && !self.is_set(AS::AllowExternalSubcommands) + { + if let Some(cdate) = + suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) + { + return Err(Error::invalid_subcommand( + arg_os.to_string_lossy().into_owned(), + cdate, + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + + let low_index_mults = self.is_set(AS::LowIndexMultiplePositional) + && pos_counter == (self.positionals.len() - 1); + let missing_pos = self.is_set(AS::AllowMissingPositional) + && (pos_counter == (self.positionals.len() - 1) + && !self.is_set(AS::TrailingValues)); + debugln!( + "Parser::get_matches_with: Positional counter...{}", + pos_counter + ); + debugln!( + "Parser::get_matches_with: Low index multiples...{:?}", + low_index_mults + ); + if low_index_mults || missing_pos { + if let Some(na) = it.peek() { + let n = (*na).clone().into(); + needs_val_of = if needs_val_of != ParseResult::ValuesDone { + if let Some(p) = self.positionals.get(pos_counter) { + ParseResult::Pos(p.b.name) + } else { + ParseResult::ValuesDone + } + } else { + ParseResult::ValuesDone + }; + let sc_match = { self.possible_subcommand(&n).0 }; + if self.is_new_arg(&n, needs_val_of) || sc_match + || suggestions::did_you_mean(&n.to_string_lossy(), sc_names!(self)) + .is_some() + { + debugln!("Parser::get_matches_with: Bumping the positional counter..."); + pos_counter += 1; + } + } else { + debugln!("Parser::get_matches_with: Bumping the positional counter..."); + pos_counter += 1; + } + } else if (self.is_set(AS::AllowMissingPositional) && self.is_set(AS::TrailingValues)) + || (self.is_set(AS::ContainsLast) && self.is_set(AS::TrailingValues)) + { + // Came to -- and one postional has .last(true) set, so we go immediately + // to the last (highest index) positional + debugln!("Parser::get_matches_with: .last(true) and --, setting last pos"); + pos_counter = self.positionals.len(); + } + if let Some(p) = self.positionals.get(pos_counter) { + if p.is_set(ArgSettings::Last) && !self.is_set(AS::TrailingValues) { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + if !self.is_set(AS::TrailingValues) + && (self.is_set(AS::TrailingVarArg) && pos_counter == self.positionals.len()) + { + self.settings.set(AS::TrailingValues); + } + if self.cache.map_or(true, |name| name != p.b.name) { + let check_all = self.is_set(AS::AllArgsOverrideSelf); + { + let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); + matcher.process_arg_overrides( + any_arg, + &mut self.overrides, + &mut self.required, + check_all, + ); + } + self.cache = Some(p.b.name); + } + let _ = self.add_val_to_arg(p, &arg_os, matcher)?; + + matcher.inc_occurrence_of(p.b.name); + let _ = self.groups_for_arg(p.b.name) + .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec))); + + self.settings.set(AS::ValidArgFound); + // Only increment the positional counter if it doesn't allow multiples + if !p.b.settings.is_set(ArgSettings::Multiple) { + pos_counter += 1; + } + self.settings.set(AS::ValidArgFound); + } else if self.is_set(AS::AllowExternalSubcommands) { + // Get external subcommand name + let sc_name = match arg_os.to_str() { + Some(s) => s.to_string(), + None => { + if !self.is_set(AS::StrictUtf8) { + return Err(Error::invalid_utf8( + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + arg_os.to_string_lossy().into_owned() + } + }; + + // Collect the external subcommand args + let mut sc_m = ArgMatcher::new(); + while let Some(v) = it.next() { + let a = v.into(); + if a.to_str().is_none() && !self.is_set(AS::StrictUtf8) { + return Err(Error::invalid_utf8( + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + sc_m.add_val_to("", &a); + } + + matcher.subcommand(SubCommand { + name: sc_name, + matches: sc_m.into(), + }); + sc_is_external = true; + } else if !((self.is_set(AS::AllowLeadingHyphen) + || self.is_set(AS::AllowNegativeNumbers)) + && arg_os.starts_with(b"-")) + && !self.is_set(AS::InferSubcommands) + { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else if !has_args || self.is_set(AS::InferSubcommands) && self.has_subcommands() { + if let Some(cdate) = + suggestions::did_you_mean(&*arg_os.to_string_lossy(), sc_names!(self)) + { + return Err(Error::invalid_subcommand( + arg_os.to_string_lossy().into_owned(), + cdate, + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else { + return Err(Error::unrecognized_subcommand( + arg_os.to_string_lossy().into_owned(), + self.meta.bin_name.as_ref().unwrap_or(&self.meta.name), + self.color(), + )); + } + } else { + return Err(Error::unknown_argument( + &*arg_os.to_string_lossy(), + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + + if !sc_is_external { + if let Some(ref pos_sc_name) = subcmd_name { + let sc_name = { + find_subcmd!(self, pos_sc_name) + .expect(INTERNAL_ERROR_MSG) + .p + .meta + .name + .clone() + }; + self.parse_subcommand(&*sc_name, matcher, it)?; + } else if self.is_set(AS::SubcommandRequired) { + let bn = self.meta.bin_name.as_ref().unwrap_or(&self.meta.name); + return Err(Error::missing_subcommand( + bn, + &usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else if self.is_set(AS::SubcommandRequiredElseHelp) { + debugln!("Parser::get_matches_with: SubcommandRequiredElseHelp=true"); + let mut out = vec![]; + self.write_help_err(&mut out)?; + return Err(Error { + message: String::from_utf8_lossy(&*out).into_owned(), + kind: ErrorKind::MissingArgumentOrSubcommand, + info: None, + }); + } + } + + // In case the last arg was new, we need to process it's overrides + let check_all = self.is_set(AS::AllArgsOverrideSelf); + { + let any_arg = find_any_by_name!(self, self.cache.unwrap_or("")); + matcher.process_arg_overrides( + any_arg, + &mut self.overrides, + &mut self.required, + check_all, + ); + } + + self.remove_overrides(matcher); + + Validator::new(self).validate(needs_val_of, subcmd_name, matcher) + } + + fn remove_overrides(&mut self, matcher: &mut ArgMatcher) { + debugln!("Parser::remove_overrides:{:?};", self.overrides); + for &(overr, name) in &self.overrides { + debugln!("Parser::remove_overrides:iter:({},{});", overr, name); + if matcher.is_present(overr) { + debugln!( + "Parser::remove_overrides:iter:({},{}): removing {};", + overr, + name, + name + ); + matcher.remove(name); + for i in (0..self.required.len()).rev() { + debugln!( + "Parser::remove_overrides:iter:({},{}): removing required {};", + overr, + name, + name + ); + if self.required[i] == name { + self.required.swap_remove(i); + break; + } + } + } + } + } + + fn propagate_help_version(&mut self) { + debugln!("Parser::propagate_help_version;"); + self.create_help_and_version(); + for sc in &mut self.subcommands { + sc.p.propagate_help_version(); + } + } + + fn build_bin_names(&mut self) { + debugln!("Parser::build_bin_names;"); + for sc in &mut self.subcommands { + debug!("Parser::build_bin_names:iter: bin_name set..."); + if sc.p.meta.bin_name.is_none() { + sdebugln!("No"); + let bin_name = format!( + "{}{}{}", + self.meta + .bin_name + .as_ref() + .unwrap_or(&self.meta.name.clone()), + if self.meta.bin_name.is_some() { + " " + } else { + "" + }, + &*sc.p.meta.name + ); + debugln!( + "Parser::build_bin_names:iter: Setting bin_name of {} to {}", + self.meta.name, + bin_name + ); + sc.p.meta.bin_name = Some(bin_name); + } else { + sdebugln!("yes ({:?})", sc.p.meta.bin_name); + } + debugln!( + "Parser::build_bin_names:iter: Calling build_bin_names from...{}", + sc.p.meta.name + ); + sc.p.build_bin_names(); + } + } + + fn parse_subcommand<I, T>( + &mut self, + sc_name: &str, + matcher: &mut ArgMatcher<'a>, + it: &mut Peekable<I>, + ) -> ClapResult<()> + where + I: Iterator<Item = T>, + T: Into<OsString> + Clone, + { + use std::fmt::Write; + debugln!("Parser::parse_subcommand;"); + let mut mid_string = String::new(); + if !self.is_set(AS::SubcommandsNegateReqs) { + let mut hs: Vec<&str> = self.required.iter().map(|n| &**n).collect(); + for k in matcher.arg_names() { + hs.push(k); + } + let reqs = usage::get_required_usage_from(self, &hs, Some(matcher), None, false); + + for s in &reqs { + write!(&mut mid_string, " {}", s).expect(INTERNAL_ERROR_MSG); + } + } + mid_string.push_str(" "); + if let Some(ref mut sc) = self.subcommands + .iter_mut() + .find(|s| s.p.meta.name == sc_name) + { + let mut sc_matcher = ArgMatcher::new(); + // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by + // a space + sc.p.meta.usage = Some(format!( + "{}{}{}", + self.meta.bin_name.as_ref().unwrap_or(&String::new()), + if self.meta.bin_name.is_some() { + &*mid_string + } else { + "" + }, + &*sc.p.meta.name + )); + sc.p.meta.bin_name = Some(format!( + "{}{}{}", + self.meta.bin_name.as_ref().unwrap_or(&String::new()), + if self.meta.bin_name.is_some() { + " " + } else { + "" + }, + &*sc.p.meta.name + )); + debugln!( + "Parser::parse_subcommand: About to parse sc={}", + sc.p.meta.name + ); + debugln!("Parser::parse_subcommand: sc settings={:#?}", sc.p.settings); + sc.p.get_matches_with(&mut sc_matcher, it)?; + matcher.subcommand(SubCommand { + name: sc.p.meta.name.clone(), + matches: sc_matcher.into(), + }); + } + Ok(()) + } + + pub fn groups_for_arg(&self, name: &str) -> Option<Vec<&'a str>> { + debugln!("Parser::groups_for_arg: name={}", name); + + if self.groups.is_empty() { + debugln!("Parser::groups_for_arg: No groups defined"); + return None; + } + let mut res = vec![]; + debugln!("Parser::groups_for_arg: Searching through groups..."); + for grp in &self.groups { + for a in &grp.args { + if a == &name { + sdebugln!("\tFound '{}'", grp.name); + res.push(&*grp.name); + } + } + } + if res.is_empty() { + return None; + } + + Some(res) + } + + pub fn args_in_group(&self, group: &str) -> Vec<String> { + debug_assert!(self.app_debug_asserts()); + + let mut g_vec = vec![]; + let mut args = vec![]; + + for n in &self.groups + .iter() + .find(|g| g.name == group) + .expect(INTERNAL_ERROR_MSG) + .args + { + if let Some(f) = self.flags.iter().find(|f| &f.b.name == n) { + args.push(f.to_string()); + } else if let Some(f) = self.opts.iter().find(|o| &o.b.name == n) { + args.push(f.to_string()); + } else if let Some(p) = self.positionals.values().find(|p| &p.b.name == n) { + args.push(p.b.name.to_owned()); + } else { + g_vec.push(*n); + } + } + + for av in g_vec.iter().map(|g| self.args_in_group(g)) { + args.extend(av); + } + args.dedup(); + args.iter().map(ToOwned::to_owned).collect() + } + + pub fn arg_names_in_group(&self, group: &str) -> Vec<&'a str> { + let mut g_vec = vec![]; + let mut args = vec![]; + + for n in &self.groups + .iter() + .find(|g| g.name == group) + .expect(INTERNAL_ERROR_MSG) + .args + { + if self.groups.iter().any(|g| g.name == *n) { + args.extend(self.arg_names_in_group(n)); + g_vec.push(*n); + } else if !args.contains(n) { + args.push(*n); + } + } + + args.iter().map(|s| *s).collect() + } + + pub fn create_help_and_version(&mut self) { + debugln!("Parser::create_help_and_version;"); + // name is "hclap_help" because flags are sorted by name + if !self.is_set(AS::DisableHelpFlags) && !self.contains_long("help") { + debugln!("Parser::create_help_and_version: Building --help"); + if self.help_short.is_none() && !self.contains_short('h') { + self.help_short = Some('h'); + } + let arg = FlagBuilder { + b: Base { + name: "hclap_help", + help: self.help_message.or(Some("Prints help information")), + ..Default::default() + }, + s: Switched { + short: self.help_short, + long: Some("help"), + ..Default::default() + }, + }; + self.flags.push(arg); + } + if !self.is_set(AS::DisableVersion) && !self.contains_long("version") { + debugln!("Parser::create_help_and_version: Building --version"); + if self.version_short.is_none() && !self.contains_short('V') { + self.version_short = Some('V'); + } + // name is "vclap_version" because flags are sorted by name + let arg = FlagBuilder { + b: Base { + name: "vclap_version", + help: self.version_message.or(Some("Prints version information")), + ..Default::default() + }, + s: Switched { + short: self.version_short, + long: Some("version"), + ..Default::default() + }, + }; + self.flags.push(arg); + } + if !self.subcommands.is_empty() && !self.is_set(AS::DisableHelpSubcommand) + && self.is_set(AS::NeedsSubcommandHelp) + { + debugln!("Parser::create_help_and_version: Building help"); + self.subcommands.push( + App::new("help") + .about("Prints this message or the help of the given subcommand(s)"), + ); + } + } + + // Retrieves the names of all args the user has supplied thus far, except required ones + // because those will be listed in self.required + fn check_for_help_and_version_str(&self, arg: &OsStr) -> ClapResult<()> { + debugln!("Parser::check_for_help_and_version_str;"); + debug!( + "Parser::check_for_help_and_version_str: Checking if --{} is help or version...", + arg.to_str().unwrap() + ); + if arg == "help" && self.is_set(AS::NeedsLongHelp) { + sdebugln!("Help"); + return Err(self._help(true)); + } + if arg == "version" && self.is_set(AS::NeedsLongVersion) { + sdebugln!("Version"); + return Err(self._version(true)); + } + sdebugln!("Neither"); + + Ok(()) + } + + fn check_for_help_and_version_char(&self, arg: char) -> ClapResult<()> { + debugln!("Parser::check_for_help_and_version_char;"); + debug!( + "Parser::check_for_help_and_version_char: Checking if -{} is help or version...", + arg + ); + if let Some(h) = self.help_short { + if arg == h && self.is_set(AS::NeedsLongHelp) { + sdebugln!("Help"); + return Err(self._help(false)); + } + } + if let Some(v) = self.version_short { + if arg == v && self.is_set(AS::NeedsLongVersion) { + sdebugln!("Version"); + return Err(self._version(false)); + } + } + sdebugln!("Neither"); + Ok(()) + } + + fn use_long_help(&self) -> bool { + // In this case, both must be checked. This allows the retention of + // original formatting, but also ensures that the actual -h or --help + // specified by the user is sent through. If HiddenShortHelp is not included, + // then items specified with hidden_short_help will also be hidden. + let should_long = |v: &Base| { + v.long_help.is_some() || + v.is_set(ArgSettings::HiddenLongHelp) || + v.is_set(ArgSettings::HiddenShortHelp) + }; + + self.meta.long_about.is_some() + || self.flags.iter().any(|f| should_long(&f.b)) + || self.opts.iter().any(|o| should_long(&o.b)) + || self.positionals.values().any(|p| should_long(&p.b)) + || self.subcommands + .iter() + .any(|s| s.p.meta.long_about.is_some()) + } + + fn _help(&self, mut use_long: bool) -> Error { + debugln!("Parser::_help: use_long={:?}", use_long); + use_long = use_long && self.use_long_help(); + let mut buf = vec![]; + match Help::write_parser_help(&mut buf, self, use_long) { + Err(e) => e, + _ => Error { + message: String::from_utf8(buf).unwrap_or_default(), + kind: ErrorKind::HelpDisplayed, + info: None, + }, + } + } + + fn _version(&self, use_long: bool) -> Error { + debugln!("Parser::_version: "); + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + match self.print_version(&mut buf_w, use_long) { + Err(e) => e, + _ => Error { + message: String::new(), + kind: ErrorKind::VersionDisplayed, + info: None, + }, + } + } + + fn parse_long_arg<I, T>( + &mut self, + matcher: &mut ArgMatcher<'a>, + full_arg: &OsStr, + it: &mut Peekable<I>, + ) -> ClapResult<ParseResult<'a>> + where + I: Iterator<Item = T>, + T: Into<OsString> + Clone, + { + // maybe here lifetime should be 'a + debugln!("Parser::parse_long_arg;"); + + // Update the current index + self.cur_idx.set(self.cur_idx.get() + 1); + + let mut val = None; + debug!("Parser::parse_long_arg: Does it contain '='..."); + let arg = if full_arg.contains_byte(b'=') { + let (p0, p1) = full_arg.trim_left_matches(b'-').split_at_byte(b'='); + sdebugln!("Yes '{:?}'", p1); + val = Some(p1); + p0 + } else { + sdebugln!("No"); + full_arg.trim_left_matches(b'-') + }; + + if let Some(opt) = find_opt_by_long!(@os self, arg) { + debugln!( + "Parser::parse_long_arg: Found valid opt '{}'", + opt.to_string() + ); + self.settings.set(AS::ValidArgFound); + let ret = self.parse_opt(val, opt, val.is_some(), matcher)?; + if self.cache.map_or(true, |name| name != opt.b.name) { + self.cache = Some(opt.b.name); + } + + return Ok(ret); + } else if let Some(flag) = find_flag_by_long!(@os self, arg) { + debugln!( + "Parser::parse_long_arg: Found valid flag '{}'", + flag.to_string() + ); + self.settings.set(AS::ValidArgFound); + // Only flags could be help or version, and we need to check the raw long + // so this is the first point to check + self.check_for_help_and_version_str(arg)?; + + self.parse_flag(flag, matcher)?; + + // Handle conflicts, requirements, etc. + if self.cache.map_or(true, |name| name != flag.b.name) { + self.cache = Some(flag.b.name); + } + + return Ok(ParseResult::Flag); + } else if self.is_set(AS::AllowLeadingHyphen) { + return Ok(ParseResult::MaybeHyphenValue); + } else if self.is_set(AS::ValidNegNumFound) { + return Ok(ParseResult::MaybeNegNum); + } + + debugln!("Parser::parse_long_arg: Didn't match anything"); + + let args_rest: Vec<_> = it.map(|x| x.clone().into()).collect(); + let args_rest2: Vec<_> = args_rest.iter().map(|x| x.to_str().expect(INVALID_UTF8)).collect(); + self.did_you_mean_error( + arg.to_str().expect(INVALID_UTF8), + matcher, + &args_rest2[..] + ).map(|_| ParseResult::NotFound) + } + + #[cfg_attr(feature = "lints", allow(len_zero))] + fn parse_short_arg( + &mut self, + matcher: &mut ArgMatcher<'a>, + full_arg: &OsStr, + ) -> ClapResult<ParseResult<'a>> { + debugln!("Parser::parse_short_arg: full_arg={:?}", full_arg); + let arg_os = full_arg.trim_left_matches(b'-'); + let arg = arg_os.to_string_lossy(); + + // If AllowLeadingHyphen is set, we want to ensure `-val` gets parsed as `-val` and not + // `-v` `-a` `-l` assuming `v` `a` and `l` are all, or mostly, valid shorts. + if self.is_set(AS::AllowLeadingHyphen) { + if arg.chars().any(|c| !self.contains_short(c)) { + debugln!( + "Parser::parse_short_arg: LeadingHyphenAllowed yet -{} isn't valid", + arg + ); + return Ok(ParseResult::MaybeHyphenValue); + } + } else if self.is_set(AS::ValidNegNumFound) { + // TODO: Add docs about having AllowNegativeNumbers and `-2` as a valid short + // May be better to move this to *after* not finding a valid flag/opt? + debugln!("Parser::parse_short_arg: Valid negative num..."); + return Ok(ParseResult::MaybeNegNum); + } + + let mut ret = ParseResult::NotFound; + for c in arg.chars() { + debugln!("Parser::parse_short_arg:iter:{}", c); + + // update each index because `-abcd` is four indices to clap + self.cur_idx.set(self.cur_idx.get() + 1); + + // Check for matching short options, and return the name if there is no trailing + // concatenated value: -oval + // Option: -o + // Value: val + if let Some(opt) = find_opt_by_short!(self, c) { + debugln!("Parser::parse_short_arg:iter:{}: Found valid opt", c); + self.settings.set(AS::ValidArgFound); + // Check for trailing concatenated value + let p: Vec<_> = arg.splitn(2, c).collect(); + debugln!( + "Parser::parse_short_arg:iter:{}: p[0]={:?}, p[1]={:?}", + c, + p[0].as_bytes(), + p[1].as_bytes() + ); + let i = p[0].as_bytes().len() + 1; + let val = if p[1].as_bytes().len() > 0 { + debugln!( + "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii)", + c, + arg_os.split_at(i).1.as_bytes(), + arg_os.split_at(i).1 + ); + Some(arg_os.split_at(i).1) + } else { + None + }; + + // Default to "we're expecting a value later" + let ret = self.parse_opt(val, opt, false, matcher)?; + + if self.cache.map_or(true, |name| name != opt.b.name) { + self.cache = Some(opt.b.name); + } + + return Ok(ret); + } else if let Some(flag) = find_flag_by_short!(self, c) { + debugln!("Parser::parse_short_arg:iter:{}: Found valid flag", c); + self.settings.set(AS::ValidArgFound); + // Only flags can be help or version + self.check_for_help_and_version_char(c)?; + ret = self.parse_flag(flag, matcher)?; + + // Handle conflicts, requirements, overrides, etc. + // Must be called here due to mutabililty + if self.cache.map_or(true, |name| name != flag.b.name) { + self.cache = Some(flag.b.name); + } + } else { + let arg = format!("-{}", c); + return Err(Error::unknown_argument( + &*arg, + "", + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + } + Ok(ret) + } + + fn parse_opt( + &self, + val: Option<&OsStr>, + opt: &OptBuilder<'a, 'b>, + had_eq: bool, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult<ParseResult<'a>> { + debugln!("Parser::parse_opt; opt={}, val={:?}", opt.b.name, val); + debugln!("Parser::parse_opt; opt.settings={:?}", opt.b.settings); + let mut has_eq = false; + let no_val = val.is_none(); + let empty_vals = opt.is_set(ArgSettings::EmptyValues); + let min_vals_zero = opt.v.min_vals.unwrap_or(1) == 0; + let needs_eq = opt.is_set(ArgSettings::RequireEquals); + + debug!("Parser::parse_opt; Checking for val..."); + if let Some(fv) = val { + has_eq = fv.starts_with(&[b'=']) || had_eq; + let v = fv.trim_left_matches(b'='); + if !empty_vals && (v.len() == 0 || (needs_eq && !has_eq)) { + sdebugln!("Found Empty - Error"); + return Err(Error::empty_value( + opt, + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } + sdebugln!("Found - {:?}, len: {}", v, v.len()); + debugln!( + "Parser::parse_opt: {:?} contains '='...{:?}", + fv, + fv.starts_with(&[b'=']) + ); + self.add_val_to_arg(opt, v, matcher)?; + } else if needs_eq && !(empty_vals || min_vals_zero) { + sdebugln!("None, but requires equals...Error"); + return Err(Error::empty_value( + opt, + &*usage::create_error_usage(self, matcher, None), + self.color(), + )); + } else { + sdebugln!("None"); + } + + matcher.inc_occurrence_of(opt.b.name); + // Increment or create the group "args" + self.groups_for_arg(opt.b.name) + .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec))); + + let needs_delim = opt.is_set(ArgSettings::RequireDelimiter); + let mult = opt.is_set(ArgSettings::Multiple); + if no_val && min_vals_zero && !has_eq && needs_eq { + debugln!("Parser::parse_opt: More arg vals not required..."); + return Ok(ParseResult::ValuesDone); + } else if no_val || (mult && !needs_delim) && !has_eq && matcher.needs_more_vals(opt) { + debugln!("Parser::parse_opt: More arg vals required..."); + return Ok(ParseResult::Opt(opt.b.name)); + } + debugln!("Parser::parse_opt: More arg vals not required..."); + Ok(ParseResult::ValuesDone) + } + + fn add_val_to_arg<A>( + &self, + arg: &A, + val: &OsStr, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult<ParseResult<'a>> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Parser::add_val_to_arg; arg={}, val={:?}", arg.name(), val); + debugln!( + "Parser::add_val_to_arg; trailing_vals={:?}, DontDelimTrailingVals={:?}", + self.is_set(AS::TrailingValues), + self.is_set(AS::DontDelimitTrailingValues) + ); + if !(self.is_set(AS::TrailingValues) && self.is_set(AS::DontDelimitTrailingValues)) { + if let Some(delim) = arg.val_delim() { + if val.is_empty() { + Ok(self.add_single_val_to_arg(arg, val, matcher)?) + } else { + let mut iret = ParseResult::ValuesDone; + for v in val.split(delim as u32 as u8) { + iret = self.add_single_val_to_arg(arg, v, matcher)?; + } + // If there was a delimiter used, we're not looking for more values + if val.contains_byte(delim as u32 as u8) + || arg.is_set(ArgSettings::RequireDelimiter) + { + iret = ParseResult::ValuesDone; + } + Ok(iret) + } + } else { + self.add_single_val_to_arg(arg, val, matcher) + } + } else { + self.add_single_val_to_arg(arg, val, matcher) + } + } + + fn add_single_val_to_arg<A>( + &self, + arg: &A, + v: &OsStr, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult<ParseResult<'a>> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Parser::add_single_val_to_arg;"); + debugln!("Parser::add_single_val_to_arg: adding val...{:?}", v); + + // update the current index because each value is a distinct index to clap + self.cur_idx.set(self.cur_idx.get() + 1); + + // @TODO @docs @p4: docs for indices should probably note that a terminator isn't a value + // and therefore not reported in indices + if let Some(t) = arg.val_terminator() { + if t == v { + return Ok(ParseResult::ValuesDone); + } + } + + matcher.add_val_to(arg.name(), v); + matcher.add_index_to(arg.name(), self.cur_idx.get()); + + // Increment or create the group "args" + if let Some(grps) = self.groups_for_arg(arg.name()) { + for grp in grps { + matcher.add_val_to(&*grp, v); + } + } + + if matcher.needs_more_vals(arg) { + return Ok(ParseResult::Opt(arg.name())); + } + Ok(ParseResult::ValuesDone) + } + + fn parse_flag( + &self, + flag: &FlagBuilder<'a, 'b>, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult<ParseResult<'a>> { + debugln!("Parser::parse_flag;"); + + matcher.inc_occurrence_of(flag.b.name); + matcher.add_index_to(flag.b.name, self.cur_idx.get()); + + // Increment or create the group "args" + self.groups_for_arg(flag.b.name) + .and_then(|vec| Some(matcher.inc_occurrences_of(&*vec))); + + Ok(ParseResult::Flag) + } + + fn did_you_mean_error(&self, arg: &str, matcher: &mut ArgMatcher<'a>, args_rest: &[&str]) -> ClapResult<()> { + // Didn't match a flag or option + let suffix = suggestions::did_you_mean_flag_suffix(arg, &args_rest, longs!(self), &self.subcommands); + + // Add the arg to the matches to build a proper usage string + if let Some(name) = suffix.1 { + if let Some(opt) = find_opt_by_long!(self, name) { + self.groups_for_arg(&*opt.b.name) + .and_then(|grps| Some(matcher.inc_occurrences_of(&*grps))); + matcher.insert(&*opt.b.name); + } else if let Some(flg) = find_flag_by_long!(self, name) { + self.groups_for_arg(&*flg.b.name) + .and_then(|grps| Some(matcher.inc_occurrences_of(&*grps))); + matcher.insert(&*flg.b.name); + } + } + + let used_arg = format!("--{}", arg); + Err(Error::unknown_argument( + &*used_arg, + &*suffix.0, + &*usage::create_error_usage(self, matcher, None), + self.color(), + )) + } + + // Prints the version to the user and exits if quit=true + fn print_version<W: Write>(&self, w: &mut W, use_long: bool) -> ClapResult<()> { + self.write_version(w, use_long)?; + w.flush().map_err(Error::from) + } + + pub fn write_version<W: Write>(&self, w: &mut W, use_long: bool) -> io::Result<()> { + let ver = if use_long { + self.meta + .long_version + .unwrap_or_else(|| self.meta.version.unwrap_or("")) + } else { + self.meta + .version + .unwrap_or_else(|| self.meta.long_version.unwrap_or("")) + }; + if let Some(bn) = self.meta.bin_name.as_ref() { + if bn.contains(' ') { + // Incase we're dealing with subcommands i.e. git mv is translated to git-mv + write!(w, "{} {}", bn.replace(" ", "-"), ver) + } else { + write!(w, "{} {}", &self.meta.name[..], ver) + } + } else { + write!(w, "{} {}", &self.meta.name[..], ver) + } + } + + pub fn print_help(&self) -> ClapResult<()> { + let out = io::stdout(); + let mut buf_w = BufWriter::new(out.lock()); + self.write_help(&mut buf_w) + } + + pub fn write_help<W: Write>(&self, w: &mut W) -> ClapResult<()> { + Help::write_parser_help(w, self, false) + } + + pub fn write_long_help<W: Write>(&self, w: &mut W) -> ClapResult<()> { + Help::write_parser_help(w, self, true) + } + + pub fn write_help_err<W: Write>(&self, w: &mut W) -> ClapResult<()> { + Help::write_parser_help_to_stderr(w, self) + } + + pub fn add_defaults(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { + debugln!("Parser::add_defaults;"); + macro_rules! add_val { + (@default $_self:ident, $a:ident, $m:ident) => { + if let Some(ref val) = $a.v.default_val { + debugln!("Parser::add_defaults:iter:{}: has default vals", $a.b.name); + if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) { + debugln!("Parser::add_defaults:iter:{}: has no user defined vals", $a.b.name); + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } else if $m.get($a.b.name).is_some() { + debugln!("Parser::add_defaults:iter:{}: has user defined vals", $a.b.name); + } else { + debugln!("Parser::add_defaults:iter:{}: wasn't used", $a.b.name); + + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } + } else { + debugln!("Parser::add_defaults:iter:{}: doesn't have default vals", $a.b.name); + } + }; + ($_self:ident, $a:ident, $m:ident) => { + if let Some(ref vm) = $a.v.default_vals_ifs { + sdebugln!(" has conditional defaults"); + let mut done = false; + if $m.get($a.b.name).is_none() { + for &(arg, val, default) in vm.values() { + let add = if let Some(a) = $m.get(arg) { + if let Some(v) = val { + a.vals.iter().any(|value| v == value) + } else { + true + } + } else { + false + }; + if add { + $_self.add_val_to_arg($a, OsStr::new(default), $m)?; + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + done = true; + break; + } + } + } + + if done { + continue; // outer loop (outside macro) + } + } else { + sdebugln!(" doesn't have conditional defaults"); + } + add_val!(@default $_self, $a, $m) + }; + } + + for o in &self.opts { + debug!("Parser::add_defaults:iter:{}:", o.b.name); + add_val!(self, o, matcher); + } + for p in self.positionals.values() { + debug!("Parser::add_defaults:iter:{}:", p.b.name); + add_val!(self, p, matcher); + } + Ok(()) + } + + pub fn add_env(&mut self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { + macro_rules! add_val { + ($_self:ident, $a:ident, $m:ident) => { + if let Some(ref val) = $a.v.env { + if $m.get($a.b.name).map(|ma| ma.vals.len()).map(|len| len == 0).unwrap_or(false) { + if let Some(ref val) = val.1 { + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } + } else { + if let Some(ref val) = val.1 { + $_self.add_val_to_arg($a, OsStr::new(val), $m)?; + + if $_self.cache.map_or(true, |name| name != $a.name()) { + $_self.cache = Some($a.name()); + } + } + } + } + }; + } + + for o in &self.opts { + add_val!(self, o, matcher); + } + for p in self.positionals.values() { + add_val!(self, p, matcher); + } + Ok(()) + } + + pub fn flags(&self) -> Iter<FlagBuilder<'a, 'b>> { self.flags.iter() } + + pub fn opts(&self) -> Iter<OptBuilder<'a, 'b>> { self.opts.iter() } + + pub fn positionals(&self) -> map::Values<PosBuilder<'a, 'b>> { self.positionals.values() } + + pub fn subcommands(&self) -> Iter<App> { self.subcommands.iter() } + + // Should we color the output? None=determined by output location, true=yes, false=no + #[doc(hidden)] + pub fn color(&self) -> ColorWhen { + debugln!("Parser::color;"); + debug!("Parser::color: Color setting..."); + if self.is_set(AS::ColorNever) { + sdebugln!("Never"); + ColorWhen::Never + } else if self.is_set(AS::ColorAlways) { + sdebugln!("Always"); + ColorWhen::Always + } else { + sdebugln!("Auto"); + ColorWhen::Auto + } + } + + pub fn find_any_arg(&self, name: &str) -> Option<&AnyArg<'a, 'b>> { + if let Some(f) = find_by_name!(self, name, flags, iter) { + return Some(f); + } + if let Some(o) = find_by_name!(self, name, opts, iter) { + return Some(o); + } + if let Some(p) = find_by_name!(self, name, positionals, values) { + return Some(p); + } + None + } + + /// Check is a given string matches the binary name for this parser + fn is_bin_name(&self, value: &str) -> bool { + self.meta + .bin_name + .as_ref() + .and_then(|name| Some(value == name)) + .unwrap_or(false) + } + + /// Check is a given string is an alias for this parser + fn is_alias(&self, value: &str) -> bool { + self.meta + .aliases + .as_ref() + .and_then(|aliases| { + for alias in aliases { + if alias.0 == value { + return Some(true); + } + } + Some(false) + }) + .unwrap_or(false) + } + + // Only used for completion scripts due to bin_name messiness + #[cfg_attr(feature = "lints", allow(block_in_if_condition_stmt))] + pub fn find_subcommand(&'b self, sc: &str) -> Option<&'b App<'a, 'b>> { + debugln!("Parser::find_subcommand: sc={}", sc); + debugln!( + "Parser::find_subcommand: Currently in Parser...{}", + self.meta.bin_name.as_ref().unwrap() + ); + for s in &self.subcommands { + if s.p.is_bin_name(sc) { + return Some(s); + } + // XXX: why do we split here? + // isn't `sc` supposed to be single word already? + let last = sc.split(' ').rev().next().expect(INTERNAL_ERROR_MSG); + if s.p.is_alias(last) { + return Some(s); + } + + if let Some(app) = s.p.find_subcommand(sc) { + return Some(app); + } + } + None + } + + #[inline] + fn contains_long(&self, l: &str) -> bool { longs!(self).any(|al| al == &l) } + + #[inline] + fn contains_short(&self, s: char) -> bool { shorts!(self).any(|arg_s| arg_s == &s) } +} diff --git a/clap/src/app/settings.rs b/clap/src/app/settings.rs new file mode 100644 index 0000000..ec03997 --- /dev/null +++ b/clap/src/app/settings.rs @@ -0,0 +1,1174 @@ +// Std +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; +use std::str::FromStr; +use std::ops::BitOr; + +bitflags! { + struct Flags: u64 { + const SC_NEGATE_REQS = 1; + const SC_REQUIRED = 1 << 1; + const A_REQUIRED_ELSE_HELP = 1 << 2; + const GLOBAL_VERSION = 1 << 3; + const VERSIONLESS_SC = 1 << 4; + const UNIFIED_HELP = 1 << 5; + const WAIT_ON_ERROR = 1 << 6; + const SC_REQUIRED_ELSE_HELP= 1 << 7; + const NEEDS_LONG_HELP = 1 << 8; + const NEEDS_LONG_VERSION = 1 << 9; + const NEEDS_SC_HELP = 1 << 10; + const DISABLE_VERSION = 1 << 11; + const HIDDEN = 1 << 12; + const TRAILING_VARARG = 1 << 13; + const NO_BIN_NAME = 1 << 14; + const ALLOW_UNK_SC = 1 << 15; + const UTF8_STRICT = 1 << 16; + const UTF8_NONE = 1 << 17; + const LEADING_HYPHEN = 1 << 18; + const NO_POS_VALUES = 1 << 19; + const NEXT_LINE_HELP = 1 << 20; + const DERIVE_DISP_ORDER = 1 << 21; + const COLORED_HELP = 1 << 22; + const COLOR_ALWAYS = 1 << 23; + const COLOR_AUTO = 1 << 24; + const COLOR_NEVER = 1 << 25; + const DONT_DELIM_TRAIL = 1 << 26; + const ALLOW_NEG_NUMS = 1 << 27; + const LOW_INDEX_MUL_POS = 1 << 28; + const DISABLE_HELP_SC = 1 << 29; + const DONT_COLLAPSE_ARGS = 1 << 30; + const ARGS_NEGATE_SCS = 1 << 31; + const PROPAGATE_VALS_DOWN = 1 << 32; + const ALLOW_MISSING_POS = 1 << 33; + const TRAILING_VALUES = 1 << 34; + const VALID_NEG_NUM_FOUND = 1 << 35; + const PROPAGATED = 1 << 36; + const VALID_ARG_FOUND = 1 << 37; + const INFER_SUBCOMMANDS = 1 << 38; + const CONTAINS_LAST = 1 << 39; + const ARGS_OVERRIDE_SELF = 1 << 40; + const DISABLE_HELP_FLAGS = 1 << 41; + } +} + +#[doc(hidden)] +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct AppFlags(Flags); + +impl BitOr for AppFlags { + type Output = Self; + fn bitor(self, rhs: Self) -> Self { AppFlags(self.0 | rhs.0) } +} + +impl Default for AppFlags { + fn default() -> Self { + AppFlags( + Flags::NEEDS_LONG_VERSION | Flags::NEEDS_LONG_HELP | Flags::NEEDS_SC_HELP + | Flags::UTF8_NONE | Flags::COLOR_AUTO, + ) + } +} + +#[allow(deprecated)] +impl AppFlags { + pub fn new() -> Self { AppFlags::default() } + pub fn zeroed() -> Self { AppFlags(Flags::empty()) } + + impl_settings! { AppSettings, + ArgRequiredElseHelp => Flags::A_REQUIRED_ELSE_HELP, + ArgsNegateSubcommands => Flags::ARGS_NEGATE_SCS, + AllArgsOverrideSelf => Flags::ARGS_OVERRIDE_SELF, + AllowExternalSubcommands => Flags::ALLOW_UNK_SC, + AllowInvalidUtf8 => Flags::UTF8_NONE, + AllowLeadingHyphen => Flags::LEADING_HYPHEN, + AllowNegativeNumbers => Flags::ALLOW_NEG_NUMS, + AllowMissingPositional => Flags::ALLOW_MISSING_POS, + ColoredHelp => Flags::COLORED_HELP, + ColorAlways => Flags::COLOR_ALWAYS, + ColorAuto => Flags::COLOR_AUTO, + ColorNever => Flags::COLOR_NEVER, + DontDelimitTrailingValues => Flags::DONT_DELIM_TRAIL, + DontCollapseArgsInUsage => Flags::DONT_COLLAPSE_ARGS, + DeriveDisplayOrder => Flags::DERIVE_DISP_ORDER, + DisableHelpFlags => Flags::DISABLE_HELP_FLAGS, + DisableHelpSubcommand => Flags::DISABLE_HELP_SC, + DisableVersion => Flags::DISABLE_VERSION, + GlobalVersion => Flags::GLOBAL_VERSION, + HidePossibleValuesInHelp => Flags::NO_POS_VALUES, + Hidden => Flags::HIDDEN, + LowIndexMultiplePositional => Flags::LOW_INDEX_MUL_POS, + NeedsLongHelp => Flags::NEEDS_LONG_HELP, + NeedsLongVersion => Flags::NEEDS_LONG_VERSION, + NeedsSubcommandHelp => Flags::NEEDS_SC_HELP, + NoBinaryName => Flags::NO_BIN_NAME, + PropagateGlobalValuesDown=> Flags::PROPAGATE_VALS_DOWN, + StrictUtf8 => Flags::UTF8_STRICT, + SubcommandsNegateReqs => Flags::SC_NEGATE_REQS, + SubcommandRequired => Flags::SC_REQUIRED, + SubcommandRequiredElseHelp => Flags::SC_REQUIRED_ELSE_HELP, + TrailingVarArg => Flags::TRAILING_VARARG, + UnifiedHelpMessage => Flags::UNIFIED_HELP, + NextLineHelp => Flags::NEXT_LINE_HELP, + VersionlessSubcommands => Flags::VERSIONLESS_SC, + WaitOnError => Flags::WAIT_ON_ERROR, + TrailingValues => Flags::TRAILING_VALUES, + ValidNegNumFound => Flags::VALID_NEG_NUM_FOUND, + Propagated => Flags::PROPAGATED, + ValidArgFound => Flags::VALID_ARG_FOUND, + InferSubcommands => Flags::INFER_SUBCOMMANDS, + ContainsLast => Flags::CONTAINS_LAST + } +} + +/// Application level settings, which affect how [`App`] operates +/// +/// **NOTE:** When these settings are used, they apply only to current command, and are *not* +/// propagated down or up through child or parent subcommands +/// +/// [`App`]: ./struct.App.html +#[derive(Debug, PartialEq, Copy, Clone)] +pub enum AppSettings { + /// Specifies that any invalid UTF-8 code points should *not* be treated as an error. + /// This is the default behavior of `clap`. + /// + /// **NOTE:** Using argument values with invalid UTF-8 code points requires using + /// [`ArgMatches::os_value_of`], [`ArgMatches::os_values_of`], [`ArgMatches::lossy_value_of`], + /// or [`ArgMatches::lossy_values_of`] for those particular arguments which may contain invalid + /// UTF-8 values + /// + /// **NOTE:** This rule only applies to argument values, as flags, options, and + /// [`SubCommand`]s themselves only allow valid UTF-8 code points. + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, AppSettings}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; + /// + /// let r = App::new("myprog") + /// //.setting(AppSettings::AllowInvalidUtf8) + /// .arg_from_usage("<arg> 'some positional arg'") + /// .get_matches_from_safe( + /// vec![ + /// OsString::from("myprog"), + /// OsString::from_vec(vec![0xe9])]); + /// + /// assert!(r.is_ok()); + /// let m = r.unwrap(); + /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]); + /// ``` + /// [`ArgMatches::os_value_of`]: ./struct.ArgMatches.html#method.os_value_of + /// [`ArgMatches::os_values_of`]: ./struct.ArgMatches.html#method.os_values_of + /// [`ArgMatches::lossy_value_of`]: ./struct.ArgMatches.html#method.lossy_value_of + /// [`ArgMatches::lossy_values_of`]: ./struct.ArgMatches.html#method.lossy_values_of + /// [`SubCommand`]: ./struct.SubCommand.html + AllowInvalidUtf8, + + /// Essentially sets [`Arg::overrides_with("itself")`] for all arguments. + /// + /// **WARNING:** Positional arguments cannot override themselves (or we would never be able + /// to advance to the next positional). This setting ignores positional arguments. + /// [`Arg::overrides_with("itself")`]: ./struct.Arg.html#method.overrides_with + AllArgsOverrideSelf, + + /// Specifies that leading hyphens are allowed in argument *values*, such as negative numbers + /// like `-10`. (which would otherwise be parsed as another flag or option) + /// + /// **NOTE:** Use this setting with caution as it silences certain circumstances which would + /// otherwise be an error (such as accidentally forgetting to specify a value for leading + /// option). It is preferred to set this on a per argument basis, via [`Arg::allow_hyphen_values`] + /// + /// # Examples + /// + /// ```rust + /// # use clap::{Arg, App, AppSettings}; + /// // Imagine you needed to represent negative numbers as well, such as -10 + /// let m = App::new("nums") + /// .setting(AppSettings::AllowLeadingHyphen) + /// .arg(Arg::with_name("neg").index(1)) + /// .get_matches_from(vec![ + /// "nums", "-20" + /// ]); + /// + /// assert_eq!(m.value_of("neg"), Some("-20")); + /// # ; + /// ``` + /// [`Arg::allow_hyphen_values`]: ./struct.Arg.html#method.allow_hyphen_values + AllowLeadingHyphen, + + /// Allows negative numbers to pass as values. This is similar to + /// `AllowLeadingHyphen` except that it only allows numbers, all + /// other undefined leading hyphens will fail to parse. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::AllowNegativeNumbers) + /// .arg(Arg::with_name("num")) + /// .get_matches_from_safe(vec![ + /// "myprog", "-20" + /// ]); + /// assert!(res.is_ok()); + /// let m = res.unwrap(); + /// assert_eq!(m.value_of("num").unwrap(), "-20"); + /// ``` + /// [`AllowLeadingHyphen`]: ./enum.AppSettings.html#variant.AllowLeadingHyphen + AllowNegativeNumbers, + + /// Allows one to implement two styles of CLIs where positionals can be used out of order. + /// + /// The first example is a CLI where the second to last positional argument is optional, but + /// the final positional argument is required. Such as `$ prog [optional] <required>` where one + /// of the two following usages is allowed: + /// + /// * `$ prog [optional] <required>` + /// * `$ prog <required>` + /// + /// This would otherwise not be allowed. This is useful when `[optional]` has a default value. + /// + /// **Note:** when using this style of "missing positionals" the final positional *must* be + /// [required] if `--` will not be used to skip to the final positional argument. + /// + /// **Note:** This style also only allows a single positional argument to be "skipped" without + /// the use of `--`. To skip more than one, see the second example. + /// + /// The second example is when one wants to skip multiple optional positional arguments, and use + /// of the `--` operator is OK (but not required if all arguments will be specified anyways). + /// + /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where + /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments). + /// + /// With this setting the following invocations are possible: + /// + /// * `$ prog foo bar baz1 baz2 baz3` + /// * `$ prog foo -- baz1 baz2 baz3` + /// * `$ prog -- baz1 baz2 baz3` + /// + /// # Examples + /// + /// Style number one from above: + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("arg1")) + /// .arg(Arg::with_name("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), None); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// + /// Now the same example, but using a default value for the first optional positional argument + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("arg1") + /// .default_value("something")) + /// .arg(Arg::with_name("arg2") + /// .required(true)) + /// .get_matches_from(vec![ + /// "prog", "other" + /// ]); + /// + /// assert_eq!(m.value_of("arg1"), Some("something")); + /// assert_eq!(m.value_of("arg2"), Some("other")); + /// ``` + /// Style number two from above: + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("foo")) + /// .arg(Arg::with_name("bar")) + /// .arg(Arg::with_name("baz").multiple(true)) + /// .get_matches_from(vec![ + /// "prog", "foo", "bar", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), Some("foo")); + /// assert_eq!(m.value_of("bar"), Some("bar")); + /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// + /// Now notice if we don't specify `foo` or `baz` but use the `--` operator. + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowMissingPositional) + /// .arg(Arg::with_name("foo")) + /// .arg(Arg::with_name("bar")) + /// .arg(Arg::with_name("baz").multiple(true)) + /// .get_matches_from(vec![ + /// "prog", "--", "baz1", "baz2", "baz3" + /// ]); + /// + /// assert_eq!(m.value_of("foo"), None); + /// assert_eq!(m.value_of("bar"), None); + /// assert_eq!(m.values_of("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]); + /// ``` + /// [required]: ./struct.Arg.html#method.required + AllowMissingPositional, + + /// Specifies that an unexpected positional argument, + /// which would otherwise cause a [`ErrorKind::UnknownArgument`] error, + /// should instead be treated as a [`SubCommand`] within the [`ArgMatches`] struct. + /// + /// **NOTE:** Use this setting with caution, + /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand) + /// will **not** cause an error and instead be treated as a potential subcommand. + /// One should check for such cases manually and inform the user appropriately. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// // Assume there is an external subcommand named "subcmd" + /// let m = App::new("myprog") + /// .setting(AppSettings::AllowExternalSubcommands) + /// .get_matches_from(vec![ + /// "myprog", "subcmd", "--option", "value", "-fff", "--flag" + /// ]); + /// + /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty + /// // string argument name + /// match m.subcommand() { + /// (external, Some(ext_m)) => { + /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect(); + /// assert_eq!(external, "subcmd"); + /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); + /// }, + /// _ => {}, + /// } + /// ``` + /// [`ErrorKind::UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`ArgMatches`]: ./struct.ArgMatches.html + AllowExternalSubcommands, + + /// Specifies that use of a valid [argument] negates [subcommands] being used after. By default + /// `clap` allows arguments between subcommands such as + /// `<cmd> [cmd_args] <cmd2> [cmd2_args] <cmd3> [cmd3_args]`. This setting disables that + /// functionality and says that arguments can only follow the *final* subcommand. For instance + /// using this setting makes only the following invocations possible: + /// + /// * `<cmd> <cmd2> <cmd3> [cmd3_args]` + /// * `<cmd> <cmd2> [cmd2_args]` + /// * `<cmd> [cmd_args]` + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ArgsNegateSubcommands) + /// # ; + /// ``` + /// [subcommands]: ./struct.SubCommand.html + /// [argument]: ./struct.Arg.html + ArgsNegateSubcommands, + + /// Specifies that the help text should be displayed (and then exit gracefully), + /// if no arguments are present at runtime (i.e. an empty run such as, `$ myprog`. + /// + /// **NOTE:** [`SubCommand`]s count as arguments + /// + /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will + /// ensure that some argument is always present. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ArgRequiredElseHelp) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value + ArgRequiredElseHelp, + + /// Uses colorized help messages. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColoredHelp) + /// .get_matches(); + /// ``` + ColoredHelp, + + /// Enables colored output only when the output is going to a terminal or TTY. + /// + /// **NOTE:** This is the default behavior of `clap`. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColorAuto) + /// .get_matches(); + /// ``` + ColorAuto, + + /// Enables colored output regardless of whether or not the output is going to a terminal/TTY. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature. + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms). + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColorAlways) + /// .get_matches(); + /// ``` + ColorAlways, + + /// Disables colored output no matter if the output is going to a terminal/TTY, or not. + /// + /// **NOTE:** Must be compiled with the `color` cargo feature + /// + /// # Platform Specific + /// + /// This setting only applies to Unix, Linux, and macOS (i.e. non-Windows platforms) + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::ColorNever) + /// .get_matches(); + /// ``` + ColorNever, + + /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DontCollapseArgsInUsage) + /// .get_matches(); + /// ``` + DontCollapseArgsInUsage, + + /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`] + /// was used. + /// + /// **NOTE:** The same thing can be done manually by setting the final positional argument to + /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate + /// when making changes. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DontDelimitTrailingValues) + /// .get_matches(); + /// ``` + /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg + /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter + DontDelimitTrailingValues, + + /// Disables `-h` and `--help` [`App`] without affecting any of the [`SubCommand`]s + /// (Defaults to `false`; application *does* have help flags) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableHelpFlags) + /// .get_matches_from_safe(vec![ + /// "myprog", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// + /// ```rust + /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .setting(AppSettings::DisableHelpFlags) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test", "-h" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::HelpDisplayed); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + DisableHelpFlags, + + /// Disables the `help` subcommand + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind, SubCommand}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::DisableHelpSubcommand) + /// // Normally, creating a subcommand causes a `help` subcommand to automatically + /// // be generated as well + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "help" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + DisableHelpSubcommand, + + /// Disables `-V` and `--version` [`App`] without affecting any of the [`SubCommand`]s + /// (Defaults to `false`; application *does* have a version flag) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::DisableVersion) + /// .get_matches_from_safe(vec![ + /// "myprog", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// + /// ```rust + /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::DisableVersion) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`App`]: ./struct.App.html + DisableVersion, + + /// Displays the arguments and [`SubCommand`]s in the help message in the order that they were + /// declared in, and not alphabetically which is the default. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::DeriveDisplayOrder) + /// .get_matches(); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + DeriveDisplayOrder, + + /// Specifies to use the version of the current command for all child [`SubCommand`]s. + /// (Defaults to `false`; subcommands have independent version strings from their parents.) + /// + /// **NOTE:** The version for the current command **and** this setting must be set **prior** to + /// adding any child subcommands + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::GlobalVersion) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches(); + /// // running `$ myprog test --version` will display + /// // "myprog-test v1.1" + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + GlobalVersion, + + /// Specifies that this [`SubCommand`] should be hidden from help messages + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand}; + /// App::new("myprog") + /// .subcommand(SubCommand::with_name("test") + /// .setting(AppSettings::Hidden)) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + Hidden, + + /// Tells `clap` *not* to print possible values when displaying help information. + /// This can be useful if there are many values, or they are explained elsewhere. + HidePossibleValuesInHelp, + + /// Tries to match unknown args to partial [`subcommands`] or their [aliases]. For example to + /// match a subcommand named `test`, one could use `t`, `te`, `tes`, and `test`. + /// + /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te` + /// to `test` there could not also be a subcommand or alias `temp` because both start with `te` + /// + /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when + /// designing CLIs which allow inferred subcommands and have potential positional/free + /// arguments whose values could start with the same characters as subcommands. If this is the + /// case, it's recommended to use settings such as [`AppSeettings::ArgsNegateSubcommands`] in + /// conjunction with this setting. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// let m = App::new("prog") + /// .setting(AppSettings::InferSubcommands) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from(vec![ + /// "prog", "te" + /// ]); + /// assert_eq!(m.subcommand_name(), Some("test")); + /// ``` + /// [`subcommands`]: ./struct.SubCommand.html + /// [positional/free arguments]: ./struct.Arg.html#method.index + /// [aliases]: ./struct.App.html#method.alias + /// [`AppSeettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands + InferSubcommands, + + /// Specifies that the parser should not assume the first argument passed is the binary name. + /// This is normally the case when using a "daemon" style mode, or an interactive CLI where one + /// one would not normally type the binary or program name for each command. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let m = App::new("myprog") + /// .setting(AppSettings::NoBinaryName) + /// .arg(Arg::from_usage("<cmd>... 'commands to run'")) + /// .get_matches_from(vec!["command", "set"]); + /// + /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(cmds, ["command", "set"]); + /// ``` + NoBinaryName, + + /// Places the help string for all arguments on the line after the argument. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::NextLineHelp) + /// .get_matches(); + /// ``` + NextLineHelp, + + /// **DEPRECATED**: This setting is no longer required in order to propagate values up or down + /// + /// Specifies that the parser should propagate global arg's values down or up through any *used* + /// child subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated to + /// said subcommand. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand}; + /// let m = App::new("myprog") + /// .arg(Arg::from_usage("[cmd] 'command to run'") + /// .global(true)) + /// .subcommand(SubCommand::with_name("foo")) + /// .get_matches_from(vec!["myprog", "set", "foo"]); + /// + /// assert_eq!(m.value_of("cmd"), Some("set")); + /// + /// let sub_m = m.subcommand_matches("foo").unwrap(); + /// assert_eq!(sub_m.value_of("cmd"), Some("set")); + /// ``` + /// Now doing the same thing, but *not* using any subcommands will result in the value not being + /// propagated down. + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand}; + /// let m = App::new("myprog") + /// .arg(Arg::from_usage("[cmd] 'command to run'") + /// .global(true)) + /// .subcommand(SubCommand::with_name("foo")) + /// .get_matches_from(vec!["myprog", "set"]); + /// + /// assert_eq!(m.value_of("cmd"), Some("set")); + /// + /// assert!(m.subcommand_matches("foo").is_none()); + /// ``` + #[deprecated(since = "2.27.0", note = "No longer required to propagate values")] + PropagateGlobalValuesDown, + + /// Allows [`SubCommand`]s to override all requirements of the parent command. + /// For example if you had a subcommand or top level application with a required argument + /// that is only required as long as there is no subcommand present, + /// using this setting would allow you to set those arguments to [`Arg::required(true)`] + /// and yet receive no error so long as the user uses a valid subcommand instead. + /// + /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements) + /// + /// # Examples + /// + /// This first example shows that it is an error to not use a required argument + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind}; + /// let err = App::new("myprog") + /// .setting(AppSettings::SubcommandsNegateReqs) + /// .arg(Arg::with_name("opt").required(true)) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog" + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument); + /// # ; + /// ``` + /// + /// This next example shows that it is no longer error to not use a required argument if a + /// valid subcommand is used. + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind}; + /// let noerr = App::new("myprog") + /// .setting(AppSettings::SubcommandsNegateReqs) + /// .arg(Arg::with_name("opt").required(true)) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test" + /// ]); + /// assert!(noerr.is_ok()); + /// # ; + /// ``` + /// [`Arg::required(true)`]: ./struct.Arg.html#method.required + /// [`SubCommand`]: ./struct.SubCommand.html + SubcommandsNegateReqs, + + /// Specifies that the help text should be displayed (before exiting gracefully) if no + /// [`SubCommand`]s are present at runtime (i.e. an empty run such as `$ myprog`). + /// + /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do + /// nearly same thing; this prints the help text, and the other prints an error. + /// + /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will + /// still be displayed and exit. If this is *not* the desired result, consider using + /// [`AppSettings::ArgRequiredElseHelp`] instead. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::SubcommandRequiredElseHelp) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired + /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp + SubcommandRequiredElseHelp, + + /// Specifies that any invalid UTF-8 code points should be treated as an error and fail + /// with a [`ErrorKind::InvalidUtf8`] error. + /// + /// **NOTE:** This rule only applies to argument values; Things such as flags, options, and + /// [`SubCommand`]s themselves only allow valid UTF-8 code points. + /// + /// # Platform Specific + /// + /// Non Windows systems only + /// + /// # Examples + /// + #[cfg_attr(not(unix), doc = " ```ignore")] + #[cfg_attr(unix, doc = " ```")] + /// # use clap::{App, AppSettings, ErrorKind}; + /// use std::ffi::OsString; + /// use std::os::unix::ffi::OsStringExt; + /// + /// let m = App::new("myprog") + /// .setting(AppSettings::StrictUtf8) + /// .arg_from_usage("<arg> 'some positional arg'") + /// .get_matches_from_safe( + /// vec![ + /// OsString::from("myprog"), + /// OsString::from_vec(vec![0xe9])]); + /// + /// assert!(m.is_err()); + /// assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + /// [`ErrorKind::InvalidUtf8`]: ./enum.ErrorKind.html#variant.InvalidUtf8 + StrictUtf8, + + /// Allows specifying that if no [`SubCommand`] is present at runtime, + /// error and exit gracefully. + /// + /// **NOTE:** This defaults to `false` (subcommands do *not* need to be present) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, AppSettings, SubCommand, ErrorKind}; + /// let err = App::new("myprog") + /// .setting(AppSettings::SubcommandRequired) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", + /// ]); + /// assert!(err.is_err()); + /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand); + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + SubcommandRequired, + + /// Specifies that the final positional argument is a "VarArg" and that `clap` should not + /// attempt to parse any further args. + /// + /// The values of the trailing positional argument will contain all args from itself on. + /// + /// **NOTE:** The final positional argument **must** have [`Arg::multiple(true)`] or the usage + /// string equivalent. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// let m = App::new("myprog") + /// .setting(AppSettings::TrailingVarArg) + /// .arg(Arg::from_usage("<cmd>... 'commands to run'")) + /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]); + /// + /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect(); + /// assert_eq!(trail, ["arg1", "-r", "val1"]); + /// ``` + /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple + TrailingVarArg, + + /// Groups flags and options together, presenting a more unified help message + /// (a la `getopts` or `docopt` style). + /// + /// The default is that the auto-generated help message will group flags, and options + /// separately. + /// + /// **NOTE:** This setting is cosmetic only and does not affect any functionality. + /// + /// # Examples + /// + /// ```no_run + /// # use clap::{App, Arg, SubCommand, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::UnifiedHelpMessage) + /// .get_matches(); + /// // running `myprog --help` will display a unified "docopt" or "getopts" style help message + /// ``` + UnifiedHelpMessage, + + /// Disables `-V` and `--version` for all [`SubCommand`]s + /// (Defaults to `false`; subcommands *do* have version flags.) + /// + /// **NOTE:** This setting must be set **prior** to adding any subcommands. + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, SubCommand, AppSettings, ErrorKind}; + /// let res = App::new("myprog") + /// .version("v1.1") + /// .setting(AppSettings::VersionlessSubcommands) + /// .subcommand(SubCommand::with_name("test")) + /// .get_matches_from_safe(vec![ + /// "myprog", "test", "-V" + /// ]); + /// assert!(res.is_err()); + /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + VersionlessSubcommands, + + /// Will display a message "Press \[ENTER\]/\[RETURN\] to continue..." and wait for user before + /// exiting + /// + /// This is most useful when writing an application which is run from a GUI shortcut, or on + /// Windows where a user tries to open the binary by double-clicking instead of using the + /// command line. + /// + /// **NOTE:** This setting is **not** recursive with [`SubCommand`]s, meaning if you wish this + /// behavior for all subcommands, you must set this on each command (needing this is extremely + /// rare) + /// + /// # Examples + /// + /// ```rust + /// # use clap::{App, Arg, AppSettings}; + /// App::new("myprog") + /// .setting(AppSettings::WaitOnError) + /// # ; + /// ``` + /// [`SubCommand`]: ./struct.SubCommand.html + WaitOnError, + + #[doc(hidden)] NeedsLongVersion, + + #[doc(hidden)] NeedsLongHelp, + + #[doc(hidden)] NeedsSubcommandHelp, + + #[doc(hidden)] LowIndexMultiplePositional, + + #[doc(hidden)] TrailingValues, + + #[doc(hidden)] ValidNegNumFound, + + #[doc(hidden)] Propagated, + + #[doc(hidden)] ValidArgFound, + + #[doc(hidden)] ContainsLast, +} + +impl FromStr for AppSettings { + type Err = String; + fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { + match &*s.to_ascii_lowercase() { + "disablehelpflags" => Ok(AppSettings::DisableHelpFlags), + "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp), + "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands), + "allowinvalidutf8" => Ok(AppSettings::AllowInvalidUtf8), + "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen), + "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands), + "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers), + "colorauto" => Ok(AppSettings::ColorAuto), + "coloralways" => Ok(AppSettings::ColorAlways), + "colornever" => Ok(AppSettings::ColorNever), + "coloredhelp" => Ok(AppSettings::ColoredHelp), + "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder), + "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage), + "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues), + "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand), + "disableversion" => Ok(AppSettings::DisableVersion), + "globalversion" => Ok(AppSettings::GlobalVersion), + "hidden" => Ok(AppSettings::Hidden), + "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp), + "infersubcommands" => Ok(AppSettings::InferSubcommands), + "lowindexmultiplepositional" => Ok(AppSettings::LowIndexMultiplePositional), + "nobinaryname" => Ok(AppSettings::NoBinaryName), + "nextlinehelp" => Ok(AppSettings::NextLineHelp), + "strictutf8" => Ok(AppSettings::StrictUtf8), + "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs), + "subcommandrequired" => Ok(AppSettings::SubcommandRequired), + "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp), + "trailingvararg" => Ok(AppSettings::TrailingVarArg), + "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage), + "versionlesssubcommands" => Ok(AppSettings::VersionlessSubcommands), + "waitonerror" => Ok(AppSettings::WaitOnError), + "validnegnumfound" => Ok(AppSettings::ValidNegNumFound), + "validargfound" => Ok(AppSettings::ValidArgFound), + "propagated" => Ok(AppSettings::Propagated), + "trailingvalues" => Ok(AppSettings::TrailingValues), + _ => Err("unknown AppSetting, cannot convert from str".to_owned()), + } + } +} + +#[cfg(test)] +mod test { + use super::AppSettings; + + #[test] + fn app_settings_fromstr() { + assert_eq!( + "disablehelpflags".parse::<AppSettings>().unwrap(), + AppSettings::DisableHelpFlags + ); + assert_eq!( + "argsnegatesubcommands".parse::<AppSettings>().unwrap(), + AppSettings::ArgsNegateSubcommands + ); + assert_eq!( + "argrequiredelsehelp".parse::<AppSettings>().unwrap(), + AppSettings::ArgRequiredElseHelp + ); + assert_eq!( + "allowexternalsubcommands".parse::<AppSettings>().unwrap(), + AppSettings::AllowExternalSubcommands + ); + assert_eq!( + "allowinvalidutf8".parse::<AppSettings>().unwrap(), + AppSettings::AllowInvalidUtf8 + ); + assert_eq!( + "allowleadinghyphen".parse::<AppSettings>().unwrap(), + AppSettings::AllowLeadingHyphen + ); + assert_eq!( + "allownegativenumbers".parse::<AppSettings>().unwrap(), + AppSettings::AllowNegativeNumbers + ); + assert_eq!( + "coloredhelp".parse::<AppSettings>().unwrap(), + AppSettings::ColoredHelp + ); + assert_eq!( + "colorauto".parse::<AppSettings>().unwrap(), + AppSettings::ColorAuto + ); + assert_eq!( + "coloralways".parse::<AppSettings>().unwrap(), + AppSettings::ColorAlways + ); + assert_eq!( + "colornever".parse::<AppSettings>().unwrap(), + AppSettings::ColorNever + ); + assert_eq!( + "disablehelpsubcommand".parse::<AppSettings>().unwrap(), + AppSettings::DisableHelpSubcommand + ); + assert_eq!( + "disableversion".parse::<AppSettings>().unwrap(), + AppSettings::DisableVersion + ); + assert_eq!( + "dontcollapseargsinusage".parse::<AppSettings>().unwrap(), + AppSettings::DontCollapseArgsInUsage + ); + assert_eq!( + "dontdelimittrailingvalues".parse::<AppSettings>().unwrap(), + AppSettings::DontDelimitTrailingValues + ); + assert_eq!( + "derivedisplayorder".parse::<AppSettings>().unwrap(), + AppSettings::DeriveDisplayOrder + ); + assert_eq!( + "globalversion".parse::<AppSettings>().unwrap(), + AppSettings::GlobalVersion + ); + assert_eq!( + "hidden".parse::<AppSettings>().unwrap(), + AppSettings::Hidden + ); + assert_eq!( + "hidepossiblevaluesinhelp".parse::<AppSettings>().unwrap(), + AppSettings::HidePossibleValuesInHelp + ); + assert_eq!( + "lowindexmultiplePositional".parse::<AppSettings>().unwrap(), + AppSettings::LowIndexMultiplePositional + ); + assert_eq!( + "nobinaryname".parse::<AppSettings>().unwrap(), + AppSettings::NoBinaryName + ); + assert_eq!( + "nextlinehelp".parse::<AppSettings>().unwrap(), + AppSettings::NextLineHelp + ); + assert_eq!( + "subcommandsnegatereqs".parse::<AppSettings>().unwrap(), + AppSettings::SubcommandsNegateReqs + ); + assert_eq!( + "subcommandrequired".parse::<AppSettings>().unwrap(), + AppSettings::SubcommandRequired + ); + assert_eq!( + "subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(), + AppSettings::SubcommandRequiredElseHelp + ); + assert_eq!( + "strictutf8".parse::<AppSettings>().unwrap(), + AppSettings::StrictUtf8 + ); + assert_eq!( + "trailingvararg".parse::<AppSettings>().unwrap(), + AppSettings::TrailingVarArg + ); + assert_eq!( + "unifiedhelpmessage".parse::<AppSettings>().unwrap(), + AppSettings::UnifiedHelpMessage + ); + assert_eq!( + "versionlesssubcommands".parse::<AppSettings>().unwrap(), + AppSettings::VersionlessSubcommands + ); + assert_eq!( + "waitonerror".parse::<AppSettings>().unwrap(), + AppSettings::WaitOnError + ); + assert_eq!( + "validnegnumfound".parse::<AppSettings>().unwrap(), + AppSettings::ValidNegNumFound + ); + assert_eq!( + "validargfound".parse::<AppSettings>().unwrap(), + AppSettings::ValidArgFound + ); + assert_eq!( + "propagated".parse::<AppSettings>().unwrap(), + AppSettings::Propagated + ); + assert_eq!( + "trailingvalues".parse::<AppSettings>().unwrap(), + AppSettings::TrailingValues + ); + assert_eq!( + "infersubcommands".parse::<AppSettings>().unwrap(), + AppSettings::InferSubcommands + ); + assert!("hahahaha".parse::<AppSettings>().is_err()); + } +} diff --git a/clap/src/app/usage.rs b/clap/src/app/usage.rs new file mode 100644 index 0000000..6090588 --- /dev/null +++ b/clap/src/app/usage.rs @@ -0,0 +1,479 @@ +// std +use std::collections::{BTreeMap, VecDeque}; + +// Internal +use INTERNAL_ERROR_MSG; +use args::{AnyArg, ArgMatcher, PosBuilder}; +use args::settings::ArgSettings; +use app::settings::AppSettings as AS; +use app::parser::Parser; + +// Creates a usage string for display. This happens just after all arguments were parsed, but before +// any subcommands have been parsed (so as to give subcommands their own usage recursively) +pub fn create_usage_with_title(p: &Parser, used: &[&str]) -> String { + debugln!("usage::create_usage_with_title;"); + let mut usage = String::with_capacity(75); + usage.push_str("USAGE:\n "); + usage.push_str(&*create_usage_no_title(p, used)); + usage +} + +// Creates a usage string to be used in error message (i.e. one with currently used args) +pub fn create_error_usage<'a, 'b>( + p: &Parser<'a, 'b>, + matcher: &'b ArgMatcher<'a>, + extra: Option<&str>, +) -> String { + let mut args: Vec<_> = matcher + .arg_names() + .iter() + .filter(|n| { + if let Some(o) = find_by_name!(p, **n, opts, iter) { + !o.b.is_set(ArgSettings::Required) && !o.b.is_set(ArgSettings::Hidden) + } else if let Some(p) = find_by_name!(p, **n, positionals, values) { + !p.b.is_set(ArgSettings::Required) && p.b.is_set(ArgSettings::Hidden) + } else { + true // flags can't be required, so they're always true + } + }) + .map(|&n| n) + .collect(); + if let Some(r) = extra { + args.push(r); + } + create_usage_with_title(p, &*args) +} + +// Creates a usage string (*without title*) if one was not provided by the user manually. +pub fn create_usage_no_title(p: &Parser, used: &[&str]) -> String { + debugln!("usage::create_usage_no_title;"); + if let Some(u) = p.meta.usage_str { + String::from(&*u) + } else if used.is_empty() { + create_help_usage(p, true) + } else { + create_smart_usage(p, used) + } +} + +// Creates a usage string for display in help messages (i.e. not for errors) +pub fn create_help_usage(p: &Parser, incl_reqs: bool) -> String { + let mut usage = String::with_capacity(75); + let name = p.meta + .usage + .as_ref() + .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name)); + usage.push_str(&*name); + let req_string = if incl_reqs { + let mut reqs: Vec<&str> = p.required().map(|r| &**r).collect(); + reqs.sort(); + reqs.dedup(); + get_required_usage_from(p, &reqs, None, None, false) + .iter() + .fold(String::new(), |a, s| a + &format!(" {}", s)[..]) + } else { + String::new() + }; + + let flags = needs_flags_tag(p); + if flags && !p.is_set(AS::UnifiedHelpMessage) { + usage.push_str(" [FLAGS]"); + } else if flags { + usage.push_str(" [OPTIONS]"); + } + if !p.is_set(AS::UnifiedHelpMessage) && p.opts.iter().any(|o| { + !o.is_set(ArgSettings::Required) && !o.is_set(ArgSettings::Hidden) + }) { + usage.push_str(" [OPTIONS]"); + } + + usage.push_str(&req_string[..]); + + let has_last = p.positionals.values().any(|p| p.is_set(ArgSettings::Last)); + // places a '--' in the usage string if there are args and options + // supporting multiple values + if p.opts.iter().any(|o| o.is_set(ArgSettings::Multiple)) + && p.positionals + .values() + .any(|p| !p.is_set(ArgSettings::Required)) + && !(p.has_visible_subcommands() || p.is_set(AS::AllowExternalSubcommands)) + && !has_last + { + usage.push_str(" [--]"); + } + let not_req_or_hidden = |p: &PosBuilder| { + (!p.is_set(ArgSettings::Required) || p.is_set(ArgSettings::Last)) + && !p.is_set(ArgSettings::Hidden) + }; + if p.has_positionals() && p.positionals.values().any(not_req_or_hidden) { + if let Some(args_tag) = get_args_tag(p, incl_reqs) { + usage.push_str(&*args_tag); + } else { + usage.push_str(" [ARGS]"); + } + if has_last && incl_reqs { + let pos = p.positionals + .values() + .find(|p| p.b.is_set(ArgSettings::Last)) + .expect(INTERNAL_ERROR_MSG); + debugln!("usage::create_help_usage: '{}' has .last(true)", pos.name()); + let req = pos.is_set(ArgSettings::Required); + if req + && p.positionals + .values() + .any(|p| !p.is_set(ArgSettings::Required)) + { + usage.push_str(" -- <"); + } else if req { + usage.push_str(" [--] <"); + } else { + usage.push_str(" [-- <"); + } + usage.push_str(&*pos.name_no_brackets()); + usage.push_str(">"); + usage.push_str(pos.multiple_str()); + if !req { + usage.push_str("]"); + } + } + } + + // incl_reqs is only false when this function is called recursively + if p.has_visible_subcommands() && incl_reqs || p.is_set(AS::AllowExternalSubcommands) { + if p.is_set(AS::SubcommandsNegateReqs) || p.is_set(AS::ArgsNegateSubcommands) { + if !p.is_set(AS::ArgsNegateSubcommands) { + usage.push_str("\n "); + usage.push_str(&*create_help_usage(p, false)); + usage.push_str(" <SUBCOMMAND>"); + } else { + usage.push_str("\n "); + usage.push_str(&*name); + usage.push_str(" <SUBCOMMAND>"); + } + } else if p.is_set(AS::SubcommandRequired) || p.is_set(AS::SubcommandRequiredElseHelp) { + usage.push_str(" <SUBCOMMAND>"); + } else { + usage.push_str(" [SUBCOMMAND]"); + } + } + usage.shrink_to_fit(); + debugln!("usage::create_help_usage: usage={}", usage); + usage +} + +// Creates a context aware usage string, or "smart usage" from currently used +// args, and requirements +fn create_smart_usage(p: &Parser, used: &[&str]) -> String { + debugln!("usage::smart_usage;"); + let mut usage = String::with_capacity(75); + let mut hs: Vec<&str> = p.required().map(|s| &**s).collect(); + hs.extend_from_slice(used); + + let r_string = get_required_usage_from(p, &hs, None, None, false) + .iter() + .fold(String::new(), |acc, s| acc + &format!(" {}", s)[..]); + + usage.push_str( + &p.meta + .usage + .as_ref() + .unwrap_or_else(|| p.meta.bin_name.as_ref().unwrap_or(&p.meta.name))[..], + ); + usage.push_str(&*r_string); + if p.is_set(AS::SubcommandRequired) { + usage.push_str(" <SUBCOMMAND>"); + } + usage.shrink_to_fit(); + usage +} + +// Gets the `[ARGS]` tag for the usage string +fn get_args_tag(p: &Parser, incl_reqs: bool) -> Option<String> { + debugln!("usage::get_args_tag;"); + let mut count = 0; + 'outer: for pos in p.positionals + .values() + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + { + debugln!("usage::get_args_tag:iter:{}:", pos.b.name); + if let Some(g_vec) = p.groups_for_arg(pos.b.name) { + for grp_s in &g_vec { + debugln!("usage::get_args_tag:iter:{}:iter:{};", pos.b.name, grp_s); + // if it's part of a required group we don't want to count it + if p.groups.iter().any(|g| g.required && (&g.name == grp_s)) { + continue 'outer; + } + } + } + count += 1; + debugln!( + "usage::get_args_tag:iter: {} Args not required or hidden", + count + ); + } + if !p.is_set(AS::DontCollapseArgsInUsage) && count > 1 { + debugln!("usage::get_args_tag:iter: More than one, returning [ARGS]"); + return None; // [ARGS] + } else if count == 1 && incl_reqs { + let pos = p.positionals + .values() + .find(|pos| { + !pos.is_set(ArgSettings::Required) && !pos.is_set(ArgSettings::Hidden) + && !pos.is_set(ArgSettings::Last) + }) + .expect(INTERNAL_ERROR_MSG); + debugln!( + "usage::get_args_tag:iter: Exactly one, returning '{}'", + pos.name() + ); + return Some(format!( + " [{}]{}", + pos.name_no_brackets(), + pos.multiple_str() + )); + } else if p.is_set(AS::DontCollapseArgsInUsage) && !p.positionals.is_empty() && incl_reqs { + debugln!("usage::get_args_tag:iter: Don't collapse returning all"); + return Some( + p.positionals + .values() + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + .map(|pos| { + format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()) + }) + .collect::<Vec<_>>() + .join(""), + ); + } else if !incl_reqs { + debugln!("usage::get_args_tag:iter: incl_reqs=false, building secondary usage string"); + let highest_req_pos = p.positionals + .iter() + .filter_map(|(idx, pos)| { + if pos.b.is_set(ArgSettings::Required) && !pos.b.is_set(ArgSettings::Last) { + Some(idx) + } else { + None + } + }) + .max() + .unwrap_or_else(|| p.positionals.len()); + return Some( + p.positionals + .iter() + .filter_map(|(idx, pos)| { + if idx <= highest_req_pos { + Some(pos) + } else { + None + } + }) + .filter(|pos| !pos.is_set(ArgSettings::Required)) + .filter(|pos| !pos.is_set(ArgSettings::Hidden)) + .filter(|pos| !pos.is_set(ArgSettings::Last)) + .map(|pos| { + format!(" [{}]{}", pos.name_no_brackets(), pos.multiple_str()) + }) + .collect::<Vec<_>>() + .join(""), + ); + } + Some("".into()) +} + +// Determines if we need the `[FLAGS]` tag in the usage string +fn needs_flags_tag(p: &Parser) -> bool { + debugln!("usage::needs_flags_tag;"); + 'outer: for f in &p.flags { + debugln!("usage::needs_flags_tag:iter: f={};", f.b.name); + if let Some(l) = f.s.long { + if l == "help" || l == "version" { + // Don't print `[FLAGS]` just for help or version + continue; + } + } + if let Some(g_vec) = p.groups_for_arg(f.b.name) { + for grp_s in &g_vec { + debugln!("usage::needs_flags_tag:iter:iter: grp_s={};", grp_s); + if p.groups.iter().any(|g| &g.name == grp_s && g.required) { + debugln!("usage::needs_flags_tag:iter:iter: Group is required"); + continue 'outer; + } + } + } + if f.is_set(ArgSettings::Hidden) { + continue; + } + debugln!("usage::needs_flags_tag:iter: [FLAGS] required"); + return true; + } + + debugln!("usage::needs_flags_tag: [FLAGS] not required"); + false +} + +// Returns the required args in usage string form by fully unrolling all groups +pub fn get_required_usage_from<'a, 'b>( + p: &Parser<'a, 'b>, + reqs: &[&'a str], + matcher: Option<&ArgMatcher<'a>>, + extra: Option<&str>, + incl_last: bool, +) -> VecDeque<String> { + debugln!( + "usage::get_required_usage_from: reqs={:?}, extra={:?}", + reqs, + extra + ); + let mut desc_reqs: Vec<&str> = vec![]; + desc_reqs.extend(extra); + let mut new_reqs: Vec<&str> = vec![]; + macro_rules! get_requires { + (@group $a: ident, $v:ident, $p:ident) => {{ + if let Some(rl) = p.groups.iter() + .filter(|g| g.requires.is_some()) + .find(|g| &g.name == $a) + .map(|g| g.requires.as_ref().unwrap()) { + for r in rl { + if !$p.contains(&r) { + debugln!("usage::get_required_usage_from:iter:{}: adding group req={:?}", + $a, r); + $v.push(r); + } + } + } + }}; + ($a:ident, $what:ident, $how:ident, $v:ident, $p:ident) => {{ + if let Some(rl) = p.$what.$how() + .filter(|a| a.b.requires.is_some()) + .find(|arg| &arg.b.name == $a) + .map(|a| a.b.requires.as_ref().unwrap()) { + for &(_, r) in rl.iter() { + if !$p.contains(&r) { + debugln!("usage::get_required_usage_from:iter:{}: adding arg req={:?}", + $a, r); + $v.push(r); + } + } + } + }}; + } + // initialize new_reqs + for a in reqs { + get_requires!(a, flags, iter, new_reqs, reqs); + get_requires!(a, opts, iter, new_reqs, reqs); + get_requires!(a, positionals, values, new_reqs, reqs); + get_requires!(@group a, new_reqs, reqs); + } + desc_reqs.extend_from_slice(&*new_reqs); + debugln!( + "usage::get_required_usage_from: after init desc_reqs={:?}", + desc_reqs + ); + loop { + let mut tmp = vec![]; + for a in &new_reqs { + get_requires!(a, flags, iter, tmp, desc_reqs); + get_requires!(a, opts, iter, tmp, desc_reqs); + get_requires!(a, positionals, values, tmp, desc_reqs); + get_requires!(@group a, tmp, desc_reqs); + } + if tmp.is_empty() { + debugln!("usage::get_required_usage_from: no more children"); + break; + } else { + debugln!("usage::get_required_usage_from: after iter tmp={:?}", tmp); + debugln!( + "usage::get_required_usage_from: after iter new_reqs={:?}", + new_reqs + ); + desc_reqs.extend_from_slice(&*new_reqs); + new_reqs.clear(); + new_reqs.extend_from_slice(&*tmp); + debugln!( + "usage::get_required_usage_from: after iter desc_reqs={:?}", + desc_reqs + ); + } + } + desc_reqs.extend_from_slice(reqs); + desc_reqs.sort(); + desc_reqs.dedup(); + debugln!( + "usage::get_required_usage_from: final desc_reqs={:?}", + desc_reqs + ); + let mut ret_val = VecDeque::new(); + let args_in_groups = p.groups + .iter() + .filter(|gn| desc_reqs.contains(&gn.name)) + .flat_map(|g| p.arg_names_in_group(g.name)) + .collect::<Vec<_>>(); + + let pmap = if let Some(m) = matcher { + desc_reqs + .iter() + .filter(|a| p.positionals.values().any(|p| &&p.b.name == a)) + .filter(|&pos| !m.contains(pos)) + .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos)) + .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) + .filter(|pos| !args_in_groups.contains(&pos.b.name)) + .map(|pos| (pos.index, pos)) + .collect::<BTreeMap<u64, &PosBuilder>>() // sort by index + } else { + desc_reqs + .iter() + .filter(|a| p.positionals.values().any(|pos| &&pos.b.name == a)) + .filter_map(|pos| p.positionals.values().find(|x| &x.b.name == pos)) + .filter(|&pos| incl_last || !pos.is_set(ArgSettings::Last)) + .filter(|pos| !args_in_groups.contains(&pos.b.name)) + .map(|pos| (pos.index, pos)) + .collect::<BTreeMap<u64, &PosBuilder>>() // sort by index + }; + debugln!( + "usage::get_required_usage_from: args_in_groups={:?}", + args_in_groups + ); + for &p in pmap.values() { + let s = p.to_string(); + if args_in_groups.is_empty() || !args_in_groups.contains(&&*s) { + ret_val.push_back(s); + } + } + for a in desc_reqs + .iter() + .filter(|name| !p.positionals.values().any(|p| &&p.b.name == name)) + .filter(|name| !p.groups.iter().any(|g| &&g.name == name)) + .filter(|name| !args_in_groups.contains(name)) + .filter(|name| { + !(matcher.is_some() && matcher.as_ref().unwrap().contains(name)) + }) { + debugln!("usage::get_required_usage_from:iter:{}:", a); + let arg = find_by_name!(p, *a, flags, iter) + .map(|f| f.to_string()) + .unwrap_or_else(|| { + find_by_name!(p, *a, opts, iter) + .map(|o| o.to_string()) + .expect(INTERNAL_ERROR_MSG) + }); + ret_val.push_back(arg); + } + let mut g_vec: Vec<String> = vec![]; + for g in desc_reqs + .iter() + .filter(|n| p.groups.iter().any(|g| &&g.name == n)) + { + let g_string = p.args_in_group(g).join("|"); + let elem = format!("<{}>", &g_string[..g_string.len()]); + if !g_vec.contains(&elem) { + g_vec.push(elem); + } + } + for g in g_vec { + ret_val.push_back(g); + } + + ret_val +} diff --git a/clap/src/app/validator.rs b/clap/src/app/validator.rs new file mode 100644 index 0000000..181b831 --- /dev/null +++ b/clap/src/app/validator.rs @@ -0,0 +1,573 @@ +// std +use std::fmt::Display; +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; + +// Internal +use INTERNAL_ERROR_MSG; +use INVALID_UTF8; +use args::{AnyArg, ArgMatcher, MatchedArg}; +use args::settings::ArgSettings; +use errors::{Error, ErrorKind}; +use errors::Result as ClapResult; +use app::settings::AppSettings as AS; +use app::parser::{ParseResult, Parser}; +use fmt::{Colorizer, ColorizerOption}; +use app::usage; + +pub struct Validator<'a, 'b, 'z>(&'z mut Parser<'a, 'b>) +where + 'a: 'b, + 'b: 'z; + +impl<'a, 'b, 'z> Validator<'a, 'b, 'z> { + pub fn new(p: &'z mut Parser<'a, 'b>) -> Self { Validator(p) } + + pub fn validate( + &mut self, + needs_val_of: ParseResult<'a>, + subcmd_name: Option<String>, + matcher: &mut ArgMatcher<'a>, + ) -> ClapResult<()> { + debugln!("Validator::validate;"); + let mut reqs_validated = false; + self.0.add_env(matcher)?; + self.0.add_defaults(matcher)?; + if let ParseResult::Opt(a) = needs_val_of { + debugln!("Validator::validate: needs_val_of={:?}", a); + let o = { + self.0 + .opts + .iter() + .find(|o| o.b.name == a) + .expect(INTERNAL_ERROR_MSG) + .clone() + }; + self.validate_required(matcher)?; + reqs_validated = true; + let should_err = if let Some(v) = matcher.0.args.get(&*o.b.name) { + v.vals.is_empty() && !(o.v.min_vals.is_some() && o.v.min_vals.unwrap() == 0) + } else { + true + }; + if should_err { + return Err(Error::empty_value( + &o, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + + if matcher.is_empty() && matcher.subcommand_name().is_none() + && self.0.is_set(AS::ArgRequiredElseHelp) + { + let mut out = vec![]; + self.0.write_help_err(&mut out)?; + return Err(Error { + message: String::from_utf8_lossy(&*out).into_owned(), + kind: ErrorKind::MissingArgumentOrSubcommand, + info: None, + }); + } + self.validate_blacklist(matcher)?; + if !(self.0.is_set(AS::SubcommandsNegateReqs) && subcmd_name.is_some()) && !reqs_validated { + self.validate_required(matcher)?; + } + self.validate_matched_args(matcher)?; + matcher.usage(usage::create_usage_with_title(self.0, &[])); + + Ok(()) + } + + fn validate_arg_values<A>( + &self, + arg: &A, + ma: &MatchedArg, + matcher: &ArgMatcher<'a>, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_values: arg={:?}", arg.name()); + for val in &ma.vals { + if self.0.is_set(AS::StrictUtf8) && val.to_str().is_none() { + debugln!( + "Validator::validate_arg_values: invalid UTF-8 found in val {:?}", + val + ); + return Err(Error::invalid_utf8( + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + if let Some(p_vals) = arg.possible_vals() { + debugln!("Validator::validate_arg_values: possible_vals={:?}", p_vals); + let val_str = val.to_string_lossy(); + let ok = if arg.is_set(ArgSettings::CaseInsensitive) { + p_vals.iter().any(|pv| pv.eq_ignore_ascii_case(&*val_str)) + } else { + p_vals.contains(&&*val_str) + }; + if !ok { + return Err(Error::invalid_value( + val_str, + p_vals, + arg, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + if !arg.is_set(ArgSettings::EmptyValues) && val.is_empty() + && matcher.contains(&*arg.name()) + { + debugln!("Validator::validate_arg_values: illegal empty val found"); + return Err(Error::empty_value( + arg, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + if let Some(vtor) = arg.validator() { + debug!("Validator::validate_arg_values: checking validator..."); + if let Err(e) = vtor(val.to_string_lossy().into_owned()) { + sdebugln!("error"); + return Err(Error::value_validation(Some(arg), e, self.0.color())); + } else { + sdebugln!("good"); + } + } + if let Some(vtor) = arg.validator_os() { + debug!("Validator::validate_arg_values: checking validator_os..."); + if let Err(e) = vtor(val) { + sdebugln!("error"); + return Err(Error::value_validation( + Some(arg), + (*e).to_string_lossy().to_string(), + self.0.color(), + )); + } else { + sdebugln!("good"); + } + } + } + Ok(()) + } + + fn build_err(&self, name: &str, matcher: &ArgMatcher) -> ClapResult<()> { + debugln!("build_err!: name={}", name); + let mut c_with = find_from!(self.0, &name, blacklist, matcher); + c_with = c_with.or( + self.0.find_any_arg(name).map_or(None, |aa| aa.blacklist()) + .map_or(None, + |bl| bl.iter().find(|arg| matcher.contains(arg))) + .map_or(None, |an| self.0.find_any_arg(an)) + .map_or(None, |aa| Some(format!("{}", aa))) + ); + debugln!("build_err!: '{:?}' conflicts with '{}'", c_with, &name); +// matcher.remove(&name); + let usg = usage::create_error_usage(self.0, matcher, None); + if let Some(f) = find_by_name!(self.0, name, flags, iter) { + debugln!("build_err!: It was a flag..."); + Err(Error::argument_conflict(f, c_with, &*usg, self.0.color())) + } else if let Some(o) = find_by_name!(self.0, name, opts, iter) { + debugln!("build_err!: It was an option..."); + Err(Error::argument_conflict(o, c_with, &*usg, self.0.color())) + } else { + match find_by_name!(self.0, name, positionals, values) { + Some(p) => { + debugln!("build_err!: It was a positional..."); + Err(Error::argument_conflict(p, c_with, &*usg, self.0.color())) + }, + None => panic!(INTERNAL_ERROR_MSG) + } + } + } + + fn validate_blacklist(&self, matcher: &mut ArgMatcher) -> ClapResult<()> { + debugln!("Validator::validate_blacklist;"); + let mut conflicts: Vec<&str> = vec![]; + for (&name, _) in matcher.iter() { + debugln!("Validator::validate_blacklist:iter:{};", name); + if let Some(grps) = self.0.groups_for_arg(name) { + for grp in &grps { + if let Some(g) = self.0.groups.iter().find(|g| &g.name == grp) { + if !g.multiple { + for arg in &g.args { + if arg == &name { + continue; + } + conflicts.push(arg); + } + } + if let Some(ref gc) = g.conflicts { + conflicts.extend(&*gc); + } + } + } + } + if let Some(arg) = find_any_by_name!(self.0, name) { + if let Some(bl) = arg.blacklist() { + for conf in bl { + if matcher.get(conf).is_some() { + conflicts.push(conf); + } + } + } + } else { + debugln!("Validator::validate_blacklist:iter:{}:group;", name); + let args = self.0.arg_names_in_group(name); + for arg in &args { + debugln!("Validator::validate_blacklist:iter:{}:group:iter:{};", name, arg); + if let Some(bl) = find_any_by_name!(self.0, *arg).unwrap().blacklist() { + for conf in bl { + if matcher.get(conf).is_some() { + conflicts.push(conf); + } + } + } + } + } + } + + for name in &conflicts { + debugln!( + "Validator::validate_blacklist:iter:{}: Checking blacklisted arg", + name + ); + let mut should_err = false; + if self.0.groups.iter().any(|g| &g.name == name) { + debugln!( + "Validator::validate_blacklist:iter:{}: groups contains it...", + name + ); + for n in self.0.arg_names_in_group(name) { + debugln!( + "Validator::validate_blacklist:iter:{}:iter:{}: looking in group...", + name, + n + ); + if matcher.contains(n) { + debugln!( + "Validator::validate_blacklist:iter:{}:iter:{}: matcher contains it...", + name, + n + ); + return self.build_err(n, matcher); + } + } + } else if let Some(ma) = matcher.get(name) { + debugln!( + "Validator::validate_blacklist:iter:{}: matcher contains it...", + name + ); + should_err = ma.occurs > 0; + } + if should_err { + return self.build_err(*name, matcher); + } + } + Ok(()) + } + + fn validate_matched_args(&self, matcher: &mut ArgMatcher<'a>) -> ClapResult<()> { + debugln!("Validator::validate_matched_args;"); + for (name, ma) in matcher.iter() { + debugln!( + "Validator::validate_matched_args:iter:{}: vals={:#?}", + name, + ma.vals + ); + if let Some(opt) = find_by_name!(self.0, *name, opts, iter) { + self.validate_arg_num_vals(opt, ma, matcher)?; + self.validate_arg_values(opt, ma, matcher)?; + self.validate_arg_requires(opt, ma, matcher)?; + self.validate_arg_num_occurs(opt, ma, matcher)?; + } else if let Some(flag) = find_by_name!(self.0, *name, flags, iter) { + self.validate_arg_requires(flag, ma, matcher)?; + self.validate_arg_num_occurs(flag, ma, matcher)?; + } else if let Some(pos) = find_by_name!(self.0, *name, positionals, values) { + self.validate_arg_num_vals(pos, ma, matcher)?; + self.validate_arg_num_occurs(pos, ma, matcher)?; + self.validate_arg_values(pos, ma, matcher)?; + self.validate_arg_requires(pos, ma, matcher)?; + } else { + let grp = self.0 + .groups + .iter() + .find(|g| &g.name == name) + .expect(INTERNAL_ERROR_MSG); + if let Some(ref g_reqs) = grp.requires { + if g_reqs.iter().any(|&n| !matcher.contains(n)) { + return self.missing_required_error(matcher, None); + } + } + } + } + Ok(()) + } + + fn validate_arg_num_occurs<A>( + &self, + a: &A, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_num_occurs: a={};", a.name()); + if ma.occurs > 1 && !a.is_set(ArgSettings::Multiple) { + // Not the first time, and we don't allow multiples + return Err(Error::unexpected_multiple_usage( + a, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + Ok(()) + } + + fn validate_arg_num_vals<A>( + &self, + a: &A, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_num_vals:{}", a.name()); + if let Some(num) = a.num_vals() { + debugln!("Validator::validate_arg_num_vals: num_vals set...{}", num); + let should_err = if a.is_set(ArgSettings::Multiple) { + ((ma.vals.len() as u64) % num) != 0 + } else { + num != (ma.vals.len() as u64) + }; + if should_err { + debugln!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues"); + return Err(Error::wrong_number_of_values( + a, + num, + if a.is_set(ArgSettings::Multiple) { + (ma.vals.len() % num as usize) + } else { + ma.vals.len() + }, + if ma.vals.len() == 1 + || (a.is_set(ArgSettings::Multiple) && (ma.vals.len() % num as usize) == 1) + { + "as" + } else { + "ere" + }, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + if let Some(num) = a.max_vals() { + debugln!("Validator::validate_arg_num_vals: max_vals set...{}", num); + if (ma.vals.len() as u64) > num { + debugln!("Validator::validate_arg_num_vals: Sending error TooManyValues"); + return Err(Error::too_many_values( + ma.vals + .iter() + .last() + .expect(INTERNAL_ERROR_MSG) + .to_str() + .expect(INVALID_UTF8), + a, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + } + let min_vals_zero = if let Some(num) = a.min_vals() { + debugln!("Validator::validate_arg_num_vals: min_vals set: {}", num); + if (ma.vals.len() as u64) < num && num != 0 { + debugln!("Validator::validate_arg_num_vals: Sending error TooFewValues"); + return Err(Error::too_few_values( + a, + num, + ma.vals.len(), + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + num == 0 + } else { + false + }; + // Issue 665 (https://github.com/clap-rs/clap/issues/665) + // Issue 1105 (https://github.com/clap-rs/clap/issues/1105) + if a.takes_value() && !min_vals_zero && ma.vals.is_empty() { + return Err(Error::empty_value( + a, + &*usage::create_error_usage(self.0, matcher, None), + self.0.color(), + )); + } + Ok(()) + } + + fn validate_arg_requires<A>( + &self, + a: &A, + ma: &MatchedArg, + matcher: &ArgMatcher, + ) -> ClapResult<()> + where + A: AnyArg<'a, 'b> + Display, + { + debugln!("Validator::validate_arg_requires:{};", a.name()); + if let Some(a_reqs) = a.requires() { + for &(val, name) in a_reqs.iter().filter(|&&(val, _)| val.is_some()) { + let missing_req = + |v| v == val.expect(INTERNAL_ERROR_MSG) && !matcher.contains(name); + if ma.vals.iter().any(missing_req) { + return self.missing_required_error(matcher, None); + } + } + for &(_, name) in a_reqs.iter().filter(|&&(val, _)| val.is_none()) { + if !matcher.contains(name) { + return self.missing_required_error(matcher, Some(name)); + } + } + } + Ok(()) + } + + fn validate_required(&mut self, matcher: &ArgMatcher) -> ClapResult<()> { + debugln!( + "Validator::validate_required: required={:?};", + self.0.required + ); + + let mut should_err = false; + let mut to_rem = Vec::new(); + for name in &self.0.required { + debugln!("Validator::validate_required:iter:{}:", name); + if matcher.contains(name) { + continue; + } + if to_rem.contains(name) { + continue; + } else if let Some(a) = find_any_by_name!(self.0, *name) { + if self.is_missing_required_ok(a, matcher) { + to_rem.push(a.name()); + if let Some(reqs) = a.requires() { + for r in reqs + .iter() + .filter(|&&(val, _)| val.is_none()) + .map(|&(_, name)| name) + { + to_rem.push(r); + } + } + continue; + } + } + should_err = true; + break; + } + if should_err { + for r in &to_rem { + 'inner: for i in (0 .. self.0.required.len()).rev() { + if &self.0.required[i] == r { + self.0.required.swap_remove(i); + break 'inner; + } + } + } + return self.missing_required_error(matcher, None); + } + + // Validate the conditionally required args + for &(a, v, r) in &self.0.r_ifs { + if let Some(ma) = matcher.get(a) { + if matcher.get(r).is_none() && ma.vals.iter().any(|val| val == v) { + return self.missing_required_error(matcher, Some(r)); + } + } + } + Ok(()) + } + + fn validate_arg_conflicts(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option<bool> { + debugln!("Validator::validate_arg_conflicts: a={:?};", a.name()); + a.blacklist().map(|bl| { + bl.iter().any(|conf| { + matcher.contains(conf) + || self.0 + .groups + .iter() + .find(|g| &g.name == conf) + .map_or(false, |g| g.args.iter().any(|arg| matcher.contains(arg))) + }) + }) + } + + fn validate_required_unless(&self, a: &AnyArg, matcher: &ArgMatcher) -> Option<bool> { + debugln!("Validator::validate_required_unless: a={:?};", a.name()); + macro_rules! check { + ($how:ident, $_self:expr, $a:ident, $m:ident) => {{ + $a.required_unless().map(|ru| { + ru.iter().$how(|n| { + $m.contains(n) || { + if let Some(grp) = $_self.groups.iter().find(|g| &g.name == n) { + grp.args.iter().any(|arg| $m.contains(arg)) + } else { + false + } + } + }) + }) + }}; + } + if a.is_set(ArgSettings::RequiredUnlessAll) { + check!(all, self.0, a, matcher) + } else { + check!(any, self.0, a, matcher) + } + } + + fn missing_required_error(&self, matcher: &ArgMatcher, extra: Option<&str>) -> ClapResult<()> { + debugln!("Validator::missing_required_error: extra={:?}", extra); + let c = Colorizer::new(ColorizerOption { + use_stderr: true, + when: self.0.color(), + }); + let mut reqs = self.0.required.iter().map(|&r| &*r).collect::<Vec<_>>(); + if let Some(r) = extra { + reqs.push(r); + } + reqs.retain(|n| !matcher.contains(n)); + reqs.dedup(); + debugln!("Validator::missing_required_error: reqs={:#?}", reqs); + let req_args = + usage::get_required_usage_from(self.0, &reqs[..], Some(matcher), extra, true) + .iter() + .fold(String::new(), |acc, s| { + acc + &format!("\n {}", c.error(s))[..] + }); + debugln!( + "Validator::missing_required_error: req_args={:#?}", + req_args + ); + Err(Error::missing_required_argument( + &*req_args, + &*usage::create_error_usage(self.0, matcher, extra), + self.0.color(), + )) + } + + #[inline] + fn is_missing_required_ok(&self, a: &AnyArg, matcher: &ArgMatcher) -> bool { + debugln!("Validator::is_missing_required_ok: a={}", a.name()); + self.validate_arg_conflicts(a, matcher).unwrap_or(false) + || self.validate_required_unless(a, matcher).unwrap_or(false) + } +} |