diff options
Diffstat (limited to 'clap/src')
41 files changed, 0 insertions, 20231 deletions
diff --git a/clap/src/app/help.rs b/clap/src/app/help.rs deleted file mode 100644 index 34f97ac..0000000 --- a/clap/src/app/help.rs +++ /dev/null @@ -1,1028 +0,0 @@ -// 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 deleted file mode 100644 index c7f128f..0000000 --- a/clap/src/app/meta.rs +++ /dev/null @@ -1,33 +0,0 @@ -#[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 deleted file mode 100644 index 3a1a383..0000000 --- a/clap/src/app/mod.rs +++ /dev/null @@ -1,1839 +0,0 @@ -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 deleted file mode 100644 index decfde4..0000000 --- a/clap/src/app/parser.rs +++ /dev/null @@ -1,2167 +0,0 @@ -// 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 deleted file mode 100644 index ec03997..0000000 --- a/clap/src/app/settings.rs +++ /dev/null @@ -1,1174 +0,0 @@ -// 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 deleted file mode 100644 index 6090588..0000000 --- a/clap/src/app/usage.rs +++ /dev/null @@ -1,479 +0,0 @@ -// 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 deleted file mode 100644 index 181b831..0000000 --- a/clap/src/app/validator.rs +++ /dev/null @@ -1,573 +0,0 @@ -// 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) - } -} diff --git a/clap/src/args/any_arg.rs b/clap/src/args/any_arg.rs deleted file mode 100644 index eee5228..0000000 --- a/clap/src/args/any_arg.rs +++ /dev/null @@ -1,74 +0,0 @@ -// Std -use std::rc::Rc; -use std::fmt as std_fmt; -use std::ffi::{OsStr, OsString}; - -// Internal -use args::settings::ArgSettings; -use map::{self, VecMap}; -use INTERNAL_ERROR_MSG; - -#[doc(hidden)] -pub trait AnyArg<'n, 'e>: std_fmt::Display { - fn name(&self) -> &'n str; - fn overrides(&self) -> Option<&[&'e str]>; - fn aliases(&self) -> Option<Vec<&'e str>>; - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]>; - fn blacklist(&self) -> Option<&[&'e str]>; - fn required_unless(&self) -> Option<&[&'e str]>; - fn is_set(&self, ArgSettings) -> bool; - fn set(&mut self, ArgSettings); - fn has_switch(&self) -> bool; - fn max_vals(&self) -> Option<u64>; - fn min_vals(&self) -> Option<u64>; - fn num_vals(&self) -> Option<u64>; - fn possible_vals(&self) -> Option<&[&'e str]>; - fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>>; - fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>>; - fn short(&self) -> Option<char>; - fn long(&self) -> Option<&'e str>; - fn val_delim(&self) -> Option<char>; - fn takes_value(&self) -> bool; - fn val_names(&self) -> Option<&VecMap<&'e str>>; - fn help(&self) -> Option<&'e str>; - fn long_help(&self) -> Option<&'e str>; - fn default_val(&self) -> Option<&'e OsStr>; - fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>>; - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)>; - fn longest_filter(&self) -> bool; - fn val_terminator(&self) -> Option<&'e str>; -} - -pub trait DispOrder { - fn disp_ord(&self) -> usize; -} - -impl<'n, 'e, 'z, T: ?Sized> AnyArg<'n, 'e> for &'z T where T: AnyArg<'n, 'e> + 'z { - fn name(&self) -> &'n str { (*self).name() } - fn overrides(&self) -> Option<&[&'e str]> { (*self).overrides() } - fn aliases(&self) -> Option<Vec<&'e str>> { (*self).aliases() } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { (*self).requires() } - fn blacklist(&self) -> Option<&[&'e str]> { (*self).blacklist() } - fn required_unless(&self) -> Option<&[&'e str]> { (*self).required_unless() } - fn is_set(&self, a: ArgSettings) -> bool { (*self).is_set(a) } - fn set(&mut self, _: ArgSettings) { panic!(INTERNAL_ERROR_MSG) } - fn has_switch(&self) -> bool { (*self).has_switch() } - fn max_vals(&self) -> Option<u64> { (*self).max_vals() } - fn min_vals(&self) -> Option<u64> { (*self).min_vals() } - fn num_vals(&self) -> Option<u64> { (*self).num_vals() } - fn possible_vals(&self) -> Option<&[&'e str]> { (*self).possible_vals() } - fn validator(&self) -> Option<&Rc<Fn(String) -> Result<(), String>>> { (*self).validator() } - fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> Result<(), OsString>>> { (*self).validator_os() } - fn short(&self) -> Option<char> { (*self).short() } - fn long(&self) -> Option<&'e str> { (*self).long() } - fn val_delim(&self) -> Option<char> { (*self).val_delim() } - fn takes_value(&self) -> bool { (*self).takes_value() } - fn val_names(&self) -> Option<&VecMap<&'e str>> { (*self).val_names() } - fn help(&self) -> Option<&'e str> { (*self).help() } - fn long_help(&self) -> Option<&'e str> { (*self).long_help() } - fn default_val(&self) -> Option<&'e OsStr> { (*self).default_val() } - fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> { (*self).default_vals_ifs() } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { (*self).env() } - fn longest_filter(&self) -> bool { (*self).longest_filter() } - fn val_terminator(&self) -> Option<&'e str> { (*self).val_terminator() } -} diff --git a/clap/src/args/arg.rs b/clap/src/args/arg.rs deleted file mode 100644 index 50a30ab..0000000 --- a/clap/src/args/arg.rs +++ /dev/null @@ -1,3954 +0,0 @@ -#[cfg(feature = "yaml")] -use std::collections::BTreeMap; -use std::rc::Rc; -use std::ffi::{OsStr, OsString}; -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use osstringext::OsStrExt3; -#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] -use std::os::unix::ffi::OsStrExt; -use std::env; - -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; -use map::VecMap; - -use usage_parser::UsageParser; -use args::settings::ArgSettings; -use args::arg_builder::{Base, Switched, Valued}; - -/// The abstract representation of a command line argument. Used to set all the options and -/// relationships that define a valid argument for the program. -/// -/// There are two methods for constructing [`Arg`]s, using the builder pattern and setting options -/// manually, or using a usage string which is far less verbose but has fewer options. You can also -/// use a combination of the two methods to achieve the best of both worlds. -/// -/// # Examples -/// -/// ```rust -/// # use clap::Arg; -/// // Using the traditional builder pattern and setting each option manually -/// let cfg = Arg::with_name("config") -/// .short("c") -/// .long("config") -/// .takes_value(true) -/// .value_name("FILE") -/// .help("Provides a config file to myprog"); -/// // Using a usage string (setting a similar argument to the one above) -/// let input = Arg::from_usage("-i, --input=[FILE] 'Provides an input file to the program'"); -/// ``` -/// [`Arg`]: ./struct.Arg.html -#[allow(missing_debug_implementations)] -#[derive(Default, Clone)] -pub struct Arg<'a, 'b> -where - 'a: 'b, -{ - #[doc(hidden)] pub b: Base<'a, 'b>, - #[doc(hidden)] pub s: Switched<'b>, - #[doc(hidden)] pub v: Valued<'a, 'b>, - #[doc(hidden)] pub index: Option<u64>, - #[doc(hidden)] pub r_ifs: Option<Vec<(&'a str, &'b str)>>, -} - -impl<'a, 'b> Arg<'a, 'b> { - /// Creates a new instance of [`Arg`] using a unique string name. The name will be used to get - /// information about whether or not the argument was used at runtime, get values, set - /// relationships with other args, etc.. - /// - /// **NOTE:** In the case of arguments that take values (i.e. [`Arg::takes_value(true)`]) - /// and positional arguments (i.e. those without a preceding `-` or `--`) the name will also - /// be displayed when the user prints the usage/help information of the program. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// # ; - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg`]: ./struct.Arg.html - pub fn with_name(n: &'a str) -> Self { - Arg { - b: Base::new(n), - ..Default::default() - } - } - - /// Creates a new instance of [`Arg`] from a .yml (YAML) file. - /// - /// # Examples - /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::Arg; - /// # fn main() { - /// let yml = load_yaml!("arg.yml"); - /// let arg = Arg::from_yaml(yml); - /// # } - /// ``` - /// [`Arg`]: ./struct.Arg.html - #[cfg(feature = "yaml")] - pub fn from_yaml(y: &BTreeMap<Yaml, Yaml>) -> Arg { - // We WANT this to panic on error...so expect() is good. - let name_yml = y.keys().nth(0).unwrap(); - let name_str = name_yml.as_str().unwrap(); - let mut a = Arg::with_name(name_str); - let arg_settings = y.get(name_yml).unwrap().as_hash().unwrap(); - - for (k, v) in arg_settings.iter() { - a = match k.as_str().unwrap() { - "short" => yaml_to_str!(a, v, short), - "long" => yaml_to_str!(a, v, long), - "aliases" => yaml_vec_or_str!(v, a, alias), - "help" => yaml_to_str!(a, v, help), - "long_help" => yaml_to_str!(a, v, long_help), - "required" => yaml_to_bool!(a, v, required), - "required_if" => yaml_tuple2!(a, v, required_if), - "required_ifs" => yaml_tuple2!(a, v, required_if), - "takes_value" => yaml_to_bool!(a, v, takes_value), - "index" => yaml_to_u64!(a, v, index), - "global" => yaml_to_bool!(a, v, global), - "multiple" => yaml_to_bool!(a, v, multiple), - "hidden" => yaml_to_bool!(a, v, hidden), - "next_line_help" => yaml_to_bool!(a, v, next_line_help), - "empty_values" => yaml_to_bool!(a, v, empty_values), - "group" => yaml_to_str!(a, v, group), - "number_of_values" => yaml_to_u64!(a, v, number_of_values), - "max_values" => yaml_to_u64!(a, v, max_values), - "min_values" => yaml_to_u64!(a, v, min_values), - "value_name" => yaml_to_str!(a, v, value_name), - "use_delimiter" => yaml_to_bool!(a, v, use_delimiter), - "allow_hyphen_values" => yaml_to_bool!(a, v, allow_hyphen_values), - "last" => yaml_to_bool!(a, v, last), - "require_delimiter" => yaml_to_bool!(a, v, require_delimiter), - "value_delimiter" => yaml_to_str!(a, v, value_delimiter), - "required_unless" => yaml_to_str!(a, v, required_unless), - "display_order" => yaml_to_usize!(a, v, display_order), - "default_value" => yaml_to_str!(a, v, default_value), - "default_value_if" => yaml_tuple3!(a, v, default_value_if), - "default_value_ifs" => yaml_tuple3!(a, v, default_value_if), - "env" => yaml_to_str!(a, v, env), - "value_names" => yaml_vec_or_str!(v, a, value_name), - "groups" => yaml_vec_or_str!(v, a, group), - "requires" => yaml_vec_or_str!(v, a, requires), - "requires_if" => yaml_tuple2!(a, v, requires_if), - "requires_ifs" => yaml_tuple2!(a, v, requires_if), - "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), - "overrides_with" => yaml_vec_or_str!(v, a, overrides_with), - "possible_values" => yaml_vec_or_str!(v, a, possible_value), - "case_insensitive" => yaml_to_bool!(a, v, case_insensitive), - "required_unless_one" => yaml_vec_or_str!(v, a, required_unless), - "required_unless_all" => { - a = yaml_vec_or_str!(v, a, required_unless); - a.setb(ArgSettings::RequiredUnlessAll); - a - } - s => panic!( - "Unknown Arg setting '{}' in YAML file for arg '{}'", - s, name_str - ), - } - } - - a - } - - /// Creates a new instance of [`Arg`] from a usage string. Allows creation of basic settings - /// for the [`Arg`]. The syntax is flexible, but there are some rules to follow. - /// - /// **NOTE**: Not all settings may be set using the usage string method. Some properties are - /// only available via the builder pattern. - /// - /// **NOTE**: Only ASCII values are officially supported in [`Arg::from_usage`] strings. Some - /// UTF-8 codepoints may work just fine, but this is not guaranteed. - /// - /// # Syntax - /// - /// Usage strings typically following the form: - /// - /// ```notrust - /// [explicit name] [short] [long] [value names] [help string] - /// ``` - /// - /// This is not a hard rule as the attributes can appear in other orders. There are also - /// several additional sigils which denote additional settings. Below are the details of each - /// portion of the string. - /// - /// ### Explicit Name - /// - /// This is an optional field, if it's omitted the argument will use one of the additional - /// fields as the name using the following priority order: - /// - /// * Explicit Name (This always takes precedence when present) - /// * Long - /// * Short - /// * Value Name - /// - /// `clap` determines explicit names as the first string of characters between either `[]` or - /// `<>` where `[]` has the dual notation of meaning the argument is optional, and `<>` meaning - /// the argument is required. - /// - /// Explicit names may be followed by: - /// * The multiple denotation `...` - /// - /// Example explicit names as follows (`ename` for an optional argument, and `rname` for a - /// required argument): - /// - /// ```notrust - /// [ename] -s, --long 'some flag' - /// <rname> -r, --longer 'some other flag' - /// ``` - /// - /// ### Short - /// - /// This is set by placing a single character after a leading `-`. - /// - /// Shorts may be followed by - /// * The multiple denotation `...` - /// * An optional comma `,` which is cosmetic only - /// * Value notation - /// - /// Example shorts are as follows (`-s`, and `-r`): - /// - /// ```notrust - /// -s, --long 'some flag' - /// <rname> -r [val], --longer 'some option' - /// ``` - /// - /// ### Long - /// - /// This is set by placing a word (no spaces) after a leading `--`. - /// - /// Shorts may be followed by - /// * The multiple denotation `...` - /// * Value notation - /// - /// Example longs are as follows (`--some`, and `--rapid`): - /// - /// ```notrust - /// -s, --some 'some flag' - /// --rapid=[FILE] 'some option' - /// ``` - /// - /// ### Values (Value Notation) - /// - /// This is set by placing a word(s) between `[]` or `<>` optionally after `=` (although this - /// is cosmetic only and does not affect functionality). If an explicit name has **not** been - /// set, using `<>` will denote a required argument, and `[]` will denote an optional argument - /// - /// Values may be followed by - /// * The multiple denotation `...` - /// * More Value notation - /// - /// More than one value will also implicitly set the arguments number of values, i.e. having - /// two values, `--option [val1] [val2]` specifies that in order for option to be satisified it - /// must receive exactly two values - /// - /// Example values are as follows (`FILE`, and `SPEED`): - /// - /// ```notrust - /// -s, --some [FILE] 'some option' - /// --rapid=<SPEED>... 'some required multiple option' - /// ``` - /// - /// ### Help String - /// - /// The help string is denoted between a pair of single quotes `''` and may contain any - /// characters. - /// - /// Example help strings are as follows: - /// - /// ```notrust - /// -s, --some [FILE] 'some option' - /// --rapid=<SPEED>... 'some required multiple option' - /// ``` - /// - /// ### Additional Sigils - /// - /// Multiple notation `...` (three consecutive dots/periods) specifies that this argument may - /// be used multiple times. Do not confuse multiple occurrences (`...`) with multiple values. - /// `--option val1 val2` is a single occurrence with multiple values. `--flag --flag` is - /// multiple occurrences (and then you can obviously have instances of both as well) - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// App::new("prog") - /// .args(&[ - /// Arg::from_usage("--config <FILE> 'a required file for the configuration and no short'"), - /// Arg::from_usage("-d, --debug... 'turns on debugging information and allows multiples'"), - /// Arg::from_usage("[input] 'an optional input file to use'") - /// ]) - /// # ; - /// ``` - /// [`Arg`]: ./struct.Arg.html - /// [`Arg::from_usage`]: ./struct.Arg.html#method.from_usage - pub fn from_usage(u: &'a str) -> Self { - let parser = UsageParser::from_usage(u); - parser.parse() - } - - /// Sets the short version of the argument without the preceding `-`. - /// - /// By default `clap` automatically assigns `V` and `h` to the auto-generated `version` and - /// `help` arguments respectively. You may use the uppercase `V` or lowercase `h` for your own - /// arguments, in which case `clap` simply will not assign those to the auto-generated - /// `version` or `help` arguments. - /// - /// **NOTE:** Any leading `-` characters will be stripped, and only the first - /// non `-` character will be used as the [`short`] version - /// - /// # Examples - /// - /// To set [`short`] use a single valid UTF-8 code point. If you supply a leading `-` such as - /// `-c`, the `-` will be stripped. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .short("c") - /// # ; - /// ``` - /// - /// Setting [`short`] allows using the argument via a single hyphen (`-`) such as `-c` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("config") - /// .short("c")) - /// .get_matches_from(vec![ - /// "prog", "-c" - /// ]); - /// - /// assert!(m.is_present("config")); - /// ``` - /// [`short`]: ./struct.Arg.html#method.short - pub fn short<S: AsRef<str>>(mut self, s: S) -> Self { - self.s.short = s.as_ref().trim_left_matches(|c| c == '-').chars().nth(0); - self - } - - /// Sets the long version of the argument without the preceding `--`. - /// - /// By default `clap` automatically assigns `version` and `help` to the auto-generated - /// `version` and `help` arguments respectively. You may use the word `version` or `help` for - /// the long form of your own arguments, in which case `clap` simply will not assign those to - /// the auto-generated `version` or `help` arguments. - /// - /// **NOTE:** Any leading `-` characters will be stripped - /// - /// # Examples - /// - /// To set `long` use a word containing valid UTF-8 codepoints. If you supply a double leading - /// `--` such as `--config` they will be stripped. Hyphens in the middle of the word, however, - /// will *not* be stripped (i.e. `config-file` is allowed) - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("cfg") - /// .long("config") - /// # ; - /// ``` - /// - /// Setting `long` allows using the argument via a double hyphen (`--`) such as `--config` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config")) - /// .get_matches_from(vec![ - /// "prog", "--config" - /// ]); - /// - /// assert!(m.is_present("cfg")); - /// ``` - pub fn long(mut self, l: &'b str) -> Self { - self.s.long = Some(l.trim_left_matches(|c| c == '-')); - self - } - - /// Allows adding a [`Arg`] alias, which function as "hidden" arguments that - /// automatically dispatch as if this argument was used. This is more efficient, and easier - /// than creating multiple hidden arguments as one only needs to check for the existence of - /// this command, and not all variants. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .long("test") - /// .alias("alias") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--alias", "cool" - /// ]); - /// assert!(m.is_present("test")); - /// assert_eq!(m.value_of("test"), Some("cool")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - pub fn alias<S: Into<&'b str>>(mut self, name: S) -> Self { - if let Some(ref mut als) = self.s.aliases { - als.push((name.into(), false)); - } else { - self.s.aliases = Some(vec![(name.into(), false)]); - } - self - } - - /// Allows adding [`Arg`] aliases, which function as "hidden" arguments that - /// automatically dispatch as if this argument 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}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .long("test") - /// .aliases(&["do-stuff", "do-tests", "tests"]) - /// .help("the file to add") - /// .required(false)) - /// .get_matches_from(vec![ - /// "prog", "--do-tests" - /// ]); - /// assert!(m.is_present("test")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - pub fn aliases(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut als) = self.s.aliases { - for n in names { - als.push((n, false)); - } - } else { - self.s.aliases = Some(names.iter().map(|n| (*n, false)).collect::<Vec<_>>()); - } - self - } - - /// Allows adding a [`Arg`] alias that functions exactly like those defined with - /// [`Arg::alias`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .visible_alias("something-awesome") - /// .long("test") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--something-awesome", "coffee" - /// ]); - /// assert!(m.is_present("test")); - /// assert_eq!(m.value_of("test"), Some("coffee")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - /// [`App::alias`]: ./struct.Arg.html#method.alias - pub fn visible_alias<S: Into<&'b str>>(mut self, name: S) -> Self { - if let Some(ref mut als) = self.s.aliases { - als.push((name.into(), true)); - } else { - self.s.aliases = Some(vec![(name.into(), true)]); - } - self - } - - /// Allows adding multiple [`Arg`] aliases that functions exactly like those defined - /// with [`Arg::aliases`], except that they are visible inside the help message. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("test") - /// .long("test") - /// .visible_aliases(&["something", "awesome", "cool"])) - /// .get_matches_from(vec![ - /// "prog", "--awesome" - /// ]); - /// assert!(m.is_present("test")); - /// ``` - /// [`Arg`]: ./struct.Arg.html - /// [`App::aliases`]: ./struct.Arg.html#method.aliases - pub fn visible_aliases(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut als) = self.s.aliases { - for n in names { - als.push((n, true)); - } - } else { - self.s.aliases = Some(names.iter().map(|n| (*n, true)).collect::<Vec<_>>()); - } - self - } - - /// Sets the short help text of the argument that will be displayed to the user when they print - /// the help information with `-h`. Typically, this is a short (one line) description of the - /// arg. - /// - /// **NOTE:** If only `Arg::help` is provided, and not [`Arg::long_help`] but the user requests - /// `--help` clap will still display the contents of `help` appropriately - /// - /// **NOTE:** Only `Arg::help` is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .help("The config file used by the myprog") - /// # ; - /// ``` - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --config Some help text describing the --config arg - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// [`Arg::long_help`]: ./struct.Arg.html#method.long_help - pub fn help(mut self, h: &'b str) -> Self { - self.b.help = Some(h); - self - } - - /// Sets the long help text of the argument that will be displayed to the user when they print - /// the help information with `--help`. Typically this a more detailed (multi-line) message - /// that describes the arg. - /// - /// **NOTE:** If only `long_help` is provided, and not [`Arg::help`] but the user requests `-h` - /// clap will still display the contents of `long_help` appropriately - /// - /// **NOTE:** Only [`Arg::help`] is used in completion script generation in order to be concise - /// - /// # Examples - /// - /// Any valid UTF-8 is allowed in the help text. The one exception is when one wishes to - /// include a newline in the help text and have the following text be properly aligned with all - /// the other help text. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .long_help( - /// "The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now.") - /// # ; - /// ``` - /// - /// Setting `help` displays a short message to the side of the argument when the user passes - /// `-h` or `--help` (by default). - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .long_help( - /// "The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now.")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --config - /// The config file used by the myprog must be in JSON format - /// with only valid keys and may not contain other nonsense - /// that cannot be read by this program. Obviously I'm going on - /// and on, so I'll stop now. - /// - /// -h, --help - /// Prints help information - /// - /// -V, --version - /// Prints version information - /// ``` - /// [`Arg::help`]: ./struct.Arg.html#method.help - pub fn long_help(mut self, h: &'b str) -> Self { - self.b.long_help = Some(h); - self - } - - /// Specifies that this arg is the last, or final, positional argument (i.e. has the highest - /// index) and is *only* able to be accessed via the `--` syntax (i.e. `$ prog args -- - /// last_arg`). Even, if no other arguments are left to parse, if the user omits the `--` syntax - /// they will receive an [`UnknownArgument`] error. Setting an argument to `.last(true)` also - /// allows one to access this arg early using the `--` syntax. Accessing an arg early, even with - /// the `--` syntax is otherwise not possible. - /// - /// **NOTE:** This will change the usage string to look like `$ prog [FLAGS] [-- <ARG>]` if - /// `ARG` is marked as `.last(true)`. - /// - /// **NOTE:** This setting will imply [`AppSettings::DontCollapseArgsInUsage`] because failing - /// to set this can make the usage string very confusing. - /// - /// **NOTE**: This setting only applies to positional arguments, and has no affect on FLAGS / - /// OPTIONS - /// - /// **CAUTION:** Setting an argument to `.last(true)` *and* having child subcommands is not - /// recommended with the exception of *also* using [`AppSettings::ArgsNegateSubcommands`] - /// (or [`AppSettings::SubcommandsNegateReqs`] if the argument marked `.last(true)` is also - /// marked [`.required(true)`]) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("args") - /// .last(true) - /// # ; - /// ``` - /// - /// Setting [`Arg::last(true)`] ensures the arg has the highest [index] of all positional args - /// and requires that the `--` syntax be used to access it early. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("first")) - /// .arg(Arg::with_name("second")) - /// .arg(Arg::with_name("third").last(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "one", "--", "three" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// assert_eq!(m.value_of("third"), Some("three")); - /// assert!(m.value_of("second").is_none()); - /// ``` - /// - /// Even if the positional argument marked `.last(true)` is the only argument left to parse, - /// failing to use the `--` syntax results in an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("first")) - /// .arg(Arg::with_name("second")) - /// .arg(Arg::with_name("third").last(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "one", "two", "three" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::last(true)`]: ./struct.Arg.html#method.last - /// [index]: ./struct.Arg.html#method.index - /// [`AppSettings::DontCollapseArgsInUsage`]: ./enum.AppSettings.html#variant.DontCollapseArgsInUsage - /// [`AppSettings::ArgsNegateSubcommands`]: ./enum.AppSettings.html#variant.ArgsNegateSubcommands - /// [`AppSettings::SubcommandsNegateReqs`]: ./enum.AppSettings.html#variant.SubcommandsNegateReqs - /// [`.required(true)`]: ./struct.Arg.html#method.required - /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument - pub fn last(self, l: bool) -> Self { - if l { - self.set(ArgSettings::Last) - } else { - self.unset(ArgSettings::Last) - } - } - - /// Sets whether or not the argument is required by default. Required by default means it is - /// required, when no other conflicting rules have been evaluated. Conflicting rules take - /// precedence over being required. **Default:** `false` - /// - /// **NOTE:** Flags (i.e. not positional, or arguments that take values) cannot be required by - /// default. This is simply because if a flag should be required, it should simply be implied - /// as no additional information is required from user. Flags by their very nature are simply - /// yes/no, or true/false. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required(true) - /// # ; - /// ``` - /// - /// Setting [`Arg::required(true)`] requires that the argument be used at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required(true)`] and *not* supplying that argument is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::required(true)`]: ./struct.Arg.html#method.required - pub fn required(self, r: bool) -> Self { - if r { - self.set(ArgSettings::Required) - } else { - self.unset(ArgSettings::Required) - } - } - - /// Requires that options use the `--option=val` syntax (i.e. an equals between the option and - /// associated value) **Default:** `false` - /// - /// **NOTE:** This setting also removes the default of allowing empty values and implies - /// [`Arg::empty_values(false)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .long("config") - /// .takes_value(true) - /// .require_equals(true) - /// # ; - /// ``` - /// - /// Setting [`Arg::require_equals(true)`] requires that the option have an equals sign between - /// it and the associated value. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .require_equals(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config=file.conf" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::require_equals(true)`] and *not* supplying the equals will cause an error - /// unless [`Arg::empty_values(true)`] is set. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .require_equals(true) - /// .takes_value(true) - /// .long("config")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); - /// ``` - /// [`Arg::require_equals(true)`]: ./struct.Arg.html#method.require_equals - /// [`Arg::empty_values(true)`]: ./struct.Arg.html#method.empty_values - /// [`Arg::empty_values(false)`]: ./struct.Arg.html#method.empty_values - pub fn require_equals(mut self, r: bool) -> Self { - if r { - self.unsetb(ArgSettings::EmptyValues); - self.set(ArgSettings::RequireEquals) - } else { - self.unset(ArgSettings::RequireEquals) - } - } - - /// Allows values which start with a leading hyphen (`-`) - /// - /// **WARNING**: Take caution when using this setting combined with [`Arg::multiple(true)`], as - /// this becomes ambiguous `$ prog --arg -- -- val`. All three `--, --, val` will be values - /// when the user may have thought the second `--` would constitute the normal, "Only - /// positional args follow" idiom. To fix this, consider using [`Arg::number_of_values(1)`] - /// - /// **WARNING**: When building your CLIs, consider the effects of allowing leading hyphens and - /// the user passing in a value that matches a valid short. For example `prog -opt -F` where - /// `-F` is supposed to be a value, yet `-F` is *also* a valid short for another arg. Care should - /// should be taken when designing these args. This is compounded by the ability to "stack" - /// short args. I.e. if `-val` is supposed to be a value, but `-v`, `-a`, and `-l` are all valid - /// shorts. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("pattern") - /// .allow_hyphen_values(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("pat") - /// .allow_hyphen_values(true) - /// .takes_value(true) - /// .long("pattern")) - /// .get_matches_from(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert_eq!(m.value_of("pat"), Some("-file")); - /// ``` - /// - /// Not setting [`Arg::allow_hyphen_values(true)`] and supplying a value which starts with a - /// hyphen is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("pat") - /// .takes_value(true) - /// .long("pattern")) - /// .get_matches_from_safe(vec![ - /// "prog", "--pattern", "-file" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values - pub fn allow_hyphen_values(self, a: bool) -> Self { - if a { - self.set(ArgSettings::AllowLeadingHyphen) - } else { - self.unset(ArgSettings::AllowLeadingHyphen) - } - } - /// Sets an arg that override this arg's required setting. (i.e. this arg will be required - /// unless this other argument is present). - /// - /// **Pro Tip:** Using [`Arg::required_unless`] implies [`Arg::required`] and is therefore not - /// mandatory to also set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_unless("debug") - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless(name)`] requires that the argument be used at runtime - /// *unless* `name` is present. In the following example, the required argument is *not* - /// provided, but it's not an error because the `unless` arg has been supplied. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless("dbg") - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless(name)`] and *not* supplying `name` or this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless("dbg") - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::required_unless`]: ./struct.Arg.html#method.required_unless - /// [`Arg::required`]: ./struct.Arg.html#method.required - /// [`Arg::required_unless(name)`]: ./struct.Arg.html#method.required_unless - pub fn required_unless(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.r_unless { - vec.push(name); - } else { - self.b.r_unless = Some(vec![name]); - } - self.required(true) - } - - /// Sets args that override this arg's required setting. (i.e. this arg will be required unless - /// all these other arguments are present). - /// - /// **NOTE:** If you wish for this argument to only be required if *one of* these args are - /// present see [`Arg::required_unless_one`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_unless_all(&["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_all(names)`] requires that the argument be used at runtime - /// *unless* *all* the args in `names` are present. In the following example, the required - /// argument is *not* provided, but it's not an error because all the `unless` args have been - /// supplied. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_all(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug", "-i", "file" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_all(names)`] and *not* supplying *all* of `names` or this - /// arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_all(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::required_unless_one`]: ./struct.Arg.html#method.required_unless_one - /// [`Arg::required_unless_all(names)`]: ./struct.Arg.html#method.required_unless_all - pub fn required_unless_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.r_unless { - for s in names { - vec.push(s); - } - } else { - self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); - } - self.setb(ArgSettings::RequiredUnlessAll); - self.required(true) - } - - /// Sets args that override this arg's [required] setting. (i.e. this arg will be required - /// unless *at least one of* these other arguments are present). - /// - /// **NOTE:** If you wish for this argument to only be required if *all of* these args are - /// present see [`Arg::required_unless_all`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_unless_all(&["cfg", "dbg"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_unless_one(names)`] requires that the argument be used at runtime - /// *unless* *at least one of* the args in `names` are present. In the following example, the - /// required argument is *not* provided, but it's not an error because one the `unless` args - /// have been supplied. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_one(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug" - /// ]); - /// - /// assert!(res.is_ok()); - /// ``` - /// - /// Setting [`Arg::required_unless_one(names)`] and *not* supplying *at least one of* `names` - /// or this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_unless_one(&["dbg", "infile"]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("dbg") - /// .long("debug")) - /// .arg(Arg::with_name("infile") - /// .short("i") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [required]: ./struct.Arg.html#method.required - /// [`Arg::required_unless_one(names)`]: ./struct.Arg.html#method.required_unless_one - /// [`Arg::required_unless_all`]: ./struct.Arg.html#method.required_unless_all - pub fn required_unless_one(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.r_unless { - for s in names { - vec.push(s); - } - } else { - self.b.r_unless = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); - } - self.required(true) - } - - /// Sets a conflicting argument by name. I.e. when using this argument, - /// the following argument can't be present and vice versa. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need - /// need to also do B.conflicts_with(A)) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .conflicts_with("debug") - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having both arguments present at runtime is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .conflicts_with("debug") - /// .long("config")) - /// .arg(Arg::with_name("debug") - /// .long("debug")) - /// .get_matches_from_safe(vec![ - /// "prog", "--debug", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); - /// ``` - pub fn conflicts_with(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.blacklist { - vec.push(name); - } else { - self.b.blacklist = Some(vec![name]); - } - self - } - - /// The same as [`Arg::conflicts_with`] but allows specifying multiple two-way conlicts per - /// argument. - /// - /// **NOTE:** Conflicting rules take precedence over being required by default. Conflict rules - /// only need to be set for one of the two arguments, they do not need to be set for each. - /// - /// **NOTE:** Defining a conflict is two-way, but does *not* need to defined for both arguments - /// (i.e. if A conflicts with B, defining A.conflicts_with(B) is sufficient. You do not need - /// need to also do B.conflicts_with(A)) - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .conflicts_with_all(&["debug", "input"]) - /// # ; - /// ``` - /// - /// Setting conflicting argument, and having any of the arguments present at runtime with a - /// conflicting argument is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .conflicts_with_all(&["debug", "input"]) - /// .long("config")) - /// .arg(Arg::with_name("debug") - /// .long("debug")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf", "file.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::ArgumentConflict); - /// ``` - /// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with - pub fn conflicts_with_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.blacklist { - for s in names { - vec.push(s); - } - } else { - self.b.blacklist = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); - } - self - } - - /// Sets a overridable argument by name. I.e. this argument and the following argument - /// will override each other in POSIX style (whichever argument was specified at runtime - /// **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// **WARNING:** Positional arguments cannot override themselves (or we would never be able - /// to advance to the next positional). If a positional agument lists itself as an override, - /// it is simply ignored. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::from_usage("-f, --flag 'some flag'") - /// .conflicts_with("debug")) - /// .arg(Arg::from_usage("-d, --debug 'other flag'")) - /// .arg(Arg::from_usage("-c, --color 'third flag'") - /// .overrides_with("flag")) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~~~~~~~^~~~~ flag is overridden by color - /// - /// assert!(m.is_present("color")); - /// assert!(m.is_present("debug")); // even though flag conflicts with debug, it's as if flag - /// // was never used because it was overridden with color - /// assert!(!m.is_present("flag")); - /// ``` - /// Care must be taken when using this setting, and having an arg override with itself. This - /// is common practice when supporting things like shell aliases, config files, etc. - /// However, when combined with multiple values, it can get dicy. - /// Here is how clap handles such situations: - /// - /// When a flag overrides itself, it's as if the flag was only ever used once (essentially - /// preventing a "Unexpected multiple usage" error): - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--flag 'some flag'").overrides_with("flag")) - /// .get_matches_from(vec!["posix", "--flag", "--flag"]); - /// assert!(m.is_present("flag")); - /// assert_eq!(m.occurrences_of("flag"), 1); - /// ``` - /// Making a arg `multiple(true)` and override itself is essentially meaningless. Therefore - /// clap ignores an override of self if it's a flag and it already accepts multiple occurrences. - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--flag... 'some flag'").overrides_with("flag")) - /// .get_matches_from(vec!["", "--flag", "--flag", "--flag", "--flag"]); - /// assert!(m.is_present("flag")); - /// assert_eq!(m.occurrences_of("flag"), 4); - /// ``` - /// Now notice with options (which *do not* set `multiple(true)`), it's as if only the last - /// occurrence happened. - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--opt [val] 'some option'").overrides_with("opt")) - /// .get_matches_from(vec!["", "--opt=some", "--opt=other"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 1); - /// assert_eq!(m.value_of("opt"), Some("other")); - /// ``` - /// - /// Just like flags, options with `multiple(true)` set, will ignore the "override self" setting. - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--opt [val]... 'some option'") - /// .overrides_with("opt")) - /// .get_matches_from(vec!["", "--opt", "first", "over", "--opt", "other", "val"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 2); - /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["first", "over", "other", "val"]); - /// ``` - /// - /// A safe thing to do if you'd like to support an option which supports multiple values, but - /// also is "overridable" by itself, is to use `use_delimiter(false)` and *not* use - /// `multiple(true)` while telling users to seperate values with a comma (i.e. `val1,val2`) - /// - /// ``` - /// # use clap::{App, Arg}; - /// let m = App::new("posix") - /// .arg(Arg::from_usage("--opt [val] 'some option'") - /// .overrides_with("opt") - /// .use_delimiter(false)) - /// .get_matches_from(vec!["", "--opt=some,other", "--opt=one,two"]); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 1); - /// assert_eq!(m.values_of("opt").unwrap().collect::<Vec<_>>(), &["one,two"]); - /// ``` - pub fn overrides_with(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.overrides { - vec.push(name); - } else { - self.b.overrides = Some(vec![name]); - } - self - } - - /// Sets multiple mutually overridable arguments by name. I.e. this argument and the following - /// argument will override each other in POSIX style (whichever argument was specified at - /// runtime **last** "wins") - /// - /// **NOTE:** When an argument is overridden it is essentially as if it never was used, any - /// conflicts, requirements, etc. are evaluated **after** all "overrides" have been removed - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::from_usage("-f, --flag 'some flag'") - /// .conflicts_with("color")) - /// .arg(Arg::from_usage("-d, --debug 'other flag'")) - /// .arg(Arg::from_usage("-c, --color 'third flag'") - /// .overrides_with_all(&["flag", "debug"])) - /// .get_matches_from(vec![ - /// "prog", "-f", "-d", "-c"]); - /// // ^~~~~~^~~~~~~~~ flag and debug are overridden by color - /// - /// assert!(m.is_present("color")); // even though flag conflicts with color, it's as if flag - /// // and debug were never used because they were overridden - /// // with color - /// assert!(!m.is_present("debug")); - /// assert!(!m.is_present("flag")); - /// ``` - pub fn overrides_with_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.overrides { - for s in names { - vec.push(s); - } - } else { - self.b.overrides = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); - } - self - } - - /// Sets an argument by name that is required when this one is present I.e. when - /// using this argument, the following argument *must* be present. - /// - /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .requires("input") - /// # ; - /// ``` - /// - /// Setting [`Arg::requires(name)`] requires that the argument be used at runtime if the - /// defining argument is used. If the defining argument isn't used, the other argument isn't - /// required - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use cfg, so input wasn't required - /// ``` - /// - /// Setting [`Arg::requires(name)`] and *not* supplying that argument is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - pub fn requires(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.requires { - vec.push((None, name)); - } else { - let mut vec = vec![]; - vec.push((None, name)); - self.b.requires = Some(vec); - } - self - } - - /// Allows a conditional requirement. The requirement will only become valid if this arg's value - /// equals `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// requires_if: - /// - [val, arg] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .requires_if("val", "arg") - /// # ; - /// ``` - /// - /// Setting [`Arg::requires_if(val, arg)`] requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument is anything other than - /// `val`, the other argument isn't required. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_if("my.cfg", "other") - /// .long("config")) - /// .arg(Arg::with_name("other")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "some.cfg" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --config=my.cfg, so other wasn't required - /// ``` - /// - /// Setting [`Arg::requires_if(val, arg)`] and setting the value to `val` but *not* supplying - /// `arg` is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_if("my.cfg", "input") - /// .long("config")) - /// .arg(Arg::with_name("input")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "my.cfg" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - pub fn requires_if(mut self, val: &'b str, arg: &'a str) -> Self { - if let Some(ref mut vec) = self.b.requires { - vec.push((Some(val), arg)); - } else { - self.b.requires = Some(vec![(Some(val), arg)]); - } - self - } - - /// Allows multiple conditional requirements. The requirement will only become valid if this arg's value - /// equals `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// requires_if: - /// - [val, arg] - /// - [val2, arg2] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .requires_ifs(&[ - /// ("val", "arg"), - /// ("other_val", "arg2"), - /// ]) - /// # ; - /// ``` - /// - /// Setting [`Arg::requires_ifs(&["val", "arg"])`] requires that the `arg` be used at runtime if the - /// defining argument's value is equal to `val`. If the defining argument's value is anything other - /// than `val`, `arg` isn't required. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_ifs(&[ - /// ("special.conf", "opt"), - /// ("other.conf", "other"), - /// ]) - /// .long("config")) - /// .arg(Arg::with_name("opt") - /// .long("option") - /// .takes_value(true)) - /// .arg(Arg::with_name("other")) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "special.conf" - /// ]); - /// - /// assert!(res.is_err()); // We used --config=special.conf so --option <val> is required - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - pub fn requires_ifs(mut self, ifs: &[(&'b str, &'a str)]) -> Self { - if let Some(ref mut vec) = self.b.requires { - for &(val, arg) in ifs { - vec.push((Some(val), arg)); - } - } else { - let mut vec = vec![]; - for &(val, arg) in ifs { - vec.push((Some(val), arg)); - } - self.b.requires = Some(vec); - } - self - } - - /// Allows specifying that an argument is [required] conditionally. The requirement will only - /// become valid if the specified `arg`'s value equals `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// required_if: - /// - [arg, val] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_if("other_arg", "value") - /// # ; - /// ``` - /// - /// Setting [`Arg::required_if(arg, val)`] makes this arg required if the `arg` is used at - /// runtime and it's value is equal to `val`. If the `arg`'s value is anything other than `val`, - /// this argument isn't required. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .required_if("other", "special") - /// .long("config")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--other", "not-special" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --other=special, so "cfg" wasn't required - /// ``` - /// - /// Setting [`Arg::required_if(arg, val)`] and having `arg` used with a value of `val` but *not* - /// using this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .required_if("other", "special") - /// .long("config")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "--other", "special" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [required]: ./struct.Arg.html#method.required - pub fn required_if(mut self, arg: &'a str, val: &'b str) -> Self { - if let Some(ref mut vec) = self.r_ifs { - vec.push((arg, val)); - } else { - self.r_ifs = Some(vec![(arg, val)]); - } - self - } - - /// Allows specifying that an argument is [required] based on multiple conditions. The - /// conditions are set up in a `(arg, val)` style tuple. The requirement will only become valid - /// if one of the specified `arg`'s value equals it's corresponding `val`. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// required_if: - /// - [arg, val] - /// - [arg2, val2] - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .required_ifs(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// # ; - /// ``` - /// - /// Setting [`Arg::required_ifs(&[(arg, val)])`] makes this arg required if any of the `arg`s - /// are used at runtime and it's corresponding value is equal to `val`. If the `arg`'s value is - /// anything other than `val`, this argument isn't required. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_ifs(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::with_name("option") - /// .takes_value(true) - /// .long("option")) - /// .get_matches_from_safe(vec![ - /// "prog", "--option", "other" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use --option=spec, or --extra=val so "cfg" isn't required - /// ``` - /// - /// Setting [`Arg::required_ifs(&[(arg, val)])`] and having any of the `arg`s used with it's - /// value of `val` but *not* using this arg is an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .required_ifs(&[ - /// ("extra", "val"), - /// ("option", "spec") - /// ]) - /// .takes_value(true) - /// .long("config")) - /// .arg(Arg::with_name("extra") - /// .takes_value(true) - /// .long("extra")) - /// .arg(Arg::with_name("option") - /// .takes_value(true) - /// .long("option")) - /// .get_matches_from_safe(vec![ - /// "prog", "--option", "spec" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`Arg::requires(name)`]: ./struct.Arg.html#method.requires - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [required]: ./struct.Arg.html#method.required - pub fn required_ifs(mut self, ifs: &[(&'a str, &'b str)]) -> Self { - if let Some(ref mut vec) = self.r_ifs { - for r_if in ifs { - vec.push((r_if.0, r_if.1)); - } - } else { - let mut vec = vec![]; - for r_if in ifs { - vec.push((r_if.0, r_if.1)); - } - self.r_ifs = Some(vec); - } - self - } - - /// Sets multiple arguments by names that are required when this one is present I.e. when - /// using this argument, the following arguments *must* be present. - /// - /// **NOTE:** [Conflicting] rules and [override] rules take precedence over being required - /// by default. - /// - /// # Examples - /// - /// ```rust - /// # use clap::Arg; - /// Arg::with_name("config") - /// .requires_all(&["input", "output"]) - /// # ; - /// ``` - /// - /// Setting [`Arg::requires_all(&[arg, arg2])`] requires that all the arguments be used at - /// runtime if the defining argument is used. If the defining argument isn't used, the other - /// argument isn't required - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires("input") - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .arg(Arg::with_name("output") - /// .index(2)) - /// .get_matches_from_safe(vec![ - /// "prog" - /// ]); - /// - /// assert!(res.is_ok()); // We didn't use cfg, so input and output weren't required - /// ``` - /// - /// Setting [`Arg::requires_all(&[arg, arg2])`] and *not* supplying all the arguments is an - /// error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .takes_value(true) - /// .requires_all(&["input", "output"]) - /// .long("config")) - /// .arg(Arg::with_name("input") - /// .index(1)) - /// .arg(Arg::with_name("output") - /// .index(2)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config", "file.conf", "in.txt" - /// ]); - /// - /// assert!(res.is_err()); - /// // We didn't use output - /// assert_eq!(res.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [Conflicting]: ./struct.Arg.html#method.conflicts_with - /// [override]: ./struct.Arg.html#method.overrides_with - /// [`Arg::requires_all(&[arg, arg2])`]: ./struct.Arg.html#method.requires_all - pub fn requires_all(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.requires { - for s in names { - vec.push((None, s)); - } - } else { - let mut vec = vec![]; - for s in names { - vec.push((None, *s)); - } - self.b.requires = Some(vec); - } - self - } - - /// Specifies that the argument takes a value at run time. - /// - /// **NOTE:** values for arguments may be specified in any of the following methods - /// - /// * Using a space such as `-o value` or `--option value` - /// * Using an equals and no space such as `-o=value` or `--option=value` - /// * Use a short and no space such as `-ovalue` - /// - /// **NOTE:** By default, args which allow [multiple values] are delimited by commas, meaning - /// `--option=val1,val2,val3` is three values for the `--option` argument. If you wish to - /// change the delimiter to another character you can use [`Arg::value_delimiter(char)`], - /// alternatively you can turn delimiting values **OFF** by using [`Arg::use_delimiter(false)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .takes_value(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// [`Arg::value_delimiter(char)`]: ./struct.Arg.html#method.value_delimiter - /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter - /// [multiple values]: ./struct.Arg.html#method.multiple - pub fn takes_value(self, tv: bool) -> Self { - if tv { - self.set(ArgSettings::TakesValue) - } else { - self.unset(ArgSettings::TakesValue) - } - } - - /// Specifies if the possible values of an argument should be displayed in the help text or - /// not. Defaults to `false` (i.e. show possible values) - /// - /// This is useful for args with many values, or ones which are explained elsewhere in the - /// help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .hide_possible_values(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .possible_values(&["fast", "slow"]) - /// .takes_value(true) - /// .hide_possible_values(true)); - /// - /// ``` - /// - /// If we were to run the above program with `--help` the `[values: fast, slow]` portion of - /// the help text would be omitted. - pub fn hide_possible_values(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HidePossibleValues) - } else { - self.unset(ArgSettings::HidePossibleValues) - } - } - - /// Specifies if the default value of an argument should be displayed in the help text or - /// not. Defaults to `false` (i.e. show default value) - /// - /// This is useful when default behavior of an arg is explained elsewhere in the help text. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .hide_default_value(true) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("connect") - /// .arg(Arg::with_name("host") - /// .long("host") - /// .default_value("localhost") - /// .hide_default_value(true)); - /// - /// ``` - /// - /// If we were to run the above program with `--help` the `[default: localhost]` portion of - /// the help text would be omitted. - pub fn hide_default_value(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HideDefaultValue) - } else { - self.unset(ArgSettings::HideDefaultValue) - } - } - - /// Specifies the index of a positional argument **starting at** 1. - /// - /// **NOTE:** The index refers to position according to **other positional argument**. It does - /// not define position in the argument list as a whole. - /// - /// **NOTE:** If no [`Arg::short`], or [`Arg::long`] have been defined, you can optionally - /// leave off the `index` method, and the index will be assigned in order of evaluation. - /// Utilizing the `index` method allows for setting indexes out of order - /// - /// **NOTE:** When utilized with [`Arg::multiple(true)`], only the **last** positional argument - /// may be defined as multiple (i.e. with the highest index) - /// - /// # Panics - /// - /// Although not in this method directly, [`App`] will [`panic!`] if indexes are skipped (such - /// as defining `index(1)` and `index(3)` but not `index(2)`, or a positional argument is - /// defined as multiple and is not the highest index - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("config") - /// .index(1) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .index(1)) - /// .arg(Arg::with_name("debug") - /// .long("debug")) - /// .get_matches_from(vec![ - /// "prog", "--debug", "fast" - /// ]); - /// - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); // notice index(1) means "first positional" - /// // *not* first argument - /// ``` - /// [`Arg::short`]: ./struct.Arg.html#method.short - /// [`Arg::long`]: ./struct.Arg.html#method.long - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`App`]: ./struct.App.html - /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html - pub fn index(mut self, idx: u64) -> Self { - self.index = Some(idx); - self - } - - /// Specifies that the argument may appear more than once. For flags, this results - /// in the number of occurrences of the flag being recorded. For example `-ddd` or `-d -d -d` - /// would count as three occurrences. For options there is a distinct difference in multiple - /// occurrences vs multiple values. - /// - /// For example, `--opt val1 val2` is one occurrence, but two values. Whereas - /// `--opt val1 --opt val2` is two occurrences. - /// - /// **WARNING:** - /// - /// Setting `multiple(true)` for an [option] with no other details, allows multiple values - /// **and** multiple occurrences because it isn't possible to have more occurrences than values - /// for options. Because multiple values are allowed, `--option val1 val2 val3` is perfectly - /// valid, be careful when designing a CLI where positional arguments are expected after a - /// option which accepts multiple values, as `clap` will continue parsing *values* until it - /// reaches the max or specific number of values defined, or another flag or option. - /// - /// **Pro Tip**: - /// - /// It's possible to define an option which allows multiple occurrences, but only one value per - /// occurrence. To do this use [`Arg::number_of_values(1)`] in coordination with - /// [`Arg::multiple(true)`]. - /// - /// **WARNING:** - /// - /// When using args with `multiple(true)` on [options] or [positionals] (i.e. those args that - /// accept values) and [subcommands], one needs to consider the possibility of an argument value - /// being the same as a valid subcommand. By default `clap` will parse the argument in question - /// as a value *only if* a value is possible at that moment. Otherwise it will be parsed as a - /// subcommand. In effect, this means using `multiple(true)` with no additional parameters and - /// a possible value that coincides with a subcommand name, the subcommand cannot be called - /// unless another argument is passed first. - /// - /// As an example, consider a CLI with an option `--ui-paths=<paths>...` and subcommand `signer` - /// - /// The following would be parsed as values to `--ui-paths`. - /// - /// ```notrust - /// $ program --ui-paths path1 path2 signer - /// ``` - /// - /// This is because `--ui-paths` accepts multiple values. `clap` will continue parsing values - /// until another argument is reached and it knows `--ui-paths` is done. - /// - /// By adding additional parameters to `--ui-paths` we can solve this issue. Consider adding - /// [`Arg::number_of_values(1)`] as discussed above. The following are all valid, and `signer` - /// is parsed as both a subcommand and a value in the second case. - /// - /// ```notrust - /// $ program --ui-paths path1 signer - /// $ program --ui-paths path1 --ui-paths signer signer - /// ``` - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .short("d") - /// .multiple(true) - /// # ; - /// ``` - /// An example with flags - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("verbose") - /// .multiple(true) - /// .short("v")) - /// .get_matches_from(vec![ - /// "prog", "-v", "-v", "-v" // note, -vvv would have same result - /// ]); - /// - /// assert!(m.is_present("verbose")); - /// assert_eq!(m.occurrences_of("verbose"), 3); - /// ``` - /// - /// An example with options - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .short("F")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(m.is_present("file")); - /// assert_eq!(m.occurrences_of("file"), 1); // notice only one occurrence - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// This is functionally equivalent to the example above - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .short("F")) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3" - /// ]); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// - /// assert!(m.is_present("file")); - /// assert_eq!(m.occurrences_of("file"), 3); // Notice 3 occurrences - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// - /// A common mistake is to define an option which allows multiples, and a positional argument - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .short("F")) - /// .arg(Arg::with_name("word") - /// .index(1)) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// - /// assert!(m.is_present("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3", "word"]); // wait...what?! - /// assert!(!m.is_present("word")); // but we clearly used word! - /// ``` - /// The problem is clap doesn't know when to stop parsing values for "files". This is further - /// compounded by if we'd said `word -F file1 file2` it would have worked fine, so it would - /// appear to only fail sometimes...not good! - /// - /// A solution for the example above is to specify that `-F` only accepts one value, but is - /// allowed to appear multiple times - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .number_of_values(1) - /// .short("F")) - /// .arg(Arg::with_name("word") - /// .index(1)) - /// .get_matches_from(vec![ - /// "prog", "-F", "file1", "-F", "file2", "-F", "file3", "word" - /// ]); - /// - /// assert!(m.is_present("file")); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// assert!(m.is_present("word")); - /// assert_eq!(m.value_of("word"), Some("word")); - /// ``` - /// As a final example, notice if we define [`Arg::number_of_values(1)`] and try to run the - /// problem example above, it would have been a runtime error with a pretty message to the - /// user :) - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .multiple(true) - /// .takes_value(true) - /// .number_of_values(1) - /// .short("F")) - /// .arg(Arg::with_name("word") - /// .index(1)) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1", "file2", "file3", "word" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - /// [option]: ./struct.Arg.html#method.takes_value - /// [options]: ./struct.Arg.html#method.takes_value - /// [subcommands]: ./struct.SubCommand.html - /// [positionals]: ./struct.Arg.html#method.index - /// [`Arg::number_of_values(1)`]: ./struct.Arg.html#method.number_of_values - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn multiple(self, multi: bool) -> Self { - if multi { - self.set(ArgSettings::Multiple) - } else { - self.unset(ArgSettings::Multiple) - } - } - - /// Specifies a value that *stops* parsing multiple values of a give argument. By default when - /// one sets [`multiple(true)`] on an argument, clap will continue parsing values for that - /// argument until it reaches another valid argument, or one of the other more specific settings - /// for multiple values is used (such as [`min_values`], [`max_values`] or - /// [`number_of_values`]). - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// **NOTE:** When the terminator is passed in on the command line, it is **not** stored as one - /// of the values - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("vals") - /// .takes_value(true) - /// .multiple(true) - /// .value_terminator(";") - /// # ; - /// ``` - /// The following example uses two arguments, a sequence of commands, and the location in which - /// to perform them - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cmds") - /// .multiple(true) - /// .allow_hyphen_values(true) - /// .value_terminator(";")) - /// .arg(Arg::with_name("location")) - /// .get_matches_from(vec![ - /// "prog", "find", "-type", "f", "-name", "special", ";", "/home/clap" - /// ]); - /// let cmds: Vec<_> = m.values_of("cmds").unwrap().collect(); - /// assert_eq!(&cmds, &["find", "-type", "f", "-name", "special"]); - /// assert_eq!(m.value_of("location"), Some("/home/clap")); - /// ``` - /// [options]: ./struct.Arg.html#method.takes_value - /// [positional arguments]: ./struct.Arg.html#method.index - /// [`multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`min_values`]: ./struct.Arg.html#method.min_values - /// [`number_of_values`]: ./struct.Arg.html#method.number_of_values - /// [`max_values`]: ./struct.Arg.html#method.max_values - pub fn value_terminator(mut self, term: &'b str) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.terminator = Some(term); - self - } - - /// Specifies that an argument can be matched to all child [`SubCommand`]s. - /// - /// **NOTE:** Global arguments *only* propagate down, **not** up (to parent commands), however - /// their values once a user uses them will be propagated back up to parents. In effect, this - /// means one should *define* all global arguments at the top level, however it doesn't matter - /// where the user *uses* the global argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .short("d") - /// .global(true) - /// # ; - /// ``` - /// - /// For example, assume an application with two subcommands, and you'd like to define a - /// `--verbose` flag that can be called on any of the subcommands and parent, but you don't - /// want to clutter the source with three duplicate [`Arg`] definitions. - /// - /// ```rust - /// # use clap::{App, Arg, SubCommand}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("verb") - /// .long("verbose") - /// .short("v") - /// .global(true)) - /// .subcommand(SubCommand::with_name("test")) - /// .subcommand(SubCommand::with_name("do-stuff")) - /// .get_matches_from(vec![ - /// "prog", "do-stuff", "--verbose" - /// ]); - /// - /// assert_eq!(m.subcommand_name(), Some("do-stuff")); - /// let sub_m = m.subcommand_matches("do-stuff").unwrap(); - /// assert!(sub_m.is_present("verb")); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [required]: ./struct.Arg.html#method.required - /// [`ArgMatches`]: ./struct.ArgMatches.html - /// [`ArgMatches::is_present("flag")`]: ./struct.ArgMatches.html#method.is_present - /// [`Arg`]: ./struct.Arg.html - pub fn global(self, g: bool) -> Self { - if g { - self.set(ArgSettings::Global) - } else { - self.unset(ArgSettings::Global) - } - } - - /// Allows an argument to accept explicitly empty values. An empty value must be specified at - /// the command line with an explicit `""`, or `''` - /// - /// **NOTE:** Defaults to `true` (Explicitly empty values are allowed) - /// - /// **NOTE:** Implicitly sets [`Arg::takes_value(true)`] when set to `false` - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .long("file") - /// .empty_values(false) - /// # ; - /// ``` - /// The default is to allow empty values, such as `--option ""` would be an empty value. But - /// we can change to make empty values become an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .short("v") - /// .empty_values(false)) - /// .get_matches_from_safe(vec![ - /// "prog", "--config=" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - pub fn empty_values(mut self, ev: bool) -> Self { - if ev { - self.set(ArgSettings::EmptyValues) - } else { - self = self.set(ArgSettings::TakesValue); - self.unset(ArgSettings::EmptyValues) - } - } - - /// Hides an argument from help message output. - /// - /// **NOTE:** Implicitly sets [`Arg::hidden_short_help(true)`] and [`Arg::hidden_long_help(true)`] - /// when set to true - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .hidden(true) - /// # ; - /// ``` - /// Setting `hidden(true)` will hide the argument when displaying help text - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// [`Arg::hidden_short_help(true)`]: ./struct.Arg.html#method.hidden_short_help - /// [`Arg::hidden_long_help(true)`]: ./struct.Arg.html#method.hidden_long_help - pub fn hidden(self, h: bool) -> Self { - if h { - self.set(ArgSettings::Hidden) - } else { - self.unset(ArgSettings::Hidden) - } - } - - /// Specifies a list of possible values for this argument. At runtime, `clap` verifies that - /// only one of the specified values was used, or fails with an error message. - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("mode") - /// .takes_value(true) - /// .possible_values(&["fast", "slow", "medium"]) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_values(&["fast", "slow", "medium"])) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// - /// The next example shows a failed parse from using a value which wasn't defined as one of the - /// possible values. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_values(&["fast", "slow", "medium"])) - /// .get_matches_from_safe(vec![ - /// "prog", "--mode", "wrong" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); - /// ``` - /// [options]: ./struct.Arg.html#method.takes_value - /// [positional arguments]: ./struct.Arg.html#method.index - pub fn possible_values(mut self, names: &[&'b str]) -> Self { - if let Some(ref mut vec) = self.v.possible_vals { - for s in names { - vec.push(s); - } - } else { - self.v.possible_vals = Some(names.iter().map(|s| *s).collect::<Vec<_>>()); - } - self - } - - /// Specifies a possible value for this argument, one at a time. At runtime, `clap` verifies - /// that only one of the specified values was used, or fails with error message. - /// - /// **NOTE:** This setting only applies to [options] and [positional arguments] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("mode") - /// .takes_value(true) - /// .possible_value("fast") - /// .possible_value("slow") - /// .possible_value("medium") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_value("fast") - /// .possible_value("slow") - /// .possible_value("medium")) - /// .get_matches_from(vec![ - /// "prog", "--mode", "fast" - /// ]); - /// assert!(m.is_present("mode")); - /// assert_eq!(m.value_of("mode"), Some("fast")); - /// ``` - /// - /// The next example shows a failed parse from using a value which wasn't defined as one of the - /// possible values. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("mode") - /// .long("mode") - /// .takes_value(true) - /// .possible_value("fast") - /// .possible_value("slow") - /// .possible_value("medium")) - /// .get_matches_from_safe(vec![ - /// "prog", "--mode", "wrong" - /// ]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::InvalidValue); - /// ``` - /// [options]: ./struct.Arg.html#method.takes_value - /// [positional arguments]: ./struct.Arg.html#method.index - pub fn possible_value(mut self, name: &'b str) -> Self { - if let Some(ref mut vec) = self.v.possible_vals { - vec.push(name); - } else { - self.v.possible_vals = Some(vec![name]); - } - self - } - - /// When used with [`Arg::possible_values`] it allows the argument value to pass validation even if - /// the case differs from that of the specified `possible_value`. - /// - /// **Pro Tip:** Use this setting with [`arg_enum!`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// # use std::ascii::AsciiExt; - /// let m = App::new("pv") - /// .arg(Arg::with_name("option") - /// .long("--option") - /// .takes_value(true) - /// .possible_value("test123") - /// .case_insensitive(true)) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", - /// ]); - /// - /// assert!(m.value_of("option").unwrap().eq_ignore_ascii_case("test123")); - /// ``` - /// - /// This setting also works when multiple values can be defined: - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("pv") - /// .arg(Arg::with_name("option") - /// .short("-o") - /// .long("--option") - /// .takes_value(true) - /// .possible_value("test123") - /// .possible_value("test321") - /// .multiple(true) - /// .case_insensitive(true)) - /// .get_matches_from(vec![ - /// "pv", "--option", "TeSt123", "teST123", "tESt321" - /// ]); - /// - /// let matched_vals = m.values_of("option").unwrap().collect::<Vec<_>>(); - /// assert_eq!(&*matched_vals, &["TeSt123", "teST123", "tESt321"]); - /// ``` - /// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.possible_values - /// [`arg_enum!`]: ./macro.arg_enum.html - pub fn case_insensitive(self, ci: bool) -> Self { - if ci { - self.set(ArgSettings::CaseInsensitive) - } else { - self.unset(ArgSettings::CaseInsensitive) - } - } - - /// Specifies the name of the [`ArgGroup`] the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .long("debug") - /// .group("mode") - /// # ; - /// ``` - /// - /// Multiple arguments can be a member of a single group and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .long("debug") - /// .group("mode")) - /// .arg(Arg::with_name("verbose") - /// .long("verbose") - /// .group("mode")) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.is_present("mode")); - /// ``` - /// [`ArgGroup`]: ./struct.ArgGroup.html - pub fn group(mut self, name: &'a str) -> Self { - if let Some(ref mut vec) = self.b.groups { - vec.push(name); - } else { - self.b.groups = Some(vec![name]); - } - self - } - - /// Specifies the names of multiple [`ArgGroup`]'s the argument belongs to. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .long("debug") - /// .groups(&["mode", "verbosity"]) - /// # ; - /// ``` - /// - /// Arguments can be members of multiple groups and then the group checked as if it - /// was one of said arguments. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .long("debug") - /// .groups(&["mode", "verbosity"])) - /// .arg(Arg::with_name("verbose") - /// .long("verbose") - /// .groups(&["mode", "verbosity"])) - /// .get_matches_from(vec![ - /// "prog", "--debug" - /// ]); - /// assert!(m.is_present("mode")); - /// assert!(m.is_present("verbosity")); - /// ``` - /// [`ArgGroup`]: ./struct.ArgGroup.html - pub fn groups(mut self, names: &[&'a str]) -> Self { - if let Some(ref mut vec) = self.b.groups { - for s in names { - vec.push(s); - } - } else { - self.b.groups = Some(names.into_iter().map(|s| *s).collect::<Vec<_>>()); - } - self - } - - /// Specifies how many values are required to satisfy this argument. For example, if you had a - /// `-f <file>` argument where you wanted exactly 3 'files' you would set - /// `.number_of_values(3)`, and this argument wouldn't be satisfied unless the user provided - /// 3 and only 3 values. - /// - /// **NOTE:** Does *not* require [`Arg::multiple(true)`] to be set. Setting - /// [`Arg::multiple(true)`] would allow `-f <file> <file> <file> -f <file> <file> <file>` where - /// as *not* setting [`Arg::multiple(true)`] would only allow one occurrence of this argument. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .short("f") - /// .number_of_values(3) - /// # ; - /// ``` - /// - /// Not supplying the correct number of values is an error - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .number_of_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::WrongNumberOfValues); - /// ``` - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn number_of_values(mut self, qty: u64) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.num_vals = Some(qty); - self - } - - /// Allows one to perform a custom validation on the argument value. You provide a closure - /// which accepts a [`String`] value, and return a [`Result`] where the [`Err(String)`] is a - /// message displayed to the user. - /// - /// **NOTE:** The error message does *not* need to contain the `error:` portion, only the - /// message as all errors will appear as - /// `error: Invalid value for '<arg>': <YOUR MESSAGE>` where `<arg>` is replaced by the actual - /// arg, and `<YOUR MESSAGE>` is the `String` you return as the error. - /// - /// **NOTE:** There is a small performance hit for using validators, as they are implemented - /// with [`Rc`] pointers. And the value to be checked will be allocated an extra time in order - /// to to be passed to the closure. This performance hit is extremely minimal in the grand - /// scheme of things. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// fn has_at(v: String) -> Result<(), String> { - /// if v.contains("@") { return Ok(()); } - /// Err(String::from("The value did not contain the required @ sigil")) - /// } - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .index(1) - /// .validator(has_at)) - /// .get_matches_from_safe(vec![ - /// "prog", "some@file" - /// ]); - /// assert!(res.is_ok()); - /// assert_eq!(res.unwrap().value_of("file"), Some("some@file")); - /// ``` - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html - /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err - /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html - pub fn validator<F>(mut self, f: F) -> Self - where - F: Fn(String) -> Result<(), String> + 'static, - { - self.v.validator = Some(Rc::new(f)); - self - } - - /// Works identically to Validator but is intended to be used with values that could - /// contain non UTF-8 formatted strings. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```rust")] - /// # use clap::{App, Arg}; - /// # use std::ffi::{OsStr, OsString}; - /// # use std::os::unix::ffi::OsStrExt; - /// fn has_ampersand(v: &OsStr) -> Result<(), OsString> { - /// if v.as_bytes().iter().any(|b| *b == b'&') { return Ok(()); } - /// Err(OsString::from("The value did not contain the required & sigil")) - /// } - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .index(1) - /// .validator_os(has_ampersand)) - /// .get_matches_from_safe(vec![ - /// "prog", "Fish & chips" - /// ]); - /// assert!(res.is_ok()); - /// assert_eq!(res.unwrap().value_of("file"), Some("Fish & chips")); - /// ``` - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html - /// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html - /// [`Err(String)`]: https://doc.rust-lang.org/std/result/enum.Result.html#variant.Err - /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html - pub fn validator_os<F>(mut self, f: F) -> Self - where - F: Fn(&OsStr) -> Result<(), OsString> + 'static, - { - self.v.validator_os = Some(Rc::new(f)); - self - } - - /// Specifies the *maximum* number of values are for this argument. For example, if you had a - /// `-f <file>` argument where you wanted up to 3 'files' you would set `.max_values(3)`, and - /// this argument would be satisfied if the user provided, 1, 2, or 3 values. - /// - /// **NOTE:** This does *not* implicitly set [`Arg::multiple(true)`]. This is because - /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single - /// occurrence with multiple values. For positional arguments this **does** set - /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple - /// occurrences and multiple values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .short("f") - /// .max_values(3) - /// # ; - /// ``` - /// - /// Supplying less than the maximum number of values is allowed - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .max_values(3) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1", "file2" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2"]); - /// ``` - /// - /// Supplying more than the maximum number of values is an error - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .max_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooManyValues); - /// ``` - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn max_values(mut self, qty: u64) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.max_vals = Some(qty); - self - } - - /// Specifies the *minimum* number of values for this argument. For example, if you had a - /// `-f <file>` argument where you wanted at least 2 'files' you would set - /// `.min_values(2)`, and this argument would be satisfied if the user provided, 2 or more - /// values. - /// - /// **NOTE:** This does not implicitly set [`Arg::multiple(true)`]. This is because - /// `-o val -o val` is multiple occurrences but a single value and `-o val1 val2` is a single - /// occurrence with multiple values. For positional arguments this **does** set - /// [`Arg::multiple(true)`] because there is no way to determine the difference between multiple - /// occurrences and multiple values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("file") - /// .short("f") - /// .min_values(3) - /// # ; - /// ``` - /// - /// Supplying more than the minimum number of values is allowed - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .min_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1", "file2", "file3" - /// ]); - /// - /// assert!(res.is_ok()); - /// let m = res.unwrap(); - /// let files: Vec<_> = m.values_of("file").unwrap().collect(); - /// assert_eq!(files, ["file1", "file2", "file3"]); - /// ``` - /// - /// Supplying less than the minimum number of values is an error - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("file") - /// .takes_value(true) - /// .min_values(2) - /// .short("F")) - /// .get_matches_from_safe(vec![ - /// "prog", "-F", "file1" - /// ]); - /// - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::TooFewValues); - /// ``` - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn min_values(mut self, qty: u64) -> Self { - self.v.min_vals = Some(qty); - self.set(ArgSettings::TakesValue) - } - - /// Specifies whether or not an argument should allow grouping of multiple values via a - /// delimiter. I.e. should `--option=val1,val2,val3` be parsed as three values (`val1`, `val2`, - /// and `val3`) or as a single value (`val1,val2,val3`). Defaults to using `,` (comma) as the - /// value delimiter for all arguments that accept values (options and positional arguments) - /// - /// **NOTE:** The default is `false`. When set to `true` the default [`Arg::value_delimiter`] - /// is the comma `,`. - /// - /// # Examples - /// - /// The following example shows the default behavior. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let delims = App::new("prog") - /// .arg(Arg::with_name("option") - /// .long("option") - /// .use_delimiter(true) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--option=val1,val2,val3", - /// ]); - /// - /// assert!(delims.is_present("option")); - /// assert_eq!(delims.occurrences_of("option"), 1); - /// assert_eq!(delims.values_of("option").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); - /// ``` - /// The next example shows the difference when turning delimiters off. This is the default - /// behavior - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let nodelims = App::new("prog") - /// .arg(Arg::with_name("option") - /// .long("option") - /// .use_delimiter(false) - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "prog", "--option=val1,val2,val3", - /// ]); - /// - /// assert!(nodelims.is_present("option")); - /// assert_eq!(nodelims.occurrences_of("option"), 1); - /// assert_eq!(nodelims.value_of("option").unwrap(), "val1,val2,val3"); - /// ``` - /// [`Arg::value_delimiter`]: ./struct.Arg.html#method.value_delimiter - pub fn use_delimiter(mut self, d: bool) -> Self { - if d { - if self.v.val_delim.is_none() { - self.v.val_delim = Some(','); - } - self.setb(ArgSettings::TakesValue); - self.setb(ArgSettings::UseValueDelimiter); - self.unset(ArgSettings::ValueDelimiterNotSet) - } else { - self.v.val_delim = None; - self.unsetb(ArgSettings::UseValueDelimiter); - self.unset(ArgSettings::ValueDelimiterNotSet) - } - } - - /// Specifies that *multiple values* may only be set using the delimiter. This means if an - /// if an option is encountered, and no delimiter is found, it automatically assumed that no - /// additional values for that option follow. This is unlike the default, where it is generally - /// assumed that more values will follow regardless of whether or not a delimiter is used. - /// - /// **NOTE:** The default is `false`. - /// - /// **NOTE:** Setting this to true implies [`Arg::use_delimiter(true)`] - /// - /// **NOTE:** It's a good idea to inform the user that use of a delimiter is required, either - /// through help text or other means. - /// - /// # Examples - /// - /// These examples demonstrate what happens when `require_delimiter(true)` is used. Notice - /// everything works in this first example, as we use a delimiter, as expected. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let delims = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .short("o") - /// .takes_value(true) - /// .multiple(true) - /// .require_delimiter(true)) - /// .get_matches_from(vec![ - /// "prog", "-o", "val1,val2,val3", - /// ]); - /// - /// assert!(delims.is_present("opt")); - /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); - /// ``` - /// In this next example, we will *not* use a delimiter. Notice it's now an error. - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .short("o") - /// .takes_value(true) - /// .multiple(true) - /// .require_delimiter(true)) - /// .get_matches_from_safe(vec![ - /// "prog", "-o", "val1", "val2", "val3", - /// ]); - /// - /// assert!(res.is_err()); - /// let err = res.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::UnknownArgument); - /// ``` - /// What's happening is `-o` is getting `val1`, and because delimiters are required yet none - /// were present, it stops parsing `-o`. At this point it reaches `val2` and because no - /// positional arguments have been defined, it's an error of an unexpected argument. - /// - /// In this final example, we contrast the above with `clap`'s default behavior where the above - /// is *not* an error. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let delims = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec![ - /// "prog", "-o", "val1", "val2", "val3", - /// ]); - /// - /// assert!(delims.is_present("opt")); - /// assert_eq!(delims.values_of("opt").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]); - /// ``` - /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter - pub fn require_delimiter(mut self, d: bool) -> Self { - if d { - self = self.use_delimiter(true); - self.unsetb(ArgSettings::ValueDelimiterNotSet); - self.setb(ArgSettings::UseValueDelimiter); - self.set(ArgSettings::RequireDelimiter) - } else { - self = self.use_delimiter(false); - self.unsetb(ArgSettings::UseValueDelimiter); - self.unset(ArgSettings::RequireDelimiter) - } - } - - /// Specifies the separator to use when values are clumped together, defaults to `,` (comma). - /// - /// **NOTE:** implicitly sets [`Arg::use_delimiter(true)`] - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("config") - /// .short("c") - /// .long("config") - /// .value_delimiter(";")) - /// .get_matches_from(vec![ - /// "prog", "--config=val1;val2;val3" - /// ]); - /// - /// assert_eq!(m.values_of("config").unwrap().collect::<Vec<_>>(), ["val1", "val2", "val3"]) - /// ``` - /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - pub fn value_delimiter(mut self, d: &str) -> Self { - self.unsetb(ArgSettings::ValueDelimiterNotSet); - self.setb(ArgSettings::TakesValue); - self.setb(ArgSettings::UseValueDelimiter); - self.v.val_delim = Some( - d.chars() - .nth(0) - .expect("Failed to get value_delimiter from arg"), - ); - self - } - - /// Specify multiple names for values of option arguments. These names are cosmetic only, used - /// for help and usage strings only. The names are **not** used to access arguments. The values - /// of the arguments are accessed in numeric order (i.e. if you specify two names `one` and - /// `two` `one` will be the first matched value, `two` will be the second). - /// - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **Pro Tip:** It may help to use [`Arg::next_line_help(true)`] if there are long, or - /// multiple value names in order to not throw off the help text alignment of all options. - /// - /// **NOTE:** This implicitly sets [`Arg::number_of_values`] if the number of value names is - /// greater than one. I.e. be aware that the number of "names" you set for the values, will be - /// the *exact* number of values required to satisfy this argument - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// **NOTE:** Does *not* require or imply [`Arg::multiple(true)`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("speed") - /// .short("s") - /// .value_names(&["fast", "slow"]) - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("io") - /// .long("io-files") - /// .value_names(&["INFILE", "OUTFILE"])) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// Running the above program produces the following output - /// - /// ```notrust - /// valnames - /// - /// USAGE: - /// valnames [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// --io-files <INFILE> <OUTFILE> Some help text - /// ``` - /// [`Arg::next_line_help(true)`]: ./struct.Arg.html#method.next_line_help - /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - pub fn value_names(mut self, names: &[&'b str]) -> Self { - self.setb(ArgSettings::TakesValue); - if self.is_set(ArgSettings::ValueDelimiterNotSet) { - self.unsetb(ArgSettings::ValueDelimiterNotSet); - self.setb(ArgSettings::UseValueDelimiter); - } - if let Some(ref mut vals) = self.v.val_names { - let mut l = vals.len(); - for s in names { - vals.insert(l, s); - l += 1; - } - } else { - let mut vm = VecMap::new(); - for (i, n) in names.iter().enumerate() { - vm.insert(i, *n); - } - self.v.val_names = Some(vm); - } - self - } - - /// Specifies the name for value of [option] or [positional] arguments inside of help - /// documentation. This name is cosmetic only, the name is **not** used to access arguments. - /// This setting can be very helpful when describing the type of input the user should be - /// using, such as `FILE`, `INTERFACE`, etc. Although not required, it's somewhat convention to - /// use all capital letters for the value name. - /// - /// **NOTE:** implicitly sets [`Arg::takes_value(true)`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("cfg") - /// .long("config") - /// .value_name("FILE") - /// # ; - /// ``` - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("config") - /// .long("config") - /// .value_name("FILE")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// Running the above program produces the following output - /// - /// ```notrust - /// valnames - /// - /// USAGE: - /// valnames [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// --config <FILE> Some help text - /// ``` - /// [option]: ./struct.Arg.html#method.takes_value - /// [positional]: ./struct.Arg.html#method.index - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - pub fn value_name(mut self, name: &'b str) -> Self { - self.setb(ArgSettings::TakesValue); - if let Some(ref mut vals) = self.v.val_names { - let l = vals.len(); - vals.insert(l, name); - } else { - let mut vm = VecMap::new(); - vm.insert(0, name); - self.v.val_names = Some(vm); - } - self - } - - /// Specifies the value of the argument when *not* specified at runtime. - /// - /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] - /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. - /// - /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will - /// still return `true`. If you wish to determine whether the argument was used at runtime or - /// not, consider [`ArgMatches::occurrences_of`] which will return `0` if the argument was *not* - /// used at runtime. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value_if`] but slightly - /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg - /// at runtime. `Arg::default_value_if` however only takes affect when the user has not provided - /// a value at runtime **and** these other conditions are met as well. If you have set - /// `Arg::default_value` and `Arg::default_value_if`, and the user **did not** provide a this - /// arg at runtime, nor did were the conditions met for `Arg::default_value_if`, the - /// `Arg::default_value` will be applied. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// **NOTE:** This setting effectively disables `AppSettings::ArgRequiredElseHelp` if used in - /// conjunction as it ensures that some argument will always be present. - /// - /// # Examples - /// - /// First we use the default value without providing any value at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("opt"), Some("myval")); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 0); - /// ``` - /// - /// Next we provide a value at runtime to override the default. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .long("myopt") - /// .default_value("myval")) - /// .get_matches_from(vec![ - /// "prog", "--myopt=non_default" - /// ]); - /// - /// assert_eq!(m.value_of("opt"), Some("non_default")); - /// assert!(m.is_present("opt")); - /// assert_eq!(m.occurrences_of("opt"), 1); - /// ``` - /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of - /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present - /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if - pub fn default_value(self, val: &'a str) -> Self { - self.default_value_os(OsStr::from_bytes(val.as_bytes())) - } - - /// Provides a default value in the exact same manner as [`Arg::default_value`] - /// only using [`OsStr`]s instead. - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - pub fn default_value_os(mut self, val: &'a OsStr) -> Self { - self.setb(ArgSettings::TakesValue); - self.v.default_val = Some(val); - self - } - - /// Specifies the value of the argument if `arg` has been used at runtime. If `val` is set to - /// `None`, `arg` only needs to be present. If `val` is set to `"some-val"` then `arg` must be - /// present at runtime **and** have the value `val`. - /// - /// **NOTE:** This setting is perfectly compatible with [`Arg::default_value`] but slightly - /// different. `Arg::default_value` *only* takes affect when the user has not provided this arg - /// at runtime. This setting however only takes affect when the user has not provided a value at - /// runtime **and** these other conditions are met as well. If you have set `Arg::default_value` - /// and `Arg::default_value_if`, and the user **did not** provide a this arg at runtime, nor did - /// were the conditions met for `Arg::default_value_if`, the `Arg::default_value` will be - /// applied. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// **NOTE:** If using YAML the values should be laid out as follows (`None` can be represented - /// as `null` in YAML) - /// - /// ```yaml - /// default_value_if: - /// - [arg, val, default] - /// ``` - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("flag", None, "default")) - /// .get_matches_from(vec![ - /// "prog", "--flag" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("flag", None, "default")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// - /// Now lets only use the default value if `--opt` contains the value `special`. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .takes_value(true) - /// .long("opt")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("opt", Some("special"), "default")) - /// .get_matches_from(vec![ - /// "prog", "--opt", "special" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// - /// We can run the same test and provide any value *other than* `special` and we won't get a - /// default value. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .takes_value(true) - /// .long("opt")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_if("opt", Some("special"), "default")) - /// .get_matches_from(vec![ - /// "prog", "--opt", "hahaha" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - pub fn default_value_if(self, arg: &'a str, val: Option<&'b str>, default: &'b str) -> Self { - self.default_value_if_os( - arg, - val.map(str::as_bytes).map(OsStr::from_bytes), - OsStr::from_bytes(default.as_bytes()), - ) - } - - /// Provides a conditional default value in the exact same manner as [`Arg::default_value_if`] - /// only using [`OsStr`]s instead. - /// [`Arg::default_value_if`]: ./struct.Arg.html#method.default_value_if - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - pub fn default_value_if_os( - mut self, - arg: &'a str, - val: Option<&'b OsStr>, - default: &'b OsStr, - ) -> Self { - self.setb(ArgSettings::TakesValue); - if let Some(ref mut vm) = self.v.default_vals_ifs { - let l = vm.len(); - vm.insert(l, (arg, val, default)); - } else { - let mut vm = VecMap::new(); - vm.insert(0, (arg, val, default)); - self.v.default_vals_ifs = Some(vm); - } - self - } - - /// Specifies multiple values and conditions in the same manner as [`Arg::default_value_if`]. - /// The method takes a slice of tuples in the `(arg, Option<val>, default)` format. - /// - /// **NOTE**: The conditions are stored in order and evaluated in the same order. I.e. the first - /// if multiple conditions are true, the first one found will be applied and the ultimate value. - /// - /// **NOTE:** If using YAML the values should be laid out as follows - /// - /// ```yaml - /// default_value_if: - /// - [arg, val, default] - /// - [arg2, null, default2] - /// ``` - /// - /// # Examples - /// - /// First we use the default value only if another arg is present at runtime. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("opt") - /// .long("opt") - /// .takes_value(true)) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, "default"), - /// ("opt", Some("channal"), "chan"), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("chan")); - /// ``` - /// - /// Next we run the same test, but without providing `--flag`. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, "default"), - /// ("opt", Some("channal"), "chan"), - /// ])) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("other"), None); - /// ``` - /// - /// We can also see that these values are applied in order, and if more than one condition is - /// true, only the first evaluated "wins" - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag")) - /// .arg(Arg::with_name("opt") - /// .long("opt") - /// .takes_value(true)) - /// .arg(Arg::with_name("other") - /// .long("other") - /// .default_value_ifs(&[ - /// ("flag", None, "default"), - /// ("opt", Some("channal"), "chan"), - /// ])) - /// .get_matches_from(vec![ - /// "prog", "--opt", "channal", "--flag" - /// ]); - /// - /// assert_eq!(m.value_of("other"), Some("default")); - /// ``` - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value - pub fn default_value_ifs(mut self, ifs: &[(&'a str, Option<&'b str>, &'b str)]) -> Self { - for &(arg, val, default) in ifs { - self = self.default_value_if_os( - arg, - val.map(str::as_bytes).map(OsStr::from_bytes), - OsStr::from_bytes(default.as_bytes()), - ); - } - self - } - - /// Provides multiple conditional default values in the exact same manner as - /// [`Arg::default_value_ifs`] only using [`OsStr`]s instead. - /// [`Arg::default_value_ifs`]: ./struct.Arg.html#method.default_value_ifs - /// [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html - #[cfg_attr(feature = "lints", allow(explicit_counter_loop))] - pub fn default_value_ifs_os(mut self, ifs: &[(&'a str, Option<&'b OsStr>, &'b OsStr)]) -> Self { - for &(arg, val, default) in ifs { - self = self.default_value_if_os(arg, val, default); - } - self - } - - /// Specifies that if the value is not passed in as an argument, that it should be retrieved - /// from the environment, if available. If it is not present in the environment, then default - /// rules will apply. - /// - /// **NOTE:** If the user *does not* use this argument at runtime, [`ArgMatches::occurrences_of`] - /// will return `0` even though the [`ArgMatches::value_of`] will return the default specified. - /// - /// **NOTE:** If the user *does not* use this argument at runtime [`ArgMatches::is_present`] will - /// return `true` if the variable is present in the environment . If you wish to determine whether - /// the argument was used at runtime or not, consider [`ArgMatches::occurrences_of`] which will - /// return `0` if the argument was *not* used at runtime. - /// - /// **NOTE:** This implicitly sets [`Arg::takes_value(true)`]. - /// - /// **NOTE:** If [`Arg::multiple(true)`] is set then [`Arg::use_delimiter(true)`] should also be - /// set. Otherwise, only a single argument will be returned from the environment variable. The - /// default delimiter is `,` and follows all the other delimiter rules. - /// - /// # Examples - /// - /// In this example, we show the variable coming from the environment: - /// - /// ```rust - /// # use std::env; - /// # use clap::{App, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("env")); - /// ``` - /// - /// In this example, we show the variable coming from an option on the CLI: - /// - /// ```rust - /// # use std::env; - /// # use clap::{App, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG")) - /// .get_matches_from(vec![ - /// "prog", "--flag", "opt" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("opt")); - /// ``` - /// - /// In this example, we show the variable coming from the environment even with the - /// presence of a default: - /// - /// ```rust - /// # use std::env; - /// # use clap::{App, Arg}; - /// - /// env::set_var("MY_FLAG", "env"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG") - /// .default_value("default")) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.value_of("flag"), Some("env")); - /// ``` - /// - /// In this example, we show the use of multiple values in a single environment variable: - /// - /// ```rust - /// # use std::env; - /// # use clap::{App, Arg}; - /// - /// env::set_var("MY_FLAG_MULTI", "env1,env2"); - /// - /// let m = App::new("prog") - /// .arg(Arg::with_name("flag") - /// .long("flag") - /// .env("MY_FLAG_MULTI") - /// .multiple(true) - /// .use_delimiter(true)) - /// .get_matches_from(vec![ - /// "prog" - /// ]); - /// - /// assert_eq!(m.values_of("flag").unwrap().collect::<Vec<_>>(), vec!["env1", "env2"]); - /// ``` - /// [`ArgMatches::occurrences_of`]: ./struct.ArgMatches.html#method.occurrences_of - /// [`ArgMatches::value_of`]: ./struct.ArgMatches.html#method.value_of - /// [`ArgMatches::is_present`]: ./struct.ArgMatches.html#method.is_present - /// [`Arg::takes_value(true)`]: ./struct.Arg.html#method.takes_value - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`Arg::use_delimiter(true)`]: ./struct.Arg.html#method.use_delimiter - pub fn env(self, name: &'a str) -> Self { - self.env_os(OsStr::new(name)) - } - - /// Specifies that if the value is not passed in as an argument, that it should be retrieved - /// from the environment if available in the exact same manner as [`Arg::env`] only using - /// [`OsStr`]s instead. - pub fn env_os(mut self, name: &'a OsStr) -> Self { - self.setb(ArgSettings::TakesValue); - - self.v.env = Some((name, env::var_os(name))); - self - } - - /// @TODO @p2 @docs @release: write docs - pub fn hide_env_values(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HideEnvValues) - } else { - self.unset(ArgSettings::HideEnvValues) - } - } - - /// When set to `true` the help string will be displayed on the line after the argument and - /// indented once. This can be helpful for arguments with very long or complex help messages. - /// This can also be helpful for arguments with very long flag names, or many/long value names. - /// - /// **NOTE:** To apply this setting to all arguments consider using - /// [`AppSettings::NextLineHelp`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("opt") - /// .long("long-option-flag") - /// .short("o") - /// .takes_value(true) - /// .value_names(&["value1", "value2"]) - /// .help("Some really long help and complex\n\ - /// help that makes more sense to be\n\ - /// on a line after the option") - /// .next_line_help(true)) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```notrust - /// nlh - /// - /// USAGE: - /// nlh [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// -o, --long-option-flag <value1> <value2> - /// Some really long help and complex - /// help that makes more sense to be - /// on a line after the option - /// ``` - /// [`AppSettings::NextLineHelp`]: ./enum.AppSettings.html#variant.NextLineHelp - pub fn next_line_help(mut self, nlh: bool) -> Self { - if nlh { - self.setb(ArgSettings::NextLineHelp); - } else { - self.unsetb(ArgSettings::NextLineHelp); - } - self - } - - /// Allows custom ordering of args within the help message. Args with a lower value will be - /// displayed first in the help message. This is helpful when one would like to emphasise - /// frequently used args, or prioritize those towards the top of the list. Duplicate values - /// **are** allowed. Args with duplicate display orders will be displayed in alphabetical - /// order. - /// - /// **NOTE:** The default is 999 for all arguments. - /// - /// **NOTE:** This setting is ignored for [positional arguments] which are always displayed in - /// [index] order. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("a") // Typically args are grouped alphabetically by name. - /// // Args without a display_order have a value of 999 and are - /// // displayed alphabetically with all other 999 valued args. - /// .long("long-option") - /// .short("o") - /// .takes_value(true) - /// .help("Some help and text")) - /// .arg(Arg::with_name("b") - /// .long("other-option") - /// .short("O") - /// .takes_value(true) - /// .display_order(1) // In order to force this arg to appear *first* - /// // all we have to do is give it a value lower than 999. - /// // Any other args with a value of 1 will be displayed - /// // alphabetically with this one...then 2 values, then 3, etc. - /// .help("I should be first!")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays the following help message - /// - /// ```notrust - /// cust-ord - /// - /// USAGE: - /// cust-ord [FLAGS] [OPTIONS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// - /// OPTIONS: - /// -O, --other-option <b> I should be first! - /// -o, --long-option <a> Some help and text - /// ``` - /// [positional arguments]: ./struct.Arg.html#method.index - /// [index]: ./struct.Arg.html#method.index - pub fn display_order(mut self, ord: usize) -> Self { - self.s.disp_ord = ord; - self - } - - /// Indicates that all parameters passed after this should not be parsed - /// individually, but rather passed in their entirety. It is worth noting - /// that setting this requires all values to come after a `--` to indicate they - /// should all be captured. For example: - /// - /// ```notrust - /// --foo something -- -v -v -v -b -b -b --baz -q -u -x - /// ``` - /// Will result in everything after `--` to be considered one raw argument. This behavior - /// may not be exactly what you are expecting and using [`AppSettings::TrailingVarArg`] - /// may be more appropriate. - /// - /// **NOTE:** Implicitly sets [`Arg::multiple(true)`], [`Arg::allow_hyphen_values(true)`], and - /// [`Arg::last(true)`] when set to `true` - /// - /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple - /// [`Arg::allow_hyphen_values(true)`]: ./struct.Arg.html#method.allow_hyphen_values - /// [`Arg::last(true)`]: ./struct.Arg.html#method.last - /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg - pub fn raw(self, raw: bool) -> Self { - self.multiple(raw).allow_hyphen_values(raw).last(raw) - } - - /// Hides an argument from short help message output. - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .hidden_short_help(true) - /// # ; - /// ``` - /// Setting `hidden_short_help(true)` will hide the argument when displaying short help text - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// - /// However, when --help is called - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_short_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --config Some help text describing the --config arg - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - pub fn hidden_short_help(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HiddenShortHelp) - } else { - self.unset(ArgSettings::HiddenShortHelp) - } - } - - /// Hides an argument from long help message output. - /// - /// **NOTE:** This does **not** hide the argument from usage strings on error - /// - /// **NOTE:** Setting this option will cause next-line-help output style to be used - /// when long help (`--help`) is called. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// Arg::with_name("debug") - /// .hidden_long_help(true) - /// # ; - /// ``` - /// Setting `hidden_long_help(true)` will hide the argument when displaying long help text - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "--help" - /// ]); - /// ``` - /// - /// The above example displays - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - /// - /// However, when -h is called - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("prog") - /// .arg(Arg::with_name("cfg") - /// .long("config") - /// .hidden_long_help(true) - /// .help("Some help text describing the --config arg")) - /// .get_matches_from(vec![ - /// "prog", "-h" - /// ]); - /// ``` - /// - /// Then the following would be displayed - /// - /// ```notrust - /// helptest - /// - /// USAGE: - /// helptest [FLAGS] - /// - /// FLAGS: - /// --config Some help text describing the --config arg - /// -h, --help Prints help information - /// -V, --version Prints version information - /// ``` - pub fn hidden_long_help(self, hide: bool) -> Self { - if hide { - self.set(ArgSettings::HiddenLongHelp) - } else { - self.unset(ArgSettings::HiddenLongHelp) - } - } - - /// Checks if one of the [`ArgSettings`] settings is set for the argument. - /// - /// [`ArgSettings`]: ./enum.ArgSettings.html - pub fn is_set(&self, s: ArgSettings) -> bool { - self.b.is_set(s) - } - - /// Sets one of the [`ArgSettings`] settings for the argument. - /// - /// [`ArgSettings`]: ./enum.ArgSettings.html - pub fn set(mut self, s: ArgSettings) -> Self { - self.setb(s); - self - } - - /// Unsets one of the [`ArgSettings`] settings for the argument. - /// - /// [`ArgSettings`]: ./enum.ArgSettings.html - pub fn unset(mut self, s: ArgSettings) -> Self { - self.unsetb(s); - self - } - - #[doc(hidden)] - pub fn setb(&mut self, s: ArgSettings) { - self.b.set(s); - } - - #[doc(hidden)] - pub fn unsetb(&mut self, s: ArgSettings) { - self.b.unset(s); - } -} - -impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for Arg<'a, 'b> { - fn from(a: &'z Arg<'a, 'b>) -> Self { - Arg { - b: a.b.clone(), - v: a.v.clone(), - s: a.s.clone(), - index: a.index, - r_ifs: a.r_ifs.clone(), - } - } -} - -impl<'n, 'e> PartialEq for Arg<'n, 'e> { - fn eq(&self, other: &Arg<'n, 'e>) -> bool { - self.b == other.b - } -} diff --git a/clap/src/args/arg_builder/base.rs b/clap/src/args/arg_builder/base.rs deleted file mode 100644 index fef9d8a..0000000 --- a/clap/src/args/arg_builder/base.rs +++ /dev/null @@ -1,38 +0,0 @@ -use args::{Arg, ArgFlags, ArgSettings}; - -#[derive(Debug, Clone, Default)] -pub struct Base<'a, 'b> -where - 'a: 'b, -{ - pub name: &'a str, - pub help: Option<&'b str>, - pub long_help: Option<&'b str>, - pub blacklist: Option<Vec<&'a str>>, - pub settings: ArgFlags, - pub r_unless: Option<Vec<&'a str>>, - pub overrides: Option<Vec<&'a str>>, - pub groups: Option<Vec<&'a str>>, - pub requires: Option<Vec<(Option<&'b str>, &'a str)>>, -} - -impl<'n, 'e> Base<'n, 'e> { - pub fn new(name: &'n str) -> Self { - Base { - name: name, - ..Default::default() - } - } - - pub fn set(&mut self, s: ArgSettings) { self.settings.set(s); } - pub fn unset(&mut self, s: ArgSettings) { self.settings.unset(s); } - pub fn is_set(&self, s: ArgSettings) -> bool { self.settings.is_set(s) } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Base<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { a.b.clone() } -} - -impl<'n, 'e> PartialEq for Base<'n, 'e> { - fn eq(&self, other: &Base<'n, 'e>) -> bool { self.name == other.name } -} diff --git a/clap/src/args/arg_builder/flag.rs b/clap/src/args/arg_builder/flag.rs deleted file mode 100644 index 641e777..0000000 --- a/clap/src/args/arg_builder/flag.rs +++ /dev/null @@ -1,159 +0,0 @@ -// Std -use std::convert::From; -use std::fmt::{Display, Formatter, Result}; -use std::rc::Rc; -use std::result::Result as StdResult; -use std::ffi::{OsStr, OsString}; -use std::mem; - -// Internal -use Arg; -use args::{AnyArg, ArgSettings, Base, DispOrder, Switched}; -use map::{self, VecMap}; - -#[derive(Default, Clone, Debug)] -#[doc(hidden)] -pub struct FlagBuilder<'n, 'e> -where - 'n: 'e, -{ - pub b: Base<'n, 'e>, - pub s: Switched<'e>, -} - -impl<'n, 'e> FlagBuilder<'n, 'e> { - pub fn new(name: &'n str) -> Self { - FlagBuilder { - b: Base::new(name), - ..Default::default() - } - } -} - -impl<'a, 'b, 'z> From<&'z Arg<'a, 'b>> for FlagBuilder<'a, 'b> { - fn from(a: &'z Arg<'a, 'b>) -> Self { - FlagBuilder { - b: Base::from(a), - s: Switched::from(a), - } - } -} - -impl<'a, 'b> From<Arg<'a, 'b>> for FlagBuilder<'a, 'b> { - fn from(mut a: Arg<'a, 'b>) -> Self { - FlagBuilder { - b: mem::replace(&mut a.b, Base::default()), - s: mem::replace(&mut a.s, Switched::default()), - } - } -} - -impl<'n, 'e> Display for FlagBuilder<'n, 'e> { - fn fmt(&self, f: &mut Formatter) -> Result { - if let Some(l) = self.s.long { - write!(f, "--{}", l)?; - } else { - write!(f, "-{}", self.s.short.unwrap())?; - } - - Ok(()) - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for FlagBuilder<'n, 'e> { - fn name(&self) -> &'n str { self.b.name } - fn overrides(&self) -> Option<&[&'e str]> { self.b.overrides.as_ref().map(|o| &o[..]) } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - self.b.requires.as_ref().map(|o| &o[..]) - } - fn blacklist(&self) -> Option<&[&'e str]> { self.b.blacklist.as_ref().map(|o| &o[..]) } - fn required_unless(&self) -> Option<&[&'e str]> { self.b.r_unless.as_ref().map(|o| &o[..]) } - fn is_set(&self, s: ArgSettings) -> bool { self.b.settings.is_set(s) } - fn has_switch(&self) -> bool { true } - fn takes_value(&self) -> bool { false } - fn set(&mut self, s: ArgSettings) { self.b.settings.set(s) } - fn max_vals(&self) -> Option<u64> { None } - fn val_names(&self) -> Option<&VecMap<&'e str>> { 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> { self.s.short } - fn long(&self) -> Option<&'e str> { self.s.long } - fn val_delim(&self) -> Option<char> { None } - fn help(&self) -> Option<&'e str> { self.b.help } - fn long_help(&self) -> Option<&'e str> { self.b.long_help } - fn val_terminator(&self) -> Option<&'e str> { None } - 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 { self.s.long.is_some() } - fn aliases(&self) -> Option<Vec<&'e str>> { - if let Some(ref aliases) = self.s.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> DispOrder for FlagBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { self.s.disp_ord } -} - -impl<'n, 'e> PartialEq for FlagBuilder<'n, 'e> { - fn eq(&self, other: &FlagBuilder<'n, 'e>) -> bool { self.b == other.b } -} - -#[cfg(test)] -mod test { - use args::settings::ArgSettings; - use super::FlagBuilder; - - #[test] - fn flagbuilder_display() { - let mut f = FlagBuilder::new("flg"); - f.b.settings.set(ArgSettings::Multiple); - f.s.long = Some("flag"); - - assert_eq!(&*format!("{}", f), "--flag"); - - let mut f2 = FlagBuilder::new("flg"); - f2.s.short = Some('f'); - - assert_eq!(&*format!("{}", f2), "-f"); - } - - #[test] - fn flagbuilder_display_single_alias() { - let mut f = FlagBuilder::new("flg"); - f.s.long = Some("flag"); - f.s.aliases = Some(vec![("als", true)]); - - assert_eq!(&*format!("{}", f), "--flag"); - } - - #[test] - fn flagbuilder_display_multiple_aliases() { - let mut f = FlagBuilder::new("flg"); - f.s.short = Some('f'); - f.s.aliases = Some(vec![ - ("alias_not_visible", false), - ("f2", true), - ("f3", true), - ("f4", true), - ]); - assert_eq!(&*format!("{}", f), "-f"); - } -} diff --git a/clap/src/args/arg_builder/mod.rs b/clap/src/args/arg_builder/mod.rs deleted file mode 100644 index d1a7a66..0000000 --- a/clap/src/args/arg_builder/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -pub use self::flag::FlagBuilder; -pub use self::option::OptBuilder; -pub use self::positional::PosBuilder; -pub use self::base::Base; -pub use self::switched::Switched; -pub use self::valued::Valued; - -mod flag; -mod positional; -mod option; -mod base; -mod valued; -mod switched; diff --git a/clap/src/args/arg_builder/option.rs b/clap/src/args/arg_builder/option.rs deleted file mode 100644 index 4bb147a..0000000 --- a/clap/src/args/arg_builder/option.rs +++ /dev/null @@ -1,244 +0,0 @@ -// Std -use std::fmt::{Display, Formatter, Result}; -use std::rc::Rc; -use std::result::Result as StdResult; -use std::ffi::{OsStr, OsString}; -use std::mem; - -// Internal -use args::{AnyArg, Arg, ArgSettings, Base, DispOrder, Switched, Valued}; -use map::{self, VecMap}; -use INTERNAL_ERROR_MSG; - -#[allow(missing_debug_implementations)] -#[doc(hidden)] -#[derive(Default, Clone)] -pub struct OptBuilder<'n, 'e> -where - 'n: 'e, -{ - pub b: Base<'n, 'e>, - pub s: Switched<'e>, - pub v: Valued<'n, 'e>, -} - -impl<'n, 'e> OptBuilder<'n, 'e> { - pub fn new(name: &'n str) -> Self { - OptBuilder { - b: Base::new(name), - ..Default::default() - } - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for OptBuilder<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { - OptBuilder { - b: Base::from(a), - s: Switched::from(a), - v: Valued::from(a), - } - } -} - -impl<'n, 'e> From<Arg<'n, 'e>> for OptBuilder<'n, 'e> { - fn from(mut a: Arg<'n, 'e>) -> Self { - a.v.fill_in(); - OptBuilder { - b: mem::replace(&mut a.b, Base::default()), - s: mem::replace(&mut a.s, Switched::default()), - v: mem::replace(&mut a.v, Valued::default()), - } - } -} - -impl<'n, 'e> Display for OptBuilder<'n, 'e> { - fn fmt(&self, f: &mut Formatter) -> Result { - debugln!("OptBuilder::fmt:{}", self.b.name); - let sep = if self.b.is_set(ArgSettings::RequireEquals) { - "=" - } else { - " " - }; - // Write the name such --long or -l - if let Some(l) = self.s.long { - write!(f, "--{}{}", l, sep)?; - } else { - write!(f, "-{}{}", self.s.short.unwrap(), sep)?; - } - let delim = if self.is_set(ArgSettings::RequireDelimiter) { - self.v.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }; - - // Write the values such as <name1> <name2> - if let Some(ref vec) = self.v.val_names { - let mut it = vec.iter().peekable(); - while let Some((_, val)) = it.next() { - write!(f, "<{}>", val)?; - if it.peek().is_some() { - write!(f, "{}", delim)?; - } - } - let num = vec.len(); - if self.is_set(ArgSettings::Multiple) && num == 1 { - write!(f, "...")?; - } - } else if let Some(num) = self.v.num_vals { - let mut it = (0..num).peekable(); - while let Some(_) = it.next() { - write!(f, "<{}>", self.b.name)?; - if it.peek().is_some() { - write!(f, "{}", delim)?; - } - } - if self.is_set(ArgSettings::Multiple) && num == 1 { - write!(f, "...")?; - } - } else { - write!( - f, - "<{}>{}", - self.b.name, - if self.is_set(ArgSettings::Multiple) { - "..." - } else { - "" - } - )?; - } - - Ok(()) - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for OptBuilder<'n, 'e> { - fn name(&self) -> &'n str { self.b.name } - fn overrides(&self) -> Option<&[&'e str]> { self.b.overrides.as_ref().map(|o| &o[..]) } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - self.b.requires.as_ref().map(|o| &o[..]) - } - fn blacklist(&self) -> Option<&[&'e str]> { self.b.blacklist.as_ref().map(|o| &o[..]) } - fn required_unless(&self) -> Option<&[&'e str]> { self.b.r_unless.as_ref().map(|o| &o[..]) } - fn val_names(&self) -> Option<&VecMap<&'e str>> { self.v.val_names.as_ref() } - fn is_set(&self, s: ArgSettings) -> bool { self.b.settings.is_set(s) } - fn has_switch(&self) -> bool { true } - fn set(&mut self, s: ArgSettings) { self.b.settings.set(s) } - fn max_vals(&self) -> Option<u64> { self.v.max_vals } - fn val_terminator(&self) -> Option<&'e str> { self.v.terminator } - fn num_vals(&self) -> Option<u64> { self.v.num_vals } - fn possible_vals(&self) -> Option<&[&'e str]> { self.v.possible_vals.as_ref().map(|o| &o[..]) } - fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { - self.v.validator.as_ref() - } - fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> { - self.v.validator_os.as_ref() - } - fn min_vals(&self) -> Option<u64> { self.v.min_vals } - fn short(&self) -> Option<char> { self.s.short } - fn long(&self) -> Option<&'e str> { self.s.long } - fn val_delim(&self) -> Option<char> { self.v.val_delim } - fn takes_value(&self) -> bool { true } - fn help(&self) -> Option<&'e str> { self.b.help } - fn long_help(&self) -> Option<&'e str> { self.b.long_help } - fn default_val(&self) -> Option<&'e OsStr> { self.v.default_val } - fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> { - self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) - } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - self.v - .env - .as_ref() - .map(|&(key, ref value)| (key, value.as_ref())) - } - fn longest_filter(&self) -> bool { true } - fn aliases(&self) -> Option<Vec<&'e str>> { - if let Some(ref aliases) = self.s.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> DispOrder for OptBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { self.s.disp_ord } -} - -impl<'n, 'e> PartialEq for OptBuilder<'n, 'e> { - fn eq(&self, other: &OptBuilder<'n, 'e>) -> bool { self.b == other.b } -} - -#[cfg(test)] -mod test { - use args::settings::ArgSettings; - use super::OptBuilder; - use map::VecMap; - - #[test] - fn optbuilder_display1() { - let mut o = OptBuilder::new("opt"); - o.s.long = Some("option"); - o.b.settings.set(ArgSettings::Multiple); - - assert_eq!(&*format!("{}", o), "--option <opt>..."); - } - - #[test] - fn optbuilder_display2() { - let mut v_names = VecMap::new(); - v_names.insert(0, "file"); - v_names.insert(1, "name"); - - let mut o2 = OptBuilder::new("opt"); - o2.s.short = Some('o'); - o2.v.val_names = Some(v_names); - - assert_eq!(&*format!("{}", o2), "-o <file> <name>"); - } - - #[test] - fn optbuilder_display3() { - let mut v_names = VecMap::new(); - v_names.insert(0, "file"); - v_names.insert(1, "name"); - - let mut o2 = OptBuilder::new("opt"); - o2.s.short = Some('o'); - o2.v.val_names = Some(v_names); - o2.b.settings.set(ArgSettings::Multiple); - - assert_eq!(&*format!("{}", o2), "-o <file> <name>"); - } - - #[test] - fn optbuilder_display_single_alias() { - let mut o = OptBuilder::new("opt"); - o.s.long = Some("option"); - o.s.aliases = Some(vec![("als", true)]); - - assert_eq!(&*format!("{}", o), "--option <opt>"); - } - - #[test] - fn optbuilder_display_multiple_aliases() { - let mut o = OptBuilder::new("opt"); - o.s.long = Some("option"); - o.s.aliases = Some(vec![ - ("als_not_visible", false), - ("als2", true), - ("als3", true), - ("als4", true), - ]); - assert_eq!(&*format!("{}", o), "--option <opt>"); - } -} diff --git a/clap/src/args/arg_builder/positional.rs b/clap/src/args/arg_builder/positional.rs deleted file mode 100644 index 43fdca4..0000000 --- a/clap/src/args/arg_builder/positional.rs +++ /dev/null @@ -1,229 +0,0 @@ -// Std -use std::borrow::Cow; -use std::fmt::{Display, Formatter, Result}; -use std::rc::Rc; -use std::result::Result as StdResult; -use std::ffi::{OsStr, OsString}; -use std::mem; - -// Internal -use Arg; -use args::{AnyArg, ArgSettings, Base, DispOrder, Valued}; -use INTERNAL_ERROR_MSG; -use map::{self, VecMap}; - -#[allow(missing_debug_implementations)] -#[doc(hidden)] -#[derive(Clone, Default)] -pub struct PosBuilder<'n, 'e> -where - 'n: 'e, -{ - pub b: Base<'n, 'e>, - pub v: Valued<'n, 'e>, - pub index: u64, -} - -impl<'n, 'e> PosBuilder<'n, 'e> { - pub fn new(name: &'n str, idx: u64) -> Self { - PosBuilder { - b: Base::new(name), - index: idx, - ..Default::default() - } - } - - pub fn from_arg_ref(a: &Arg<'n, 'e>, idx: u64) -> Self { - let mut pb = PosBuilder { - b: Base::from(a), - v: Valued::from(a), - index: idx, - }; - if a.v.max_vals.is_some() || a.v.min_vals.is_some() - || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) - { - pb.b.settings.set(ArgSettings::Multiple); - } - pb - } - - pub fn from_arg(mut a: Arg<'n, 'e>, idx: u64) -> Self { - if a.v.max_vals.is_some() || a.v.min_vals.is_some() - || (a.v.num_vals.is_some() && a.v.num_vals.unwrap() > 1) - { - a.b.settings.set(ArgSettings::Multiple); - } - PosBuilder { - b: mem::replace(&mut a.b, Base::default()), - v: mem::replace(&mut a.v, Valued::default()), - index: idx, - } - } - - pub fn multiple_str(&self) -> &str { - let mult_vals = self.v - .val_names - .as_ref() - .map_or(true, |names| names.len() < 2); - if self.is_set(ArgSettings::Multiple) && mult_vals { - "..." - } else { - "" - } - } - - pub fn name_no_brackets(&self) -> Cow<str> { - debugln!("PosBuilder::name_no_brackets;"); - let mut delim = String::new(); - delim.push(if self.is_set(ArgSettings::RequireDelimiter) { - self.v.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }); - if let Some(ref names) = self.v.val_names { - debugln!("PosBuilder:name_no_brackets: val_names={:#?}", names); - if names.len() > 1 { - Cow::Owned( - names - .values() - .map(|n| format!("<{}>", n)) - .collect::<Vec<_>>() - .join(&*delim), - ) - } else { - Cow::Borrowed(names.values().next().expect(INTERNAL_ERROR_MSG)) - } - } else { - debugln!("PosBuilder:name_no_brackets: just name"); - Cow::Borrowed(self.b.name) - } - } -} - -impl<'n, 'e> Display for PosBuilder<'n, 'e> { - fn fmt(&self, f: &mut Formatter) -> Result { - let mut delim = String::new(); - delim.push(if self.is_set(ArgSettings::RequireDelimiter) { - self.v.val_delim.expect(INTERNAL_ERROR_MSG) - } else { - ' ' - }); - if let Some(ref names) = self.v.val_names { - write!( - f, - "{}", - names - .values() - .map(|n| format!("<{}>", n)) - .collect::<Vec<_>>() - .join(&*delim) - )?; - } else { - write!(f, "<{}>", self.b.name)?; - } - if self.b.settings.is_set(ArgSettings::Multiple) - && (self.v.val_names.is_none() || self.v.val_names.as_ref().unwrap().len() == 1) - { - write!(f, "...")?; - } - - Ok(()) - } -} - -impl<'n, 'e> AnyArg<'n, 'e> for PosBuilder<'n, 'e> { - fn name(&self) -> &'n str { self.b.name } - fn overrides(&self) -> Option<&[&'e str]> { self.b.overrides.as_ref().map(|o| &o[..]) } - fn requires(&self) -> Option<&[(Option<&'e str>, &'n str)]> { - self.b.requires.as_ref().map(|o| &o[..]) - } - fn blacklist(&self) -> Option<&[&'e str]> { self.b.blacklist.as_ref().map(|o| &o[..]) } - fn required_unless(&self) -> Option<&[&'e str]> { self.b.r_unless.as_ref().map(|o| &o[..]) } - fn val_names(&self) -> Option<&VecMap<&'e str>> { self.v.val_names.as_ref() } - fn is_set(&self, s: ArgSettings) -> bool { self.b.settings.is_set(s) } - fn set(&mut self, s: ArgSettings) { self.b.settings.set(s) } - fn has_switch(&self) -> bool { false } - fn max_vals(&self) -> Option<u64> { self.v.max_vals } - fn val_terminator(&self) -> Option<&'e str> { self.v.terminator } - fn num_vals(&self) -> Option<u64> { self.v.num_vals } - fn possible_vals(&self) -> Option<&[&'e str]> { self.v.possible_vals.as_ref().map(|o| &o[..]) } - fn validator(&self) -> Option<&Rc<Fn(String) -> StdResult<(), String>>> { - self.v.validator.as_ref() - } - fn validator_os(&self) -> Option<&Rc<Fn(&OsStr) -> StdResult<(), OsString>>> { - self.v.validator_os.as_ref() - } - fn min_vals(&self) -> Option<u64> { self.v.min_vals } - fn short(&self) -> Option<char> { None } - fn long(&self) -> Option<&'e str> { None } - fn val_delim(&self) -> Option<char> { self.v.val_delim } - fn takes_value(&self) -> bool { true } - fn help(&self) -> Option<&'e str> { self.b.help } - fn long_help(&self) -> Option<&'e str> { self.b.long_help } - fn default_vals_ifs(&self) -> Option<map::Values<(&'n str, Option<&'e OsStr>, &'e OsStr)>> { - self.v.default_vals_ifs.as_ref().map(|vm| vm.values()) - } - fn default_val(&self) -> Option<&'e OsStr> { self.v.default_val } - fn env<'s>(&'s self) -> Option<(&'n OsStr, Option<&'s OsString>)> { - self.v - .env - .as_ref() - .map(|&(key, ref value)| (key, value.as_ref())) - } - fn longest_filter(&self) -> bool { true } - fn aliases(&self) -> Option<Vec<&'e str>> { None } -} - -impl<'n, 'e> DispOrder for PosBuilder<'n, 'e> { - fn disp_ord(&self) -> usize { self.index as usize } -} - -impl<'n, 'e> PartialEq for PosBuilder<'n, 'e> { - fn eq(&self, other: &PosBuilder<'n, 'e>) -> bool { self.b == other.b } -} - -#[cfg(test)] -mod test { - use args::settings::ArgSettings; - use super::PosBuilder; - use map::VecMap; - - #[test] - fn display_mult() { - let mut p = PosBuilder::new("pos", 1); - p.b.settings.set(ArgSettings::Multiple); - - assert_eq!(&*format!("{}", p), "<pos>..."); - } - - #[test] - fn display_required() { - let mut p2 = PosBuilder::new("pos", 1); - p2.b.settings.set(ArgSettings::Required); - - assert_eq!(&*format!("{}", p2), "<pos>"); - } - - #[test] - fn display_val_names() { - let mut p2 = PosBuilder::new("pos", 1); - let mut vm = VecMap::new(); - vm.insert(0, "file1"); - vm.insert(1, "file2"); - p2.v.val_names = Some(vm); - - assert_eq!(&*format!("{}", p2), "<file1> <file2>"); - } - - #[test] - fn display_val_names_req() { - let mut p2 = PosBuilder::new("pos", 1); - p2.b.settings.set(ArgSettings::Required); - let mut vm = VecMap::new(); - vm.insert(0, "file1"); - vm.insert(1, "file2"); - p2.v.val_names = Some(vm); - - assert_eq!(&*format!("{}", p2), "<file1> <file2>"); - } -} diff --git a/clap/src/args/arg_builder/switched.rs b/clap/src/args/arg_builder/switched.rs deleted file mode 100644 index 224b2f2..0000000 --- a/clap/src/args/arg_builder/switched.rs +++ /dev/null @@ -1,38 +0,0 @@ -use Arg; - -#[derive(Debug)] -pub struct Switched<'b> { - pub short: Option<char>, - pub long: Option<&'b str>, - pub aliases: Option<Vec<(&'b str, bool)>>, // (name, visible) - pub disp_ord: usize, - pub unified_ord: usize, -} - -impl<'e> Default for Switched<'e> { - fn default() -> Self { - Switched { - short: None, - long: None, - aliases: None, - disp_ord: 999, - unified_ord: 999, - } - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Switched<'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { a.s.clone() } -} - -impl<'e> Clone for Switched<'e> { - fn clone(&self) -> Self { - Switched { - short: self.short, - long: self.long, - aliases: self.aliases.clone(), - disp_ord: self.disp_ord, - unified_ord: self.unified_ord, - } - } -} diff --git a/clap/src/args/arg_builder/valued.rs b/clap/src/args/arg_builder/valued.rs deleted file mode 100644 index d70854d..0000000 --- a/clap/src/args/arg_builder/valued.rs +++ /dev/null @@ -1,67 +0,0 @@ -use std::rc::Rc; -use std::ffi::{OsStr, OsString}; - -use map::VecMap; - -use Arg; - -#[allow(missing_debug_implementations)] -#[derive(Clone)] -pub struct Valued<'a, 'b> -where - 'a: 'b, -{ - pub possible_vals: Option<Vec<&'b str>>, - pub val_names: Option<VecMap<&'b str>>, - pub num_vals: Option<u64>, - pub max_vals: Option<u64>, - pub min_vals: Option<u64>, - pub validator: Option<Rc<Fn(String) -> Result<(), String>>>, - pub validator_os: Option<Rc<Fn(&OsStr) -> Result<(), OsString>>>, - pub val_delim: Option<char>, - pub default_val: Option<&'b OsStr>, - pub default_vals_ifs: Option<VecMap<(&'a str, Option<&'b OsStr>, &'b OsStr)>>, - pub env: Option<(&'a OsStr, Option<OsString>)>, - pub terminator: Option<&'b str>, -} - -impl<'n, 'e> Default for Valued<'n, 'e> { - fn default() -> Self { - Valued { - possible_vals: None, - num_vals: None, - min_vals: None, - max_vals: None, - val_names: None, - validator: None, - validator_os: None, - val_delim: None, - default_val: None, - default_vals_ifs: None, - env: None, - terminator: None, - } - } -} - -impl<'n, 'e> Valued<'n, 'e> { - pub fn fill_in(&mut self) { - if let Some(ref vec) = self.val_names { - if vec.len() > 1 { - self.num_vals = Some(vec.len() as u64); - } - } - } -} - -impl<'n, 'e, 'z> From<&'z Arg<'n, 'e>> for Valued<'n, 'e> { - fn from(a: &'z Arg<'n, 'e>) -> Self { - let mut v = a.v.clone(); - if let Some(ref vec) = a.v.val_names { - if vec.len() > 1 { - v.num_vals = Some(vec.len() as u64); - } - } - v - } -} diff --git a/clap/src/args/arg_matcher.rs b/clap/src/args/arg_matcher.rs deleted file mode 100644 index e1d8067..0000000 --- a/clap/src/args/arg_matcher.rs +++ /dev/null @@ -1,218 +0,0 @@ -// Std -use std::collections::hash_map::{Entry, Iter}; -use std::collections::HashMap; -use std::ffi::OsStr; -use std::ops::Deref; -use std::mem; - -// Internal -use args::{ArgMatches, MatchedArg, SubCommand}; -use args::AnyArg; -use args::settings::ArgSettings; - -#[doc(hidden)] -#[allow(missing_debug_implementations)] -pub struct ArgMatcher<'a>(pub ArgMatches<'a>); - -impl<'a> Default for ArgMatcher<'a> { - fn default() -> Self { ArgMatcher(ArgMatches::default()) } -} - -impl<'a> ArgMatcher<'a> { - pub fn new() -> Self { ArgMatcher::default() } - - pub fn process_arg_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>, overrides: &mut Vec<(&'b str, &'a str)>, required: &mut Vec<&'a str>, check_all: bool) { - debugln!("ArgMatcher::process_arg_overrides:{:?};", a.map_or(None, |a| Some(a.name()))); - if let Some(aa) = a { - let mut self_done = false; - if let Some(a_overrides) = aa.overrides() { - for overr in a_overrides { - debugln!("ArgMatcher::process_arg_overrides:iter:{};", overr); - if overr == &aa.name() { - self_done = true; - self.handle_self_overrides(a); - } else if self.is_present(overr) { - debugln!("ArgMatcher::process_arg_overrides:iter:{}: removing from matches;", overr); - self.remove(overr); - for i in (0 .. required.len()).rev() { - if &required[i] == overr { - debugln!("ArgMatcher::process_arg_overrides:iter:{}: removing required;", overr); - required.swap_remove(i); - break; - } - } - overrides.push((overr, aa.name())); - } else { - overrides.push((overr, aa.name())); - } - } - } - if check_all && !self_done { - self.handle_self_overrides(a); - } - } - } - - pub fn handle_self_overrides<'b>(&mut self, a: Option<&AnyArg<'a, 'b>>) { - debugln!("ArgMatcher::handle_self_overrides:{:?};", a.map_or(None, |a| Some(a.name()))); - if let Some(aa) = a { - if !aa.has_switch() || aa.is_set(ArgSettings::Multiple) { - // positional args can't override self or else we would never advance to the next - - // Also flags with --multiple set are ignored otherwise we could never have more - // than one - return; - } - if let Some(ma) = self.get_mut(aa.name()) { - if ma.vals.len() > 1 { - // swap_remove(0) would be O(1) but does not preserve order, which - // we need - ma.vals.remove(0); - ma.occurs = 1; - } else if !aa.takes_value() && ma.occurs > 1 { - ma.occurs = 1; - } - } - } - } - - pub fn is_present(&self, name: &str) -> bool { - self.0.is_present(name) - } - - pub fn propagate_globals(&mut self, global_arg_vec: &[&'a str]) { - debugln!( "ArgMatcher::get_global_values: global_arg_vec={:?}", global_arg_vec ); - let mut vals_map = HashMap::new(); - self.fill_in_global_values(global_arg_vec, &mut vals_map); - } - - fn fill_in_global_values( - &mut self, - global_arg_vec: &[&'a str], - vals_map: &mut HashMap<&'a str, MatchedArg>, - ) { - for global_arg in global_arg_vec { - if let Some(ma) = self.get(global_arg) { - // We have to check if the parent's global arg wasn't used but still exists - // such as from a default value. - // - // For example, `myprog subcommand --global-arg=value` where --global-arg defines - // a default value of `other` myprog would have an existing MatchedArg for - // --global-arg where the value is `other`, however the occurs will be 0. - let to_update = if let Some(parent_ma) = vals_map.get(global_arg) { - if parent_ma.occurs > 0 && ma.occurs == 0 { - parent_ma.clone() - } else { - ma.clone() - } - } else { - ma.clone() - }; - vals_map.insert(global_arg, to_update); - } - } - if let Some(ref mut sc) = self.0.subcommand { - let mut am = ArgMatcher(mem::replace(&mut sc.matches, ArgMatches::new())); - am.fill_in_global_values(global_arg_vec, vals_map); - mem::swap(&mut am.0, &mut sc.matches); - } - - for (name, matched_arg) in vals_map.into_iter() { - self.0.args.insert(name, matched_arg.clone()); - } - } - - pub fn get_mut(&mut self, arg: &str) -> Option<&mut MatchedArg> { self.0.args.get_mut(arg) } - - pub fn get(&self, arg: &str) -> Option<&MatchedArg> { self.0.args.get(arg) } - - pub fn remove(&mut self, arg: &str) { self.0.args.remove(arg); } - - pub fn remove_all(&mut self, args: &[&str]) { - for &arg in args { - self.0.args.remove(arg); - } - } - - pub fn insert(&mut self, name: &'a str) { self.0.args.insert(name, MatchedArg::new()); } - - pub fn contains(&self, arg: &str) -> bool { self.0.args.contains_key(arg) } - - pub fn is_empty(&self) -> bool { self.0.args.is_empty() } - - pub fn usage(&mut self, usage: String) { self.0.usage = Some(usage); } - - pub fn arg_names(&'a self) -> Vec<&'a str> { self.0.args.keys().map(Deref::deref).collect() } - - pub fn entry(&mut self, arg: &'a str) -> Entry<&'a str, MatchedArg> { self.0.args.entry(arg) } - - pub fn subcommand(&mut self, sc: SubCommand<'a>) { self.0.subcommand = Some(Box::new(sc)); } - - pub fn subcommand_name(&self) -> Option<&str> { self.0.subcommand_name() } - - pub fn iter(&self) -> Iter<&str, MatchedArg> { self.0.args.iter() } - - pub fn inc_occurrence_of(&mut self, arg: &'a str) { - debugln!("ArgMatcher::inc_occurrence_of: arg={}", arg); - if let Some(a) = self.get_mut(arg) { - a.occurs += 1; - return; - } - debugln!("ArgMatcher::inc_occurrence_of: first instance"); - self.insert(arg); - } - - pub fn inc_occurrences_of(&mut self, args: &[&'a str]) { - debugln!("ArgMatcher::inc_occurrences_of: args={:?}", args); - for arg in args { - self.inc_occurrence_of(arg); - } - } - - pub fn add_val_to(&mut self, arg: &'a str, val: &OsStr) { - let ma = self.entry(arg).or_insert(MatchedArg { - occurs: 0, - indices: Vec::with_capacity(1), - vals: Vec::with_capacity(1), - }); - ma.vals.push(val.to_owned()); - } - - pub fn add_index_to(&mut self, arg: &'a str, idx: usize) { - let ma = self.entry(arg).or_insert(MatchedArg { - occurs: 0, - indices: Vec::with_capacity(1), - vals: Vec::new(), - }); - ma.indices.push(idx); - } - - pub fn needs_more_vals<'b, A>(&self, o: &A) -> bool - where - A: AnyArg<'a, 'b>, - { - debugln!("ArgMatcher::needs_more_vals: o={}", o.name()); - if let Some(ma) = self.get(o.name()) { - if let Some(num) = o.num_vals() { - debugln!("ArgMatcher::needs_more_vals: num_vals...{}", num); - return if o.is_set(ArgSettings::Multiple) { - ((ma.vals.len() as u64) % num) != 0 - } else { - num != (ma.vals.len() as u64) - }; - } else if let Some(num) = o.max_vals() { - debugln!("ArgMatcher::needs_more_vals: max_vals...{}", num); - return !((ma.vals.len() as u64) > num); - } else if o.min_vals().is_some() { - debugln!("ArgMatcher::needs_more_vals: min_vals...true"); - return true; - } - return o.is_set(ArgSettings::Multiple); - } - true - } -} - -impl<'a> Into<ArgMatches<'a>> for ArgMatcher<'a> { - fn into(self) -> ArgMatches<'a> { self.0 } -} diff --git a/clap/src/args/arg_matches.rs b/clap/src/args/arg_matches.rs deleted file mode 100644 index 6cf70a4..0000000 --- a/clap/src/args/arg_matches.rs +++ /dev/null @@ -1,963 +0,0 @@ -// Std -use std::borrow::Cow; -use std::collections::HashMap; -use std::ffi::{OsStr, OsString}; -use std::iter::Map; -use std::slice::Iter; - -// Internal -use INVALID_UTF8; -use args::MatchedArg; -use args::SubCommand; - -/// Used to get information about the arguments that where supplied to the program at runtime by -/// the user. New instances of this struct are obtained by using the [`App::get_matches`] family of -/// methods. -/// -/// # Examples -/// -/// ```no_run -/// # use clap::{App, Arg}; -/// let matches = App::new("MyApp") -/// .arg(Arg::with_name("out") -/// .long("output") -/// .required(true) -/// .takes_value(true)) -/// .arg(Arg::with_name("debug") -/// .short("d") -/// .multiple(true)) -/// .arg(Arg::with_name("cfg") -/// .short("c") -/// .takes_value(true)) -/// .get_matches(); // builds the instance of ArgMatches -/// -/// // to get information about the "cfg" argument we created, such as the value supplied we use -/// // various ArgMatches methods, such as ArgMatches::value_of -/// if let Some(c) = matches.value_of("cfg") { -/// println!("Value for -c: {}", c); -/// } -/// -/// // The ArgMatches::value_of method returns an Option because the user may not have supplied -/// // that argument at runtime. But if we specified that the argument was "required" as we did -/// // with the "out" argument, we can safely unwrap because `clap` verifies that was actually -/// // used at runtime. -/// println!("Value for --output: {}", matches.value_of("out").unwrap()); -/// -/// // You can check the presence of an argument -/// if matches.is_present("out") { -/// // Another way to check if an argument was present, or if it occurred multiple times is to -/// // use occurrences_of() which returns 0 if an argument isn't found at runtime, or the -/// // number of times that it occurred, if it was. To allow an argument to appear more than -/// // once, you must use the .multiple(true) method, otherwise it will only return 1 or 0. -/// if matches.occurrences_of("debug") > 2 { -/// println!("Debug mode is REALLY on, don't be crazy"); -/// } else { -/// println!("Debug mode kind of on"); -/// } -/// } -/// ``` -/// [`App::get_matches`]: ./struct.App.html#method.get_matches -#[derive(Debug, Clone)] -pub struct ArgMatches<'a> { - #[doc(hidden)] pub args: HashMap<&'a str, MatchedArg>, - #[doc(hidden)] pub subcommand: Option<Box<SubCommand<'a>>>, - #[doc(hidden)] pub usage: Option<String>, -} - -impl<'a> Default for ArgMatches<'a> { - fn default() -> Self { - ArgMatches { - args: HashMap::new(), - subcommand: None, - usage: None, - } - } -} - -impl<'a> ArgMatches<'a> { - #[doc(hidden)] - pub fn new() -> Self { - ArgMatches { - ..Default::default() - } - } - - /// Gets the value of a specific [option] or [positional] argument (i.e. an argument that takes - /// an additional value at runtime). If the option wasn't present at runtime - /// it returns `None`. - /// - /// *NOTE:* If getting a value for an option or positional argument that allows multiples, - /// prefer [`ArgMatches::values_of`] as `ArgMatches::value_of` will only return the *first* - /// value. - /// - /// # Panics - /// - /// This method will [`panic!`] if the value contains invalid UTF-8 code points. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("output") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "something"]); - /// - /// assert_eq!(m.value_of("output"), Some("something")); - /// ``` - /// [option]: ./struct.Arg.html#method.takes_value - /// [positional]: ./struct.Arg.html#method.index - /// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of - /// [`panic!`]: https://doc.rust-lang.org/std/macro.panic!.html - pub fn value_of<S: AsRef<str>>(&self, name: S) -> Option<&str> { - if let Some(arg) = self.args.get(name.as_ref()) { - if let Some(v) = arg.vals.get(0) { - return Some(v.to_str().expect(INVALID_UTF8)); - } - } - None - } - - /// Gets the lossy value of a specific argument. If the argument wasn't present at runtime - /// it returns `None`. A lossy value is one which contains invalid UTF-8 code points, those - /// invalid points will be replaced with `\u{FFFD}` - /// - /// *NOTE:* If getting a value for an option or positional argument that allows multiples, - /// prefer [`Arg::values_of_lossy`] as `value_of_lossy()` will only return the *first* value. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage("<arg> 'some arg'")) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi {0xe9}!" - /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); - /// assert_eq!(&*m.value_of_lossy("arg").unwrap(), "Hi \u{FFFD}!"); - /// ``` - /// [`Arg::values_of_lossy`]: ./struct.ArgMatches.html#method.values_of_lossy - pub fn value_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Cow<'a, str>> { - if let Some(arg) = self.args.get(name.as_ref()) { - if let Some(v) = arg.vals.get(0) { - return Some(v.to_string_lossy()); - } - } - None - } - - /// Gets the OS version of a string value of a specific argument. If the option wasn't present - /// at runtime it returns `None`. An OS value on Unix-like systems is any series of bytes, - /// regardless of whether or not they contain valid UTF-8 code points. Since [`String`]s in - /// Rust are guaranteed to be valid UTF-8, a valid filename on a Unix system as an argument - /// value may contain invalid UTF-8 code points. - /// - /// *NOTE:* If getting a value for an option or positional argument that allows multiples, - /// prefer [`ArgMatches::values_of_os`] as `Arg::value_of_os` will only return the *first* - /// value. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage("<arg> 'some arg'")) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi {0xe9}!" - /// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); - /// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); - /// ``` - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os - pub fn value_of_os<S: AsRef<str>>(&self, name: S) -> Option<&OsStr> { - self.args - .get(name.as_ref()) - .and_then(|arg| arg.vals.get(0).map(|v| v.as_os_str())) - } - - /// Gets a [`Values`] struct which implements [`Iterator`] for values of a specific argument - /// (i.e. an argument that takes multiple values at runtime). If the option wasn't present at - /// runtime it returns `None` - /// - /// # Panics - /// - /// This method will panic if any of the values contain invalid UTF-8 code points. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("output") - /// .multiple(true) - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec![ - /// "myprog", "-o", "val1", "val2", "val3" - /// ]); - /// let vals: Vec<&str> = m.values_of("output").unwrap().collect(); - /// assert_eq!(vals, ["val1", "val2", "val3"]); - /// ``` - /// [`Values`]: ./struct.Values.html - /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html - pub fn values_of<S: AsRef<str>>(&'a self, name: S) -> Option<Values<'a>> { - if let Some(arg) = self.args.get(name.as_ref()) { - fn to_str_slice(o: &OsString) -> &str { o.to_str().expect(INVALID_UTF8) } - let to_str_slice: fn(&OsString) -> &str = to_str_slice; // coerce to fn pointer - return Some(Values { - iter: arg.vals.iter().map(to_str_slice), - }); - } - None - } - - /// Gets the lossy values of a specific argument. If the option wasn't present at runtime - /// it returns `None`. A lossy value is one where if it contains invalid UTF-8 code points, - /// those invalid points will be replaced with `\u{FFFD}` - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::OsString; - /// use std::os::unix::ffi::OsStringExt; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage("<arg>... 'some arg'")) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi" - /// OsString::from_vec(vec![b'H', b'i']), - /// // "{0xe9}!" - /// OsString::from_vec(vec![0xe9, b'!'])]); - /// let mut itr = m.values_of_lossy("arg").unwrap().into_iter(); - /// assert_eq!(&itr.next().unwrap()[..], "Hi"); - /// assert_eq!(&itr.next().unwrap()[..], "\u{FFFD}!"); - /// assert_eq!(itr.next(), None); - /// ``` - pub fn values_of_lossy<S: AsRef<str>>(&'a self, name: S) -> Option<Vec<String>> { - if let Some(arg) = self.args.get(name.as_ref()) { - return Some( - arg.vals - .iter() - .map(|v| v.to_string_lossy().into_owned()) - .collect(), - ); - } - None - } - - /// Gets a [`OsValues`] struct which is implements [`Iterator`] for [`OsString`] values of a - /// specific argument. If the option wasn't present at runtime it returns `None`. An OS value - /// on Unix-like systems is any series of bytes, regardless of whether or not they contain - /// valid UTF-8 code points. Since [`String`]s in Rust are guaranteed to be valid UTF-8, a valid - /// filename as an argument value on Linux (for example) may contain invalid UTF-8 code points. - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg}; - /// use std::ffi::{OsStr,OsString}; - /// use std::os::unix::ffi::{OsStrExt,OsStringExt}; - /// - /// let m = App::new("utf8") - /// .arg(Arg::from_usage("<arg>... 'some arg'")) - /// .get_matches_from(vec![OsString::from("myprog"), - /// // "Hi" - /// OsString::from_vec(vec![b'H', b'i']), - /// // "{0xe9}!" - /// OsString::from_vec(vec![0xe9, b'!'])]); - /// - /// let mut itr = m.values_of_os("arg").unwrap().into_iter(); - /// assert_eq!(itr.next(), Some(OsStr::new("Hi"))); - /// assert_eq!(itr.next(), Some(OsStr::from_bytes(&[0xe9, b'!']))); - /// assert_eq!(itr.next(), None); - /// ``` - /// [`OsValues`]: ./struct.OsValues.html - /// [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html - /// [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - pub fn values_of_os<S: AsRef<str>>(&'a self, name: S) -> Option<OsValues<'a>> { - fn to_str_slice(o: &OsString) -> &OsStr { &*o } - let to_str_slice: fn(&'a OsString) -> &'a OsStr = to_str_slice; // coerce to fn pointer - if let Some(arg) = self.args.get(name.as_ref()) { - return Some(OsValues { - iter: arg.vals.iter().map(to_str_slice), - }); - } - None - } - - /// Returns `true` if an argument was present at runtime, otherwise `false`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .get_matches_from(vec![ - /// "myprog", "-d" - /// ]); - /// - /// assert!(m.is_present("debug")); - /// ``` - pub fn is_present<S: AsRef<str>>(&self, name: S) -> bool { - if let Some(ref sc) = self.subcommand { - if sc.name == name.as_ref() { - return true; - } - } - self.args.contains_key(name.as_ref()) - } - - /// Returns the number of times an argument was used at runtime. If an argument isn't present - /// it will return `0`. - /// - /// **NOTE:** This returns the number of times the argument was used, *not* the number of - /// values. For example, `-o val1 val2 val3 -o val4` would return `2` (2 occurrences, but 4 - /// values). - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d") - /// .multiple(true)) - /// .get_matches_from(vec![ - /// "myprog", "-d", "-d", "-d" - /// ]); - /// - /// assert_eq!(m.occurrences_of("debug"), 3); - /// ``` - /// - /// This next example shows that counts actual uses of the argument, not just `-`'s - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d") - /// .multiple(true)) - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .get_matches_from(vec![ - /// "myprog", "-ddfd" - /// ]); - /// - /// assert_eq!(m.occurrences_of("debug"), 3); - /// assert_eq!(m.occurrences_of("flag"), 1); - /// ``` - pub fn occurrences_of<S: AsRef<str>>(&self, name: S) -> u64 { - self.args.get(name.as_ref()).map_or(0, |a| a.occurs) - } - - /// Gets the starting index of the argument in respect to all other arguments. Indices are - /// similar to argv indices, but are not exactly 1:1. - /// - /// For flags (i.e. those arguments which don't have an associated value), indices refer - /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices - /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the - /// index for `val` would be recorded. This is by design. - /// - /// Besides the flag/option descrepancy, the primary difference between an argv index and clap - /// index, is that clap continues counting once all arguments have properly seperated, whereas - /// an argv index does not. - /// - /// The examples should clear this up. - /// - /// *NOTE:* If an argument is allowed multiple times, this method will only give the *first* - /// index. - /// - /// # Examples - /// - /// The argv indices are listed in the comments below. See how they correspond to the clap - /// indices. Note that if it's not listed in a clap index, this is becuase it's not saved in - /// in an `ArgMatches` struct for querying. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-f", "-o", "val"]); - /// // ARGV idices: ^0 ^1 ^2 ^3 - /// // clap idices: ^1 ^3 - /// - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("option"), Some(3)); - /// ``` - /// - /// Now notice, if we use one of the other styles of options: - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-f", "-o=val"]); - /// // ARGV idices: ^0 ^1 ^2 - /// // clap idices: ^1 ^3 - /// - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("option"), Some(3)); - /// ``` - /// - /// Things become much more complicated, or clear if we look at a more complex combination of - /// flags. Let's also throw in the final option style for good measure. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("flag2") - /// .short("F")) - /// .arg(Arg::with_name("flag3") - /// .short("z")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true)) - /// .get_matches_from(vec!["myapp", "-fzF", "-oval"]); - /// // ARGV idices: ^0 ^1 ^2 - /// // clap idices: ^1,2,3 ^5 - /// // - /// // clap sees the above as 'myapp -f -z -F -o val' - /// // ^0 ^1 ^2 ^3 ^4 ^5 - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("flag2"), Some(3)); - /// assert_eq!(m.index_of("flag3"), Some(2)); - /// assert_eq!(m.index_of("option"), Some(5)); - /// ``` - /// - /// One final combination of flags/options to see how they combine: - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("flag2") - /// .short("F")) - /// .arg(Arg::with_name("flag3") - /// .short("z")) - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-fzFoval"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^1,2,3^5 - /// // - /// // clap sees the above as 'myapp -f -z -F -o val' - /// // ^0 ^1 ^2 ^3 ^4 ^5 - /// assert_eq!(m.index_of("flag"), Some(1)); - /// assert_eq!(m.index_of("flag2"), Some(3)); - /// assert_eq!(m.index_of("flag3"), Some(2)); - /// assert_eq!(m.index_of("option"), Some(5)); - /// ``` - /// - /// The last part to mention is when values are sent in multiple groups with a [delimiter]. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^2 ^3 ^4 - /// // - /// // clap sees the above as 'myapp -o val1 val2 val3' - /// // ^0 ^1 ^2 ^3 ^4 - /// assert_eq!(m.index_of("option"), Some(2)); - /// ``` - /// [`ArgMatches`]: ./struct.ArgMatches.html - /// [delimiter]: ./struct.Arg.html#method.value_delimiter - pub fn index_of<S: AsRef<str>>(&self, name: S) -> Option<usize> { - if let Some(arg) = self.args.get(name.as_ref()) { - if let Some(i) = arg.indices.get(0) { - return Some(*i); - } - } - None - } - - /// Gets all indices of the argument in respect to all other arguments. Indices are - /// similar to argv indices, but are not exactly 1:1. - /// - /// For flags (i.e. those arguments which don't have an associated value), indices refer - /// to occurrence of the switch, such as `-f`, or `--flag`. However, for options the indices - /// refer to the *values* `-o val` would therefore not represent two distinct indices, only the - /// index for `val` would be recorded. This is by design. - /// - /// *NOTE:* For more information about how clap indices compare to argv indices, see - /// [`ArgMatches::index_of`] - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .use_delimiter(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^2 ^3 ^4 - /// // - /// // clap sees the above as 'myapp -o val1 val2 val3' - /// // ^0 ^1 ^2 ^3 ^4 - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 3, 4]); - /// ``` - /// - /// Another quick example is when flags and options are used together - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .arg(Arg::with_name("flag") - /// .short("f") - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o", "val1", "-f", "-o", "val2", "-f"]); - /// // ARGV idices: ^0 ^1 ^2 ^3 ^4 ^5 ^6 - /// // clap idices: ^2 ^3 ^5 ^6 - /// - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2, 5]); - /// assert_eq!(m.indices_of("flag").unwrap().collect::<Vec<_>>(), &[3, 6]); - /// ``` - /// - /// One final example, which is an odd case; if we *don't* use value delimiter as we did with - /// the first example above instead of `val1`, `val2` and `val3` all being distinc values, they - /// would all be a single value of `val1,val2,val3`, in which case case they'd only receive a - /// single index. - /// - /// ```rust - /// # use clap::{App, Arg}; - /// let m = App::new("myapp") - /// .arg(Arg::with_name("option") - /// .short("o") - /// .takes_value(true) - /// .multiple(true)) - /// .get_matches_from(vec!["myapp", "-o=val1,val2,val3"]); - /// // ARGV idices: ^0 ^1 - /// // clap idices: ^2 - /// // - /// // clap sees the above as 'myapp -o "val1,val2,val3"' - /// // ^0 ^1 ^2 - /// assert_eq!(m.indices_of("option").unwrap().collect::<Vec<_>>(), &[2]); - /// ``` - /// [`ArgMatches`]: ./struct.ArgMatches.html - /// [`ArgMatches::index_of`]: ./struct.ArgMatches.html#method.index_of - /// [delimiter]: ./struct.Arg.html#method.value_delimiter - pub fn indices_of<S: AsRef<str>>(&'a self, name: S) -> Option<Indices<'a>> { - if let Some(arg) = self.args.get(name.as_ref()) { - fn to_usize(i: &usize) -> usize { *i } - let to_usize: fn(&usize) -> usize = to_usize; // coerce to fn pointer - return Some(Indices { - iter: arg.indices.iter().map(to_usize), - }); - } - None - } - - /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`] - /// as well. This method returns the [`ArgMatches`] for a particular subcommand or `None` if - /// the subcommand wasn't present at runtime. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("myprog") - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .subcommand(SubCommand::with_name("test") - /// .arg(Arg::with_name("opt") - /// .long("option") - /// .takes_value(true))) - /// .get_matches_from(vec![ - /// "myprog", "-d", "test", "--option", "val" - /// ]); - /// - /// // Both parent commands, and child subcommands can have arguments present at the same times - /// assert!(app_m.is_present("debug")); - /// - /// // Get the subcommand's ArgMatches instance - /// if let Some(sub_m) = app_m.subcommand_matches("test") { - /// // Use the struct like normal - /// assert_eq!(sub_m.value_of("opt"), Some("val")); - /// } - /// ``` - /// [`Subcommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - /// [`ArgMatches`]: ./struct.ArgMatches.html - pub fn subcommand_matches<S: AsRef<str>>(&self, name: S) -> Option<&ArgMatches<'a>> { - if let Some(ref s) = self.subcommand { - if s.name == name.as_ref() { - return Some(&s.matches); - } - } - None - } - - /// Because [`Subcommand`]s are essentially "sub-[`App`]s" they have their own [`ArgMatches`] - /// as well.But simply getting the sub-[`ArgMatches`] doesn't help much if we don't also know - /// which subcommand was actually used. This method returns the name of the subcommand that was - /// used at runtime, or `None` if one wasn't. - /// - /// *NOTE*: Subcommands form a hierarchy, where multiple subcommands can be used at runtime, - /// but only a single subcommand from any group of sibling commands may used at once. - /// - /// An ASCII art depiction may help explain this better...Using a fictional version of `git` as - /// the demo subject. Imagine the following are all subcommands of `git` (note, the author is - /// aware these aren't actually all subcommands in the real `git` interface, but it makes - /// explanation easier) - /// - /// ```notrust - /// Top Level App (git) TOP - /// | - /// ----------------------------------------- - /// / | \ \ - /// clone push add commit LEVEL 1 - /// | / \ / \ | - /// url origin remote ref name message LEVEL 2 - /// / /\ - /// path remote local LEVEL 3 - /// ``` - /// - /// Given the above fictional subcommand hierarchy, valid runtime uses would be (not an all - /// inclusive list, and not including argument options per command for brevity and clarity): - /// - /// ```sh - /// $ git clone url - /// $ git push origin path - /// $ git add ref local - /// $ git commit message - /// ``` - /// - /// Notice only one command per "level" may be used. You could not, for example, do `$ git - /// clone url push origin path` - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("git") - /// .subcommand(SubCommand::with_name("clone")) - /// .subcommand(SubCommand::with_name("push")) - /// .subcommand(SubCommand::with_name("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand_name() { - /// Some("clone") => {}, // clone was used - /// Some("push") => {}, // push was used - /// Some("commit") => {}, // commit was used - /// _ => {}, // Either no subcommand or one not tested for... - /// } - /// ``` - /// [`Subcommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - /// [`ArgMatches`]: ./struct.ArgMatches.html - pub fn subcommand_name(&self) -> Option<&str> { - self.subcommand.as_ref().map(|sc| &sc.name[..]) - } - - /// This brings together [`ArgMatches::subcommand_matches`] and [`ArgMatches::subcommand_name`] - /// by returning a tuple with both pieces of information. - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("git") - /// .subcommand(SubCommand::with_name("clone")) - /// .subcommand(SubCommand::with_name("push")) - /// .subcommand(SubCommand::with_name("commit")) - /// .get_matches(); - /// - /// match app_m.subcommand() { - /// ("clone", Some(sub_m)) => {}, // clone was used - /// ("push", Some(sub_m)) => {}, // push was used - /// ("commit", Some(sub_m)) => {}, // commit was used - /// _ => {}, // Either no subcommand or one not tested for... - /// } - /// ``` - /// - /// Another useful scenario is when you want to support third party, or external, subcommands. - /// In these cases you can't know the subcommand name ahead of time, so use a variable instead - /// with pattern matching! - /// - /// ```rust - /// # use clap::{App, AppSettings}; - /// // Assume there is an external subcommand named "subcmd" - /// let app_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 app_m.subcommand() { - /// (external, Some(sub_m)) => { - /// let ext_args: Vec<&str> = sub_m.values_of("").unwrap().collect(); - /// assert_eq!(external, "subcmd"); - /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]); - /// }, - /// _ => {}, - /// } - /// ``` - /// [`ArgMatches::subcommand_matches`]: ./struct.ArgMatches.html#method.subcommand_matches - /// [`ArgMatches::subcommand_name`]: ./struct.ArgMatches.html#method.subcommand_name - pub fn subcommand(&self) -> (&str, Option<&ArgMatches<'a>>) { - self.subcommand - .as_ref() - .map_or(("", None), |sc| (&sc.name[..], Some(&sc.matches))) - } - - /// Returns a string slice of the usage statement for the [`App`] or [`SubCommand`] - /// - /// # Examples - /// - /// ```no_run - /// # use clap::{App, Arg, SubCommand}; - /// let app_m = App::new("myprog") - /// .subcommand(SubCommand::with_name("test")) - /// .get_matches(); - /// - /// println!("{}", app_m.usage()); - /// ``` - /// [`Subcommand`]: ./struct.SubCommand.html - /// [`App`]: ./struct.App.html - pub fn usage(&self) -> &str { self.usage.as_ref().map_or("", |u| &u[..]) } -} - - -// The following were taken and adapated from vec_map source -// repo: https://github.com/contain-rs/vec-map -// commit: be5e1fa3c26e351761b33010ddbdaf5f05dbcc33 -// license: MIT - Copyright (c) 2015 The Rust Project Developers - -/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of`] -/// method. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{App, Arg}; -/// let m = App::new("myapp") -/// .arg(Arg::with_name("output") -/// .short("o") -/// .multiple(true) -/// .takes_value(true)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); -/// -/// let mut values = m.values_of("output").unwrap(); -/// -/// assert_eq!(values.next(), Some("val1")); -/// assert_eq!(values.next(), Some("val2")); -/// assert_eq!(values.next(), None); -/// ``` -/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of -#[derive(Debug, Clone)] -pub struct Values<'a> { - iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a str>, -} - -impl<'a> Iterator for Values<'a> { - type Item = &'a str; - - fn next(&mut self) -> Option<&'a str> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } -} - -impl<'a> DoubleEndedIterator for Values<'a> { - fn next_back(&mut self) -> Option<&'a str> { self.iter.next_back() } -} - -impl<'a> ExactSizeIterator for Values<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for Values<'a> { - fn default() -> Self { - static EMPTY: [OsString; 0] = []; - // This is never called because the iterator is empty: - fn to_str_slice(_: &OsString) -> &str { unreachable!() }; - Values { - iter: EMPTY[..].iter().map(to_str_slice), - } - } -} - -/// An iterator for getting multiple values out of an argument via the [`ArgMatches::values_of_os`] -/// method. Usage of this iterator allows values which contain invalid UTF-8 code points unlike -/// [`Values`]. -/// -/// # Examples -/// -#[cfg_attr(not(unix), doc = " ```ignore")] -#[cfg_attr(unix, doc = " ```")] -/// # use clap::{App, Arg}; -/// use std::ffi::OsString; -/// use std::os::unix::ffi::{OsStrExt,OsStringExt}; -/// -/// let m = App::new("utf8") -/// .arg(Arg::from_usage("<arg> 'some arg'")) -/// .get_matches_from(vec![OsString::from("myprog"), -/// // "Hi {0xe9}!" -/// OsString::from_vec(vec![b'H', b'i', b' ', 0xe9, b'!'])]); -/// assert_eq!(&*m.value_of_os("arg").unwrap().as_bytes(), [b'H', b'i', b' ', 0xe9, b'!']); -/// ``` -/// [`ArgMatches::values_of_os`]: ./struct.ArgMatches.html#method.values_of_os -/// [`Values`]: ./struct.Values.html -#[derive(Debug, Clone)] -pub struct OsValues<'a> { - iter: Map<Iter<'a, OsString>, fn(&'a OsString) -> &'a OsStr>, -} - -impl<'a> Iterator for OsValues<'a> { - type Item = &'a OsStr; - - fn next(&mut self) -> Option<&'a OsStr> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } -} - -impl<'a> DoubleEndedIterator for OsValues<'a> { - fn next_back(&mut self) -> Option<&'a OsStr> { self.iter.next_back() } -} - -impl<'a> ExactSizeIterator for OsValues<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for OsValues<'a> { - fn default() -> Self { - static EMPTY: [OsString; 0] = []; - // This is never called because the iterator is empty: - fn to_str_slice(_: &OsString) -> &OsStr { unreachable!() }; - OsValues { - iter: EMPTY[..].iter().map(to_str_slice), - } - } -} - -/// An iterator for getting multiple indices out of an argument via the [`ArgMatches::indices_of`] -/// method. -/// -/// # Examples -/// -/// ```rust -/// # use clap::{App, Arg}; -/// let m = App::new("myapp") -/// .arg(Arg::with_name("output") -/// .short("o") -/// .multiple(true) -/// .takes_value(true)) -/// .get_matches_from(vec!["myapp", "-o", "val1", "val2"]); -/// -/// let mut indices = m.indices_of("output").unwrap(); -/// -/// assert_eq!(indices.next(), Some(2)); -/// assert_eq!(indices.next(), Some(3)); -/// assert_eq!(indices.next(), None); -/// ``` -/// [`ArgMatches::indices_of`]: ./struct.ArgMatches.html#method.indices_of -#[derive(Debug, Clone)] -pub struct Indices<'a> { // would rather use '_, but: https://github.com/rust-lang/rust/issues/48469 - iter: Map<Iter<'a, usize>, fn(&'a usize) -> usize>, -} - -impl<'a> Iterator for Indices<'a> { - type Item = usize; - - fn next(&mut self) -> Option<usize> { self.iter.next() } - fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } -} - -impl<'a> DoubleEndedIterator for Indices<'a> { - fn next_back(&mut self) -> Option<usize> { self.iter.next_back() } -} - -impl<'a> ExactSizeIterator for Indices<'a> {} - -/// Creates an empty iterator. -impl<'a> Default for Indices<'a> { - fn default() -> Self { - static EMPTY: [usize; 0] = []; - // This is never called because the iterator is empty: - fn to_usize(_: &usize) -> usize { unreachable!() }; - Indices { - iter: EMPTY[..].iter().map(to_usize), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_default_values() { - let mut values: Values = Values::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_values_with_shorter_lifetime() { - let matches = ArgMatches::new(); - let mut values = matches.values_of("").unwrap_or_default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_osvalues() { - let mut values: OsValues = OsValues::default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_osvalues_with_shorter_lifetime() { - let matches = ArgMatches::new(); - let mut values = matches.values_of_os("").unwrap_or_default(); - assert_eq!(values.next(), None); - } - - #[test] - fn test_default_indices() { - let mut indices: Indices = Indices::default(); - assert_eq!(indices.next(), None); - } - - #[test] - fn test_default_indices_with_shorter_lifetime() { - let matches = ArgMatches::new(); - let mut indices = matches.indices_of("").unwrap_or_default(); - assert_eq!(indices.next(), None); - } -} diff --git a/clap/src/args/group.rs b/clap/src/args/group.rs deleted file mode 100644 index f8bfb7a..0000000 --- a/clap/src/args/group.rs +++ /dev/null @@ -1,635 +0,0 @@ -#[cfg(feature = "yaml")] -use std::collections::BTreeMap; -use std::fmt::{Debug, Formatter, Result}; - -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -/// `ArgGroup`s are a family of related [arguments] and way for you to express, "Any of these -/// arguments". By placing arguments in a logical group, you can create easier requirement and -/// exclusion rules instead of having to list each argument individually, or when you want a rule -/// to apply "any but not all" arguments. -/// -/// For instance, you can make an entire `ArgGroup` required. If [`ArgGroup::multiple(true)`] is -/// set, this means that at least one argument from that group must be present. If -/// [`ArgGroup::multiple(false)`] is set (the default), one and *only* one must be present. -/// -/// You can also do things such as name an entire `ArgGroup` as a [conflict] or [requirement] for -/// another argument, meaning any of the arguments that belong to that group will cause a failure -/// if present, or must present respectively. -/// -/// Perhaps the most common use of `ArgGroup`s is to require one and *only* one argument to be -/// present out of a given set. Imagine that you had multiple arguments, and you want one of them -/// to be required, but making all of them required isn't feasible because perhaps they conflict -/// with each other. For example, lets say that you were building an application where one could -/// set a given version number by supplying a string with an option argument, i.e. -/// `--set-ver v1.2.3`, you also wanted to support automatically using a previous version number -/// and simply incrementing one of the three numbers. So you create three flags `--major`, -/// `--minor`, and `--patch`. All of these arguments shouldn't be used at one time but you want to -/// specify that *at least one* of them is used. For this, you can create a group. -/// -/// Finally, you may use `ArgGroup`s to pull a value from a group of arguments when you don't care -/// exactly which argument was actually used at runtime. -/// -/// # 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. -/// -/// ```rust -/// # use clap::{App, ArgGroup, ErrorKind}; -/// let result = 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)) -/// .get_matches_from_safe(vec!["app", "--major", "--patch"]); -/// // Because we used two args in the group it's an error -/// assert!(result.is_err()); -/// let err = result.unwrap_err(); -/// assert_eq!(err.kind, ErrorKind::ArgumentConflict); -/// ``` -/// This next example shows a passing parse of the same scenario -/// -/// ```rust -/// # use clap::{App, ArgGroup}; -/// let result = 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)) -/// .get_matches_from_safe(vec!["app", "--major"]); -/// assert!(result.is_ok()); -/// let matches = result.unwrap(); -/// // We may not know which of the args was used, so we can test for the group... -/// assert!(matches.is_present("vers")); -/// // we could also alternatively check each arg individually (not shown here) -/// ``` -/// [`ArgGroup::multiple(true)`]: ./struct.ArgGroup.html#method.multiple -/// [arguments]: ./struct.Arg.html -/// [conflict]: ./struct.Arg.html#method.conflicts_with -/// [requirement]: ./struct.Arg.html#method.requires -#[derive(Default)] -pub struct ArgGroup<'a> { - #[doc(hidden)] pub name: &'a str, - #[doc(hidden)] pub args: Vec<&'a str>, - #[doc(hidden)] pub required: bool, - #[doc(hidden)] pub requires: Option<Vec<&'a str>>, - #[doc(hidden)] pub conflicts: Option<Vec<&'a str>>, - #[doc(hidden)] pub multiple: bool, -} - -impl<'a> ArgGroup<'a> { - /// Creates a new instance of `ArgGroup` using a unique string name. The name will be used to - /// get values from the group or refer to the group inside of conflict and requirement rules. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, ArgGroup}; - /// ArgGroup::with_name("config") - /// # ; - /// ``` - pub fn with_name(n: &'a str) -> Self { - ArgGroup { - name: n, - required: false, - args: vec![], - requires: None, - conflicts: None, - multiple: false, - } - } - - /// Creates a new instance of `ArgGroup` from a .yml (YAML) file. - /// - /// # Examples - /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::ArgGroup; - /// # fn main() { - /// let yml = load_yaml!("group.yml"); - /// let ag = ArgGroup::from_yaml(yml); - /// # } - /// ``` - #[cfg(feature = "yaml")] - pub fn from_yaml(y: &'a Yaml) -> ArgGroup<'a> { ArgGroup::from(y.as_hash().unwrap()) } - - /// Adds an [argument] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") - /// .arg("flag") - /// .arg("color")) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.is_present("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.is_present("flag")); - /// ``` - /// [argument]: ./struct.Arg.html - #[cfg_attr(feature = "lints", allow(should_assert_eq))] - pub fn arg(mut self, n: &'a str) -> Self { - assert!( - self.name != n, - "ArgGroup '{}' can not have same name as arg inside it", - &*self.name - ); - self.args.push(n); - self - } - - /// Adds multiple [arguments] to this group by name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"])) - /// .get_matches_from(vec!["myprog", "-f"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.is_present("req_flags")); - /// // but we can also check individually if needed - /// assert!(m.is_present("flag")); - /// ``` - /// [arguments]: ./struct.Arg.html - pub fn args(mut self, ns: &[&'a str]) -> Self { - for n in ns { - self = self.arg(n); - } - self - } - - /// Allows more than one of the ['Arg']s in this group to be used. (Default: `false`) - /// - /// # Examples - /// - /// Notice in this example we use *both* the `-f` and `-c` flags which are both part of the - /// group - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup}; - /// let m = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"]) - /// .multiple(true)) - /// .get_matches_from(vec!["myprog", "-f", "-c"]); - /// // maybe we don't know which of the two flags was used... - /// assert!(m.is_present("req_flags")); - /// ``` - /// In this next example, we show the default behavior (i.e. `multiple(false)) which will throw - /// an error if more than one of the args in the group was used. - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup, ErrorKind}; - /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"])) - /// .get_matches_from_safe(vec!["myprog", "-f", "-c"]); - /// // Because we used both args in the group it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::ArgumentConflict); - /// ``` - /// ['Arg']: ./struct.Arg.html - pub fn multiple(mut self, m: bool) -> Self { - self.multiple = m; - self - } - - /// Sets the group as required or not. A required group will be displayed in the usage string - /// of the application in the format `<arg|arg2|arg3>`. A required `ArgGroup` simply states - /// that one argument from this group *must* be present at runtime (unless - /// conflicting with another argument). - /// - /// **NOTE:** This setting only applies to the current [`App`] / [`SubCommand`], and not - /// globally. - /// - /// **NOTE:** By default, [`ArgGroup::multiple`] is set to `false` which when combined with - /// `ArgGroup::required(true)` states, "One and *only one* arg must be used from this group. - /// Use of more than one arg is an error." Vice setting `ArgGroup::multiple(true)` which - /// states, '*At least* one arg from this group must be used. Using multiple is OK." - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup, ErrorKind}; - /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"]) - /// .required(true)) - /// .get_matches_from_safe(vec!["myprog"]); - /// // Because we didn't use any of the args in the group, it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [`App`]: ./struct.App.html - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`ArgGroup::multiple`]: ./struct.ArgGroup.html#method.multiple - pub fn required(mut self, r: bool) -> Self { - self.required = r; - self - } - - /// Sets the requirement rules of this group. This is not to be confused with a - /// [required group]. Requirement rules function just like [argument requirement rules], you - /// can name other arguments or groups that must be present when any one of the arguments from - /// this group is used. - /// - /// **NOTE:** The name provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup, ErrorKind}; - /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"]) - /// .requires("debug")) - /// .get_matches_from_safe(vec!["myprog", "-c"]); - /// // because we used an arg from the group, and the group requires "-d" to be used, it's an - /// // error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ./struct.ArgGroup.html#method.required - /// [argument requirement rules]: ./struct.Arg.html#method.requires - pub fn requires(mut self, n: &'a str) -> Self { - if let Some(ref mut reqs) = self.requires { - reqs.push(n); - } else { - self.requires = Some(vec![n]); - } - self - } - - /// Sets the requirement rules of this group. This is not to be confused with a - /// [required group]. Requirement rules function just like [argument requirement rules], you - /// can name other arguments or groups that must be present when one of the arguments from this - /// group is used. - /// - /// **NOTE:** The names provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup, ErrorKind}; - /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .arg(Arg::with_name("verb") - /// .short("v")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"]) - /// .requires_all(&["debug", "verb"])) - /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group requires "-d" and "-v" to be used, - /// // yet we only used "-d" it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::MissingRequiredArgument); - /// ``` - /// [required group]: ./struct.ArgGroup.html#method.required - /// [argument requirement rules]: ./struct.Arg.html#method.requires_all - pub fn requires_all(mut self, ns: &[&'a str]) -> Self { - for n in ns { - self = self.requires(n); - } - self - } - - /// Sets the exclusion rules of this group. Exclusion (aka conflict) rules function just like - /// [argument exclusion rules], you can name other arguments or groups that must *not* be - /// present when one of the arguments from this group are used. - /// - /// **NOTE:** The name provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup, ErrorKind}; - /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"]) - /// .conflicts_with("debug")) - /// .get_matches_from_safe(vec!["myprog", "-c", "-d"]); - /// // because we used an arg from the group, and the group conflicts with "-d", it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::ArgumentConflict); - /// ``` - /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with - pub fn conflicts_with(mut self, n: &'a str) -> Self { - if let Some(ref mut confs) = self.conflicts { - confs.push(n); - } else { - self.conflicts = Some(vec![n]); - } - self - } - - /// Sets the exclusion rules of this group. Exclusion rules function just like - /// [argument exclusion rules], you can name other arguments or groups that must *not* be - /// present when one of the arguments from this group are used. - /// - /// **NOTE:** The names provided may be an argument, or group name - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ArgGroup, ErrorKind}; - /// let result = App::new("myprog") - /// .arg(Arg::with_name("flag") - /// .short("f")) - /// .arg(Arg::with_name("color") - /// .short("c")) - /// .arg(Arg::with_name("debug") - /// .short("d")) - /// .arg(Arg::with_name("verb") - /// .short("v")) - /// .group(ArgGroup::with_name("req_flags") - /// .args(&["flag", "color"]) - /// .conflicts_with_all(&["debug", "verb"])) - /// .get_matches_from_safe(vec!["myprog", "-c", "-v"]); - /// // because we used an arg from the group, and the group conflicts with either "-v" or "-d" - /// // it's an error - /// assert!(result.is_err()); - /// let err = result.unwrap_err(); - /// assert_eq!(err.kind, ErrorKind::ArgumentConflict); - /// ``` - /// [argument exclusion rules]: ./struct.Arg.html#method.conflicts_with_all - pub fn conflicts_with_all(mut self, ns: &[&'a str]) -> Self { - for n in ns { - self = self.conflicts_with(n); - } - self - } -} - -impl<'a> Debug for ArgGroup<'a> { - fn fmt(&self, f: &mut Formatter) -> Result { - write!( - f, - "{{\n\ - \tname: {:?},\n\ - \targs: {:?},\n\ - \trequired: {:?},\n\ - \trequires: {:?},\n\ - \tconflicts: {:?},\n\ - }}", - self.name, - self.args, - self.required, - self.requires, - self.conflicts - ) - } -} - -impl<'a, 'z> From<&'z ArgGroup<'a>> for ArgGroup<'a> { - fn from(g: &'z ArgGroup<'a>) -> Self { - ArgGroup { - name: g.name, - required: g.required, - args: g.args.clone(), - requires: g.requires.clone(), - conflicts: g.conflicts.clone(), - multiple: g.multiple, - } - } -} - -#[cfg(feature = "yaml")] -impl<'a> From<&'a BTreeMap<Yaml, Yaml>> for ArgGroup<'a> { - fn from(b: &'a BTreeMap<Yaml, Yaml>) -> Self { - // We WANT this to panic on error...so expect() is good. - let mut a = ArgGroup::default(); - let group_settings = if b.len() == 1 { - let name_yml = b.keys().nth(0).expect("failed to get name"); - let name_str = name_yml - .as_str() - .expect("failed to convert arg YAML name to str"); - a.name = name_str; - b.get(name_yml) - .expect("failed to get name_str") - .as_hash() - .expect("failed to convert to a hash") - } else { - b - }; - - for (k, v) in group_settings { - a = match k.as_str().unwrap() { - "required" => a.required(v.as_bool().unwrap()), - "multiple" => a.multiple(v.as_bool().unwrap()), - "args" => yaml_vec_or_str!(v, a, arg), - "arg" => { - if let Some(ys) = v.as_str() { - a = a.arg(ys); - } - a - } - "requires" => yaml_vec_or_str!(v, a, requires), - "conflicts_with" => yaml_vec_or_str!(v, a, conflicts_with), - "name" => { - if let Some(ys) = v.as_str() { - a.name = ys; - } - a - } - s => panic!( - "Unknown ArgGroup setting '{}' in YAML file for \ - ArgGroup '{}'", - s, - a.name - ), - } - } - - a - } -} - -#[cfg(test)] -mod test { - use super::ArgGroup; - #[cfg(feature = "yaml")] - use yaml_rust::YamlLoader; - - #[test] - fn groups() { - let g = ArgGroup::with_name("test") - .arg("a1") - .arg("a4") - .args(&["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(&["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(&["r2", "r3"]) - .requires("r4"); - - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; - - assert_eq!(g.args, args); - assert_eq!(g.requires, Some(reqs)); - assert_eq!(g.conflicts, Some(confs)); - } - - #[test] - fn test_debug() { - let g = ArgGroup::with_name("test") - .arg("a1") - .arg("a4") - .args(&["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(&["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(&["r2", "r3"]) - .requires("r4"); - - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; - - let debug_str = format!( - "{{\n\ - \tname: \"test\",\n\ - \targs: {:?},\n\ - \trequired: {:?},\n\ - \trequires: {:?},\n\ - \tconflicts: {:?},\n\ - }}", - args, - true, - Some(reqs), - Some(confs) - ); - assert_eq!(&*format!("{:?}", g), &*debug_str); - } - - #[test] - fn test_from() { - let g = ArgGroup::with_name("test") - .arg("a1") - .arg("a4") - .args(&["a2", "a3"]) - .required(true) - .conflicts_with("c1") - .conflicts_with_all(&["c2", "c3"]) - .conflicts_with("c4") - .requires("r1") - .requires_all(&["r2", "r3"]) - .requires("r4"); - - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; - - let g2 = ArgGroup::from(&g); - assert_eq!(g2.args, args); - assert_eq!(g2.requires, Some(reqs)); - assert_eq!(g2.conflicts, Some(confs)); - } - - #[cfg(feature = "yaml")] - #[cfg_attr(feature = "yaml", test)] - fn test_yaml() { - let g_yaml = "name: test -args: -- a1 -- a4 -- a2 -- a3 -conflicts_with: -- c1 -- c2 -- c3 -- c4 -requires: -- r1 -- r2 -- r3 -- r4"; - let yml = &YamlLoader::load_from_str(g_yaml).expect("failed to load YAML file")[0]; - let g = ArgGroup::from_yaml(yml); - let args = vec!["a1", "a4", "a2", "a3"]; - let reqs = vec!["r1", "r2", "r3", "r4"]; - let confs = vec!["c1", "c2", "c3", "c4"]; - assert_eq!(g.args, args); - assert_eq!(g.requires, Some(reqs)); - assert_eq!(g.conflicts, Some(confs)); - } -} - -impl<'a> Clone for ArgGroup<'a> { - fn clone(&self) -> Self { - ArgGroup { - name: self.name, - required: self.required, - args: self.args.clone(), - requires: self.requires.clone(), - conflicts: self.conflicts.clone(), - multiple: self.multiple, - } - } -} diff --git a/clap/src/args/macros.rs b/clap/src/args/macros.rs deleted file mode 100644 index 1de12f4..0000000 --- a/clap/src/args/macros.rs +++ /dev/null @@ -1,109 +0,0 @@ -#[cfg(feature = "yaml")] -macro_rules! yaml_tuple2 { - ($a:ident, $v:ident, $c:ident) => {{ - if let Some(vec) = $v.as_vec() { - for ys in vec { - if let Some(tup) = ys.as_vec() { - debug_assert_eq!(2, tup.len()); - $a = $a.$c(yaml_str!(tup[0]), yaml_str!(tup[1])); - } else { - panic!("Failed to convert YAML value to vec"); - } - } - } else { - panic!("Failed to convert YAML value to vec"); - } - $a - } - }; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_tuple3 { - ($a:ident, $v:ident, $c:ident) => {{ - if let Some(vec) = $v.as_vec() { - for ys in vec { - if let Some(tup) = ys.as_vec() { - debug_assert_eq!(3, tup.len()); - $a = $a.$c(yaml_str!(tup[0]), yaml_opt_str!(tup[1]), yaml_str!(tup[2])); - } else { - panic!("Failed to convert YAML value to vec"); - } - } - } else { - panic!("Failed to convert YAML value to vec"); - } - $a - } - }; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_vec_or_str { - ($v:ident, $a:ident, $c:ident) => {{ - let maybe_vec = $v.as_vec(); - if let Some(vec) = maybe_vec { - for ys in vec { - if let Some(s) = ys.as_str() { - $a = $a.$c(s); - } else { - panic!("Failed to convert YAML value {:?} to a string", ys); - } - } - } else { - if let Some(s) = $v.as_str() { - $a = $a.$c(s); - } else { - panic!("Failed to convert YAML value {:?} to either a vec or string", $v); - } - } - $a - } - }; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_opt_str { - ($v:expr) => {{ - if $v.is_null() { - Some($v.as_str().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) - } else { - None - } - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_str { - ($v:expr) => {{ - $v.as_str().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_str { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c(yaml_str!($v)) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_bool { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v.as_bool().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v))) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_u64 { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v.as_i64().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) as u64) - }}; -} - -#[cfg(feature = "yaml")] -macro_rules! yaml_to_usize { - ($a:ident, $v:ident, $c:ident) => {{ - $a.$c($v.as_i64().unwrap_or_else(|| panic!("failed to convert YAML {:?} value to a string", $v)) as usize) - }}; -} diff --git a/clap/src/args/matched_arg.rs b/clap/src/args/matched_arg.rs deleted file mode 100644 index eeda261..0000000 --- a/clap/src/args/matched_arg.rs +++ /dev/null @@ -1,24 +0,0 @@ -// Std -use std::ffi::OsString; - -#[doc(hidden)] -#[derive(Debug, Clone)] -pub struct MatchedArg { - #[doc(hidden)] pub occurs: u64, - #[doc(hidden)] pub indices: Vec<usize>, - #[doc(hidden)] pub vals: Vec<OsString>, -} - -impl Default for MatchedArg { - fn default() -> Self { - MatchedArg { - occurs: 1, - indices: Vec::new(), - vals: Vec::new(), - } - } -} - -impl MatchedArg { - pub fn new() -> Self { MatchedArg::default() } -} diff --git a/clap/src/args/mod.rs b/clap/src/args/mod.rs deleted file mode 100644 index 21f9b85..0000000 --- a/clap/src/args/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -pub use self::any_arg::{AnyArg, DispOrder}; -pub use self::arg::Arg; -pub use self::arg_builder::{Base, FlagBuilder, OptBuilder, PosBuilder, Switched, Valued}; -pub use self::arg_matcher::ArgMatcher; -pub use self::arg_matches::{ArgMatches, OsValues, Values}; -pub use self::group::ArgGroup; -pub use self::matched_arg::MatchedArg; -pub use self::settings::{ArgFlags, ArgSettings}; -pub use self::subcommand::SubCommand; - -#[macro_use] -mod macros; -mod arg; -pub mod any_arg; -mod arg_matches; -mod arg_matcher; -mod subcommand; -mod arg_builder; -mod matched_arg; -mod group; -pub mod settings; diff --git a/clap/src/args/settings.rs b/clap/src/args/settings.rs deleted file mode 100644 index 7b0e0a2..0000000 --- a/clap/src/args/settings.rs +++ /dev/null @@ -1,231 +0,0 @@ -// Std -#[allow(deprecated, unused_imports)] -use std::ascii::AsciiExt; -use std::str::FromStr; - -bitflags! { - struct Flags: u32 { - const REQUIRED = 1; - const MULTIPLE = 1 << 1; - const EMPTY_VALS = 1 << 2; - const GLOBAL = 1 << 3; - const HIDDEN = 1 << 4; - const TAKES_VAL = 1 << 5; - const USE_DELIM = 1 << 6; - const NEXT_LINE_HELP = 1 << 7; - const R_UNLESS_ALL = 1 << 8; - const REQ_DELIM = 1 << 9; - const DELIM_NOT_SET = 1 << 10; - const HIDE_POS_VALS = 1 << 11; - const ALLOW_TAC_VALS = 1 << 12; - const REQUIRE_EQUALS = 1 << 13; - const LAST = 1 << 14; - const HIDE_DEFAULT_VAL = 1 << 15; - const CASE_INSENSITIVE = 1 << 16; - const HIDE_ENV_VALS = 1 << 17; - const HIDDEN_SHORT_H = 1 << 18; - const HIDDEN_LONG_H = 1 << 19; - } -} - -#[doc(hidden)] -#[derive(Debug, Clone, Copy)] -pub struct ArgFlags(Flags); - -impl ArgFlags { - pub fn new() -> Self { ArgFlags::default() } - - impl_settings!{ArgSettings, - Required => Flags::REQUIRED, - Multiple => Flags::MULTIPLE, - EmptyValues => Flags::EMPTY_VALS, - Global => Flags::GLOBAL, - Hidden => Flags::HIDDEN, - TakesValue => Flags::TAKES_VAL, - UseValueDelimiter => Flags::USE_DELIM, - NextLineHelp => Flags::NEXT_LINE_HELP, - RequiredUnlessAll => Flags::R_UNLESS_ALL, - RequireDelimiter => Flags::REQ_DELIM, - ValueDelimiterNotSet => Flags::DELIM_NOT_SET, - HidePossibleValues => Flags::HIDE_POS_VALS, - AllowLeadingHyphen => Flags::ALLOW_TAC_VALS, - RequireEquals => Flags::REQUIRE_EQUALS, - Last => Flags::LAST, - CaseInsensitive => Flags::CASE_INSENSITIVE, - HideEnvValues => Flags::HIDE_ENV_VALS, - HideDefaultValue => Flags::HIDE_DEFAULT_VAL, - HiddenShortHelp => Flags::HIDDEN_SHORT_H, - HiddenLongHelp => Flags::HIDDEN_LONG_H - } -} - -impl Default for ArgFlags { - fn default() -> Self { ArgFlags(Flags::EMPTY_VALS | Flags::DELIM_NOT_SET) } -} - -/// Various settings that apply to arguments and may be set, unset, and checked via getter/setter -/// methods [`Arg::set`], [`Arg::unset`], and [`Arg::is_set`] -/// -/// [`Arg::set`]: ./struct.Arg.html#method.set -/// [`Arg::unset`]: ./struct.Arg.html#method.unset -/// [`Arg::is_set`]: ./struct.Arg.html#method.is_set -#[derive(Debug, PartialEq, Copy, Clone)] -pub enum ArgSettings { - /// The argument must be used - Required, - /// The argument may be used multiple times such as `--flag --flag` - Multiple, - /// The argument allows empty values such as `--option ""` - EmptyValues, - /// The argument should be propagated down through all child [`SubCommand`]s - /// - /// [`SubCommand`]: ./struct.SubCommand.html - Global, - /// The argument should **not** be shown in help text - Hidden, - /// The argument accepts a value, such as `--option <value>` - TakesValue, - /// Determines if the argument allows values to be grouped via a delimiter - UseValueDelimiter, - /// Prints the help text on the line after the argument - NextLineHelp, - /// Requires the use of a value delimiter for all multiple values - RequireDelimiter, - /// Hides the possible values from the help string - HidePossibleValues, - /// Allows vals that start with a '-' - AllowLeadingHyphen, - /// Require options use `--option=val` syntax - RequireEquals, - /// Specifies that the arg is the last positional argument and may be accessed early via `--` - /// syntax - Last, - /// Hides the default value from the help string - HideDefaultValue, - /// Makes `Arg::possible_values` case insensitive - CaseInsensitive, - /// Hides ENV values in the help message - HideEnvValues, - /// The argument should **not** be shown in short help text - HiddenShortHelp, - /// The argument should **not** be shown in long help text - HiddenLongHelp, - #[doc(hidden)] RequiredUnlessAll, - #[doc(hidden)] ValueDelimiterNotSet, -} - -impl FromStr for ArgSettings { - type Err = String; - fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> { - match &*s.to_ascii_lowercase() { - "required" => Ok(ArgSettings::Required), - "multiple" => Ok(ArgSettings::Multiple), - "global" => Ok(ArgSettings::Global), - "emptyvalues" => Ok(ArgSettings::EmptyValues), - "hidden" => Ok(ArgSettings::Hidden), - "takesvalue" => Ok(ArgSettings::TakesValue), - "usevaluedelimiter" => Ok(ArgSettings::UseValueDelimiter), - "nextlinehelp" => Ok(ArgSettings::NextLineHelp), - "requiredunlessall" => Ok(ArgSettings::RequiredUnlessAll), - "requiredelimiter" => Ok(ArgSettings::RequireDelimiter), - "valuedelimiternotset" => Ok(ArgSettings::ValueDelimiterNotSet), - "hidepossiblevalues" => Ok(ArgSettings::HidePossibleValues), - "allowleadinghyphen" => Ok(ArgSettings::AllowLeadingHyphen), - "requireequals" => Ok(ArgSettings::RequireEquals), - "last" => Ok(ArgSettings::Last), - "hidedefaultvalue" => Ok(ArgSettings::HideDefaultValue), - "caseinsensitive" => Ok(ArgSettings::CaseInsensitive), - "hideenvvalues" => Ok(ArgSettings::HideEnvValues), - "hiddenshorthelp" => Ok(ArgSettings::HiddenShortHelp), - "hiddenlonghelp" => Ok(ArgSettings::HiddenLongHelp), - _ => Err("unknown ArgSetting, cannot convert from str".to_owned()), - } - } -} - -#[cfg(test)] -mod test { - use super::ArgSettings; - - #[test] - fn arg_settings_fromstr() { - assert_eq!( - "allowleadinghyphen".parse::<ArgSettings>().unwrap(), - ArgSettings::AllowLeadingHyphen - ); - assert_eq!( - "emptyvalues".parse::<ArgSettings>().unwrap(), - ArgSettings::EmptyValues - ); - assert_eq!( - "global".parse::<ArgSettings>().unwrap(), - ArgSettings::Global - ); - assert_eq!( - "hidepossiblevalues".parse::<ArgSettings>().unwrap(), - ArgSettings::HidePossibleValues - ); - assert_eq!( - "hidden".parse::<ArgSettings>().unwrap(), - ArgSettings::Hidden - ); - assert_eq!( - "multiple".parse::<ArgSettings>().unwrap(), - ArgSettings::Multiple - ); - assert_eq!( - "nextlinehelp".parse::<ArgSettings>().unwrap(), - ArgSettings::NextLineHelp - ); - assert_eq!( - "requiredunlessall".parse::<ArgSettings>().unwrap(), - ArgSettings::RequiredUnlessAll - ); - assert_eq!( - "requiredelimiter".parse::<ArgSettings>().unwrap(), - ArgSettings::RequireDelimiter - ); - assert_eq!( - "required".parse::<ArgSettings>().unwrap(), - ArgSettings::Required - ); - assert_eq!( - "takesvalue".parse::<ArgSettings>().unwrap(), - ArgSettings::TakesValue - ); - assert_eq!( - "usevaluedelimiter".parse::<ArgSettings>().unwrap(), - ArgSettings::UseValueDelimiter - ); - assert_eq!( - "valuedelimiternotset".parse::<ArgSettings>().unwrap(), - ArgSettings::ValueDelimiterNotSet - ); - assert_eq!( - "requireequals".parse::<ArgSettings>().unwrap(), - ArgSettings::RequireEquals - ); - assert_eq!("last".parse::<ArgSettings>().unwrap(), ArgSettings::Last); - assert_eq!( - "hidedefaultvalue".parse::<ArgSettings>().unwrap(), - ArgSettings::HideDefaultValue - ); - assert_eq!( - "caseinsensitive".parse::<ArgSettings>().unwrap(), - ArgSettings::CaseInsensitive - ); - assert_eq!( - "hideenvvalues".parse::<ArgSettings>().unwrap(), - ArgSettings::HideEnvValues - ); - assert_eq!( - "hiddenshorthelp".parse::<ArgSettings>().unwrap(), - ArgSettings::HiddenShortHelp - ); - assert_eq!( - "hiddenlonghelp".parse::<ArgSettings>().unwrap(), - ArgSettings::HiddenLongHelp - ); - assert!("hahahaha".parse::<ArgSettings>().is_err()); - } -} diff --git a/clap/src/args/subcommand.rs b/clap/src/args/subcommand.rs deleted file mode 100644 index eebbf82..0000000 --- a/clap/src/args/subcommand.rs +++ /dev/null @@ -1,66 +0,0 @@ -// Third Party -#[cfg(feature = "yaml")] -use yaml_rust::Yaml; - -// Internal -use App; -use ArgMatches; - -/// The abstract representation of a command line subcommand. -/// -/// This struct describes all the valid options of the subcommand for the program. Subcommands are -/// essentially "sub-[`App`]s" and contain all the same possibilities (such as their own -/// [arguments], subcommands, and settings). -/// -/// # Examples -/// -/// ```rust -/// # use clap::{App, Arg, SubCommand}; -/// App::new("myprog") -/// .subcommand( -/// SubCommand::with_name("config") -/// .about("Used for configuration") -/// .arg(Arg::with_name("config_file") -/// .help("The configuration file to use") -/// .index(1))) -/// # ; -/// ``` -/// [`App`]: ./struct.App.html -/// [arguments]: ./struct.Arg.html -#[derive(Debug, Clone)] -pub struct SubCommand<'a> { - #[doc(hidden)] pub name: String, - #[doc(hidden)] pub matches: ArgMatches<'a>, -} - -impl<'a> SubCommand<'a> { - /// Creates a new instance of a subcommand requiring a name. The name will be displayed - /// to the user when they print version or help and usage information. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, SubCommand}; - /// App::new("myprog") - /// .subcommand( - /// SubCommand::with_name("config")) - /// # ; - /// ``` - pub fn with_name<'b>(name: &str) -> App<'a, 'b> { App::new(name) } - - /// Creates a new instance of a subcommand from a YAML (.yml) document - /// - /// # Examples - /// - /// ```ignore - /// # #[macro_use] - /// # extern crate clap; - /// # use clap::Subcommand; - /// # fn main() { - /// let sc_yaml = load_yaml!("test_subcommand.yml"); - /// let sc = SubCommand::from_yaml(sc_yaml); - /// # } - /// ``` - #[cfg(feature = "yaml")] - pub fn from_yaml(yaml: &Yaml) -> App { App::from_yaml(yaml) } -} diff --git a/clap/src/completions/bash.rs b/clap/src/completions/bash.rs deleted file mode 100644 index 37dfa66..0000000 --- a/clap/src/completions/bash.rs +++ /dev/null @@ -1,219 +0,0 @@ -// Std -use std::io::Write; - -// Internal -use app::parser::Parser; -use args::OptBuilder; -use completions; - -pub struct BashGen<'a, 'b> -where - 'a: 'b, -{ - p: &'b Parser<'a, 'b>, -} - -impl<'a, 'b> BashGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { BashGen { p: p } } - - pub fn generate_to<W: Write>(&self, buf: &mut W) { - w!( - buf, - format!( - r#"_{name}() {{ - local i cur prev opts cmds - COMPREPLY=() - cur="${{COMP_WORDS[COMP_CWORD]}}" - prev="${{COMP_WORDS[COMP_CWORD-1]}}" - cmd="" - opts="" - - for i in ${{COMP_WORDS[@]}} - do - case "${{i}}" in - {name}) - cmd="{name}" - ;; - {subcmds} - *) - ;; - esac - done - - case "${{cmd}}" in - {name}) - opts="{name_opts}" - if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq 1 ]] ; then - COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) - return 0 - fi - case "${{prev}}" in - {name_opts_details} - *) - COMPREPLY=() - ;; - esac - COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) - return 0 - ;; - {subcmd_details} - esac -}} - -complete -F _{name} -o bashdefault -o default {name} -"#, - name = self.p.meta.bin_name.as_ref().unwrap(), - name_opts = self.all_options_for_path(self.p.meta.bin_name.as_ref().unwrap()), - name_opts_details = - self.option_details_for_path(self.p.meta.bin_name.as_ref().unwrap()), - subcmds = self.all_subcommands(), - subcmd_details = self.subcommand_details() - ).as_bytes() - ); - } - - fn all_subcommands(&self) -> String { - debugln!("BashGen::all_subcommands;"); - let mut subcmds = String::new(); - let scs = completions::all_subcommand_names(self.p); - - for sc in &scs { - subcmds = format!( - r#"{} - {name}) - cmd+="__{fn_name}" - ;;"#, - subcmds, - name = sc, - fn_name = sc.replace("-", "__") - ); - } - - subcmds - } - - fn subcommand_details(&self) -> String { - debugln!("BashGen::subcommand_details;"); - let mut subcmd_dets = String::new(); - let mut scs = completions::get_all_subcommand_paths(self.p, true); - scs.sort(); - scs.dedup(); - - for sc in &scs { - subcmd_dets = format!( - r#"{} - {subcmd}) - opts="{sc_opts}" - if [[ ${{cur}} == -* || ${{COMP_CWORD}} -eq {level} ]] ; then - COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) - return 0 - fi - case "${{prev}}" in - {opts_details} - *) - COMPREPLY=() - ;; - esac - COMPREPLY=( $(compgen -W "${{opts}}" -- "${{cur}}") ) - return 0 - ;;"#, - subcmd_dets, - subcmd = sc.replace("-", "__"), - sc_opts = self.all_options_for_path(&*sc), - level = sc.split("__").map(|_| 1).fold(0, |acc, n| acc + n), - opts_details = self.option_details_for_path(&*sc) - ); - } - - subcmd_dets - } - - fn option_details_for_path(&self, path: &str) -> String { - debugln!("BashGen::option_details_for_path: path={}", path); - let mut p = self.p; - for sc in path.split("__").skip(1) { - debugln!("BashGen::option_details_for_path:iter: sc={}", sc); - p = &find_subcmd!(p, sc).unwrap().p; - } - let mut opts = String::new(); - for o in p.opts() { - if let Some(l) = o.s.long { - opts = format!( - "{} - --{}) - COMPREPLY=({}) - return 0 - ;;", - opts, - l, - self.vals_for(o) - ); - } - if let Some(s) = o.s.short { - opts = format!( - "{} - -{}) - COMPREPLY=({}) - return 0 - ;;", - opts, - s, - self.vals_for(o) - ); - } - } - opts - } - - fn vals_for(&self, o: &OptBuilder) -> String { - debugln!("BashGen::vals_for: o={}", o.b.name); - use args::AnyArg; - if let Some(vals) = o.possible_vals() { - format!(r#"$(compgen -W "{}" -- "${{cur}}")"#, vals.join(" ")) - } else { - String::from(r#"$(compgen -f "${cur}")"#) - } - } - - fn all_options_for_path(&self, path: &str) -> String { - debugln!("BashGen::all_options_for_path: path={}", path); - let mut p = self.p; - for sc in path.split("__").skip(1) { - debugln!("BashGen::all_options_for_path:iter: sc={}", sc); - p = &find_subcmd!(p, sc).unwrap().p; - } - let mut opts = shorts!(p).fold(String::new(), |acc, s| format!("{} -{}", acc, s)); - opts = format!( - "{} {}", - opts, - longs!(p).fold(String::new(), |acc, l| format!("{} --{}", acc, l)) - ); - opts = format!( - "{} {}", - opts, - p.positionals - .values() - .fold(String::new(), |acc, p| format!("{} {}", acc, p)) - ); - opts = format!( - "{} {}", - opts, - p.subcommands - .iter() - .fold(String::new(), |acc, s| format!("{} {}", acc, s.p.meta.name)) - ); - for sc in &p.subcommands { - if let Some(ref aliases) = sc.p.meta.aliases { - opts = format!( - "{} {}", - opts, - aliases - .iter() - .map(|&(n, _)| n) - .fold(String::new(), |acc, a| format!("{} {}", acc, a)) - ); - } - } - opts - } -} diff --git a/clap/src/completions/elvish.rs b/clap/src/completions/elvish.rs deleted file mode 100644 index 9a5f21a..0000000 --- a/clap/src/completions/elvish.rs +++ /dev/null @@ -1,126 +0,0 @@ -// Std -use std::io::Write; - -// Internal -use app::parser::Parser; -use INTERNAL_ERROR_MSG; - -pub struct ElvishGen<'a, 'b> -where - 'a: 'b, -{ - p: &'b Parser<'a, 'b>, -} - -impl<'a, 'b> ElvishGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { ElvishGen { p: p } } - - pub fn generate_to<W: Write>(&self, buf: &mut W) { - let bin_name = self.p.meta.bin_name.as_ref().unwrap(); - - let mut names = vec![]; - let subcommands_cases = - generate_inner(self.p, "", &mut names); - - let result = format!(r#" -edit:completion:arg-completer[{bin_name}] = [@words]{{ - fn spaces [n]{{ - repeat $n ' ' | joins '' - }} - fn cand [text desc]{{ - edit:complex-candidate $text &display-suffix=' '(spaces (- 14 (wcswidth $text)))$desc - }} - command = '{bin_name}' - for word $words[1:-1] {{ - if (has-prefix $word '-') {{ - break - }} - command = $command';'$word - }} - completions = [{subcommands_cases} - ] - $completions[$command] -}} -"#, - bin_name = bin_name, - subcommands_cases = subcommands_cases - ); - - w!(buf, result.as_bytes()); - } -} - -// Escape string inside single quotes -fn escape_string(string: &str) -> String { string.replace("'", "''") } - -fn get_tooltip<T : ToString>(help: Option<&str>, data: T) -> String { - match help { - Some(help) => escape_string(help), - _ => data.to_string() - } -} - -fn generate_inner<'a, 'b, 'p>( - p: &'p Parser<'a, 'b>, - previous_command_name: &str, - names: &mut Vec<&'p str>, -) -> String { - debugln!("ElvishGen::generate_inner;"); - let command_name = if previous_command_name.is_empty() { - p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone() - } else { - format!("{};{}", previous_command_name, &p.meta.name) - }; - - let mut completions = String::new(); - let preamble = String::from("\n cand "); - - for option in p.opts() { - if let Some(data) = option.s.short { - let tooltip = get_tooltip(option.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("-{} '{}'", data, tooltip).as_str()); - } - if let Some(data) = option.s.long { - let tooltip = get_tooltip(option.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("--{} '{}'", data, tooltip).as_str()); - } - } - - for flag in p.flags() { - if let Some(data) = flag.s.short { - let tooltip = get_tooltip(flag.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("-{} '{}'", data, tooltip).as_str()); - } - if let Some(data) = flag.s.long { - let tooltip = get_tooltip(flag.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("--{} '{}'", data, tooltip).as_str()); - } - } - - for subcommand in &p.subcommands { - let data = &subcommand.p.meta.name; - let tooltip = get_tooltip(subcommand.p.meta.about, data); - completions.push_str(&preamble); - completions.push_str(format!("{} '{}'", data, tooltip).as_str()); - } - - let mut subcommands_cases = format!( - r" - &'{}'= {{{} - }}", - &command_name, - completions - ); - - for subcommand in &p.subcommands { - let subcommand_subcommands_cases = - generate_inner(&subcommand.p, &command_name, names); - subcommands_cases.push_str(&subcommand_subcommands_cases); - } - - subcommands_cases -} diff --git a/clap/src/completions/fish.rs b/clap/src/completions/fish.rs deleted file mode 100644 index c2c5a5e..0000000 --- a/clap/src/completions/fish.rs +++ /dev/null @@ -1,99 +0,0 @@ -// Std -use std::io::Write; - -// Internal -use app::parser::Parser; - -pub struct FishGen<'a, 'b> -where - 'a: 'b, -{ - p: &'b Parser<'a, 'b>, -} - -impl<'a, 'b> FishGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { FishGen { p: p } } - - pub fn generate_to<W: Write>(&self, buf: &mut W) { - let command = self.p.meta.bin_name.as_ref().unwrap(); - let mut buffer = String::new(); - gen_fish_inner(command, self, command, &mut buffer); - w!(buf, buffer.as_bytes()); - } -} - -// Escape string inside single quotes -fn escape_string(string: &str) -> String { string.replace("\\", "\\\\").replace("'", "\\'") } - -fn gen_fish_inner(root_command: &str, comp_gen: &FishGen, subcommand: &str, buffer: &mut String) { - debugln!("FishGen::gen_fish_inner;"); - // example : - // - // complete - // -c {command} - // -d "{description}" - // -s {short} - // -l {long} - // -a "{possible_arguments}" - // -r # if require parameter - // -f # don't use file completion - // -n "__fish_use_subcommand" # complete for command "myprog" - // -n "__fish_seen_subcommand_from subcmd1" # complete for command "myprog subcmd1" - - let mut basic_template = format!("complete -c {} -n ", root_command); - if root_command == subcommand { - basic_template.push_str("\"__fish_use_subcommand\""); - } else { - basic_template.push_str(format!("\"__fish_seen_subcommand_from {}\"", subcommand).as_str()); - } - - for option in comp_gen.p.opts() { - let mut template = basic_template.clone(); - if let Some(data) = option.s.short { - template.push_str(format!(" -s {}", data).as_str()); - } - if let Some(data) = option.s.long { - template.push_str(format!(" -l {}", data).as_str()); - } - if let Some(data) = option.b.help { - template.push_str(format!(" -d '{}'", escape_string(data)).as_str()); - } - if let Some(ref data) = option.v.possible_vals { - template.push_str(format!(" -r -f -a \"{}\"", data.join(" ")).as_str()); - } - buffer.push_str(template.as_str()); - buffer.push_str("\n"); - } - - for flag in comp_gen.p.flags() { - let mut template = basic_template.clone(); - if let Some(data) = flag.s.short { - template.push_str(format!(" -s {}", data).as_str()); - } - if let Some(data) = flag.s.long { - template.push_str(format!(" -l {}", data).as_str()); - } - if let Some(data) = flag.b.help { - template.push_str(format!(" -d '{}'", escape_string(data)).as_str()); - } - buffer.push_str(template.as_str()); - buffer.push_str("\n"); - } - - for subcommand in &comp_gen.p.subcommands { - let mut template = basic_template.clone(); - template.push_str(" -f"); - template.push_str(format!(" -a \"{}\"", &subcommand.p.meta.name).as_str()); - if let Some(data) = subcommand.p.meta.about { - template.push_str(format!(" -d '{}'", escape_string(data)).as_str()) - } - buffer.push_str(template.as_str()); - buffer.push_str("\n"); - } - - // generate options of subcommands - for subcommand in &comp_gen.p.subcommands { - let sub_comp_gen = FishGen::new(&subcommand.p); - gen_fish_inner(root_command, &sub_comp_gen, &subcommand.to_string(), buffer); - } -} diff --git a/clap/src/completions/macros.rs b/clap/src/completions/macros.rs deleted file mode 100644 index 653c72c..0000000 --- a/clap/src/completions/macros.rs +++ /dev/null @@ -1,28 +0,0 @@ -macro_rules! w { - ($buf:expr, $to_w:expr) => { - match $buf.write_all($to_w) { - Ok(..) => (), - Err(..) => panic!("Failed to write to completions file"), - } - }; -} - -macro_rules! get_zsh_arg_conflicts { - ($p:ident, $arg:ident, $msg:ident) => { - if let Some(conf_vec) = $arg.blacklist() { - let mut v = vec![]; - for arg_name in conf_vec { - let arg = $p.find_any_arg(arg_name).expect($msg); - if let Some(s) = arg.short() { - v.push(format!("-{}", s)); - } - if let Some(l) = arg.long() { - v.push(format!("--{}", l)); - } - } - v.join(" ") - } else { - String::new() - } - } -} diff --git a/clap/src/completions/mod.rs b/clap/src/completions/mod.rs deleted file mode 100644 index a3306d7..0000000 --- a/clap/src/completions/mod.rs +++ /dev/null @@ -1,179 +0,0 @@ -#[macro_use] -mod macros; -mod bash; -mod fish; -mod zsh; -mod powershell; -mod elvish; -mod shell; - -// Std -use std::io::Write; - -// Internal -use app::parser::Parser; -use self::bash::BashGen; -use self::fish::FishGen; -use self::zsh::ZshGen; -use self::powershell::PowerShellGen; -use self::elvish::ElvishGen; -pub use self::shell::Shell; - -pub struct ComplGen<'a, 'b> -where - 'a: 'b, -{ - p: &'b Parser<'a, 'b>, -} - -impl<'a, 'b> ComplGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { ComplGen { p: p } } - - pub fn generate<W: Write>(&self, for_shell: Shell, buf: &mut W) { - match for_shell { - Shell::Bash => BashGen::new(self.p).generate_to(buf), - Shell::Fish => FishGen::new(self.p).generate_to(buf), - Shell::Zsh => ZshGen::new(self.p).generate_to(buf), - Shell::PowerShell => PowerShellGen::new(self.p).generate_to(buf), - Shell::Elvish => ElvishGen::new(self.p).generate_to(buf), - } - } -} - -// Gets all subcommands including child subcommands in the form of 'name' where the name -// is a single word (i.e. "install") of the path to said subcommand (i.e. -// "rustup toolchain install") -// -// Also note, aliases are treated as their own subcommands but duplicates of whatever they're -// aliasing. -pub fn all_subcommand_names(p: &Parser) -> Vec<String> { - debugln!("all_subcommand_names;"); - let mut subcmds: Vec<_> = subcommands_of(p) - .iter() - .map(|&(ref n, _)| n.clone()) - .collect(); - for sc_v in p.subcommands.iter().map(|s| all_subcommand_names(&s.p)) { - subcmds.extend(sc_v); - } - subcmds.sort(); - subcmds.dedup(); - subcmds -} - -// Gets all subcommands including child subcommands in the form of ('name', 'bin_name') where the name -// is a single word (i.e. "install") of the path and full bin_name of said subcommand (i.e. -// "rustup toolchain install") -// -// Also note, aliases are treated as their own subcommands but duplicates of whatever they're -// aliasing. -pub fn all_subcommands(p: &Parser) -> Vec<(String, String)> { - debugln!("all_subcommands;"); - let mut subcmds: Vec<_> = subcommands_of(p); - for sc_v in p.subcommands.iter().map(|s| all_subcommands(&s.p)) { - subcmds.extend(sc_v); - } - subcmds -} - -// Gets all subcommands excluding child subcommands in the form of (name, bin_name) where the name -// is a single word (i.e. "install") and the bin_name is a space delineated list of the path to said -// subcommand (i.e. "rustup toolchain install") -// -// Also note, aliases are treated as their own subcommands but duplicates of whatever they're -// aliasing. -pub fn subcommands_of(p: &Parser) -> Vec<(String, String)> { - debugln!( - "subcommands_of: name={}, bin_name={}", - p.meta.name, - p.meta.bin_name.as_ref().unwrap() - ); - let mut subcmds = vec![]; - - debugln!( - "subcommands_of: Has subcommands...{:?}", - p.has_subcommands() - ); - if !p.has_subcommands() { - let mut ret = vec![]; - debugln!("subcommands_of: Looking for aliases..."); - if let Some(ref aliases) = p.meta.aliases { - for &(n, _) in aliases { - debugln!("subcommands_of:iter:iter: Found alias...{}", n); - let mut als_bin_name: Vec<_> = - p.meta.bin_name.as_ref().unwrap().split(' ').collect(); - als_bin_name.push(n); - let old = als_bin_name.len() - 2; - als_bin_name.swap_remove(old); - ret.push((n.to_owned(), als_bin_name.join(" "))); - } - } - return ret; - } - for sc in &p.subcommands { - debugln!( - "subcommands_of:iter: name={}, bin_name={}", - sc.p.meta.name, - sc.p.meta.bin_name.as_ref().unwrap() - ); - - debugln!("subcommands_of:iter: Looking for aliases..."); - if let Some(ref aliases) = sc.p.meta.aliases { - for &(n, _) in aliases { - debugln!("subcommands_of:iter:iter: Found alias...{}", n); - let mut als_bin_name: Vec<_> = - p.meta.bin_name.as_ref().unwrap().split(' ').collect(); - als_bin_name.push(n); - let old = als_bin_name.len() - 2; - als_bin_name.swap_remove(old); - subcmds.push((n.to_owned(), als_bin_name.join(" "))); - } - } - subcmds.push(( - sc.p.meta.name.clone(), - sc.p.meta.bin_name.as_ref().unwrap().clone(), - )); - } - subcmds -} - -pub fn get_all_subcommand_paths(p: &Parser, first: bool) -> Vec<String> { - debugln!("get_all_subcommand_paths;"); - let mut subcmds = vec![]; - if !p.has_subcommands() { - if !first { - let name = &*p.meta.name; - let path = p.meta.bin_name.as_ref().unwrap().clone().replace(" ", "__"); - let mut ret = vec![path.clone()]; - if let Some(ref aliases) = p.meta.aliases { - for &(n, _) in aliases { - ret.push(path.replace(name, n)); - } - } - return ret; - } - return vec![]; - } - for sc in &p.subcommands { - let name = &*sc.p.meta.name; - let path = sc.p - .meta - .bin_name - .as_ref() - .unwrap() - .clone() - .replace(" ", "__"); - subcmds.push(path.clone()); - if let Some(ref aliases) = sc.p.meta.aliases { - for &(n, _) in aliases { - subcmds.push(path.replace(name, n)); - } - } - } - for sc_v in p.subcommands - .iter() - .map(|s| get_all_subcommand_paths(&s.p, false)) - { - subcmds.extend(sc_v); - } - subcmds -} diff --git a/clap/src/completions/powershell.rs b/clap/src/completions/powershell.rs deleted file mode 100644 index 9fc77c7..0000000 --- a/clap/src/completions/powershell.rs +++ /dev/null @@ -1,139 +0,0 @@ -// Std -use std::io::Write; - -// Internal -use app::parser::Parser; -use INTERNAL_ERROR_MSG; - -pub struct PowerShellGen<'a, 'b> -where - 'a: 'b, -{ - p: &'b Parser<'a, 'b>, -} - -impl<'a, 'b> PowerShellGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { PowerShellGen { p: p } } - - pub fn generate_to<W: Write>(&self, buf: &mut W) { - let bin_name = self.p.meta.bin_name.as_ref().unwrap(); - - let mut names = vec![]; - let subcommands_cases = - generate_inner(self.p, "", &mut names); - - let result = format!(r#" -using namespace System.Management.Automation -using namespace System.Management.Automation.Language - -Register-ArgumentCompleter -Native -CommandName '{bin_name}' -ScriptBlock {{ - param($wordToComplete, $commandAst, $cursorPosition) - - $commandElements = $commandAst.CommandElements - $command = @( - '{bin_name}' - for ($i = 1; $i -lt $commandElements.Count; $i++) {{ - $element = $commandElements[$i] - if ($element -isnot [StringConstantExpressionAst] -or - $element.StringConstantType -ne [StringConstantType]::BareWord -or - $element.Value.StartsWith('-')) {{ - break - }} - $element.Value - }}) -join ';' - - $completions = @(switch ($command) {{{subcommands_cases} - }}) - - $completions.Where{{ $_.CompletionText -like "$wordToComplete*" }} | - Sort-Object -Property ListItemText -}} -"#, - bin_name = bin_name, - subcommands_cases = subcommands_cases - ); - - w!(buf, result.as_bytes()); - } -} - -// Escape string inside single quotes -fn escape_string(string: &str) -> String { string.replace("'", "''") } - -fn get_tooltip<T : ToString>(help: Option<&str>, data: T) -> String { - match help { - Some(help) => escape_string(help), - _ => data.to_string() - } -} - -fn generate_inner<'a, 'b, 'p>( - p: &'p Parser<'a, 'b>, - previous_command_name: &str, - names: &mut Vec<&'p str>, -) -> String { - debugln!("PowerShellGen::generate_inner;"); - let command_name = if previous_command_name.is_empty() { - p.meta.bin_name.as_ref().expect(INTERNAL_ERROR_MSG).clone() - } else { - format!("{};{}", previous_command_name, &p.meta.name) - }; - - let mut completions = String::new(); - let preamble = String::from("\n [CompletionResult]::new("); - - for option in p.opts() { - if let Some(data) = option.s.short { - let tooltip = get_tooltip(option.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("'-{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); - } - if let Some(data) = option.s.long { - let tooltip = get_tooltip(option.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("'--{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); - } - } - - for flag in p.flags() { - if let Some(data) = flag.s.short { - let tooltip = get_tooltip(flag.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("'-{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); - } - if let Some(data) = flag.s.long { - let tooltip = get_tooltip(flag.b.help, data); - completions.push_str(&preamble); - completions.push_str(format!("'--{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterName", tooltip).as_str()); - } - } - - for subcommand in &p.subcommands { - let data = &subcommand.p.meta.name; - let tooltip = get_tooltip(subcommand.p.meta.about, data); - completions.push_str(&preamble); - completions.push_str(format!("'{}', '{}', {}, '{}')", - data, data, "[CompletionResultType]::ParameterValue", tooltip).as_str()); - } - - let mut subcommands_cases = format!( - r" - '{}' {{{} - break - }}", - &command_name, - completions - ); - - for subcommand in &p.subcommands { - let subcommand_subcommands_cases = - generate_inner(&subcommand.p, &command_name, names); - subcommands_cases.push_str(&subcommand_subcommands_cases); - } - - subcommands_cases -} diff --git a/clap/src/completions/shell.rs b/clap/src/completions/shell.rs deleted file mode 100644 index 19aab86..0000000 --- a/clap/src/completions/shell.rs +++ /dev/null @@ -1,52 +0,0 @@ -#[allow(deprecated, unused_imports)] -use std::ascii::AsciiExt; -use std::str::FromStr; -use std::fmt; - -/// Describes which shell to produce a completions file for -#[cfg_attr(feature = "lints", allow(enum_variant_names))] -#[derive(Debug, Copy, Clone)] -pub enum Shell { - /// Generates a .bash completion file for the Bourne Again SHell (BASH) - Bash, - /// Generates a .fish completion file for the Friendly Interactive SHell (fish) - Fish, - /// Generates a completion file for the Z SHell (ZSH) - Zsh, - /// Generates a completion file for PowerShell - PowerShell, - /// Generates a completion file for Elvish - Elvish, -} - -impl Shell { - /// A list of possible variants in `&'static str` form - pub fn variants() -> [&'static str; 5] { ["zsh", "bash", "fish", "powershell", "elvish"] } -} - -impl FromStr for Shell { - type Err = String; - - fn from_str(s: &str) -> Result<Self, Self::Err> { - match s { - "ZSH" | _ if s.eq_ignore_ascii_case("zsh") => Ok(Shell::Zsh), - "FISH" | _ if s.eq_ignore_ascii_case("fish") => Ok(Shell::Fish), - "BASH" | _ if s.eq_ignore_ascii_case("bash") => Ok(Shell::Bash), - "POWERSHELL" | _ if s.eq_ignore_ascii_case("powershell") => Ok(Shell::PowerShell), - "ELVISH" | _ if s.eq_ignore_ascii_case("elvish") => Ok(Shell::Elvish), - _ => Err(String::from("[valid values: bash, fish, zsh, powershell, elvish]")), - } - } -} - -impl fmt::Display for Shell { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Shell::Bash => write!(f, "BASH"), - Shell::Fish => write!(f, "FISH"), - Shell::Zsh => write!(f, "ZSH"), - Shell::PowerShell => write!(f, "POWERSHELL"), - Shell::Elvish => write!(f, "ELVISH"), - } - } -} diff --git a/clap/src/completions/zsh.rs b/clap/src/completions/zsh.rs deleted file mode 100644 index 5d23fd2..0000000 --- a/clap/src/completions/zsh.rs +++ /dev/null @@ -1,472 +0,0 @@ -// Std -use std::io::Write; -#[allow(deprecated, unused_imports)] -use std::ascii::AsciiExt; - -// Internal -use app::App; -use app::parser::Parser; -use args::{AnyArg, ArgSettings}; -use completions; -use INTERNAL_ERROR_MSG; - -pub struct ZshGen<'a, 'b> -where - 'a: 'b, -{ - p: &'b Parser<'a, 'b>, -} - -impl<'a, 'b> ZshGen<'a, 'b> { - pub fn new(p: &'b Parser<'a, 'b>) -> Self { - debugln!("ZshGen::new;"); - ZshGen { p: p } - } - - pub fn generate_to<W: Write>(&self, buf: &mut W) { - debugln!("ZshGen::generate_to;"); - w!( - buf, - format!( - "\ -#compdef {name} - -autoload -U is-at-least - -_{name}() {{ - typeset -A opt_args - typeset -a _arguments_options - local ret=1 - - if is-at-least 5.2; then - _arguments_options=(-s -S -C) - else - _arguments_options=(-s -C) - fi - - local context curcontext=\"$curcontext\" state line - {initial_args} - {subcommands} -}} - -{subcommand_details} - -_{name} \"$@\"", - name = self.p.meta.bin_name.as_ref().unwrap(), - initial_args = get_args_of(self.p), - subcommands = get_subcommands_of(self.p), - subcommand_details = subcommand_details(self.p) - ).as_bytes() - ); - } -} - -// Displays the commands of a subcommand -// (( $+functions[_[bin_name_underscore]_commands] )) || -// _[bin_name_underscore]_commands() { -// local commands; commands=( -// '[arg_name]:[arg_help]' -// ) -// _describe -t commands '[bin_name] commands' commands "$@" -// -// Where the following variables are present: -// [bin_name_underscore]: The full space delineated bin_name, where spaces have been replaced by -// underscore characters -// [arg_name]: The name of the subcommand -// [arg_help]: The help message of the subcommand -// [bin_name]: The full space delineated bin_name -// -// Here's a snippet from rustup: -// -// (( $+functions[_rustup_commands] )) || -// _rustup_commands() { -// local commands; commands=( -// 'show:Show the active and installed toolchains' -// 'update:Update Rust toolchains' -// # ... snip for brevity -// 'help:Prints this message or the help of the given subcommand(s)' -// ) -// _describe -t commands 'rustup commands' commands "$@" -// -fn subcommand_details(p: &Parser) -> String { - debugln!("ZshGen::subcommand_details;"); - // First we do ourself - let mut ret = vec![ - format!( - "\ -(( $+functions[_{bin_name_underscore}_commands] )) || -_{bin_name_underscore}_commands() {{ - local commands; commands=( - {subcommands_and_args} - ) - _describe -t commands '{bin_name} commands' commands \"$@\" -}}", - bin_name_underscore = p.meta.bin_name.as_ref().unwrap().replace(" ", "__"), - bin_name = p.meta.bin_name.as_ref().unwrap(), - subcommands_and_args = subcommands_of(p) - ), - ]; - - // Next we start looping through all the children, grandchildren, etc. - let mut all_subcommands = completions::all_subcommands(p); - all_subcommands.sort(); - all_subcommands.dedup(); - for &(_, ref bin_name) in &all_subcommands { - debugln!("ZshGen::subcommand_details:iter: bin_name={}", bin_name); - ret.push(format!( - "\ -(( $+functions[_{bin_name_underscore}_commands] )) || -_{bin_name_underscore}_commands() {{ - local commands; commands=( - {subcommands_and_args} - ) - _describe -t commands '{bin_name} commands' commands \"$@\" -}}", - bin_name_underscore = bin_name.replace(" ", "__"), - bin_name = bin_name, - subcommands_and_args = subcommands_of(parser_of(p, bin_name)) - )); - } - - ret.join("\n") -} - -// Generates subcommand completions in form of -// -// '[arg_name]:[arg_help]' -// -// Where: -// [arg_name]: the subcommand's name -// [arg_help]: the help message of the subcommand -// -// A snippet from rustup: -// 'show:Show the active and installed toolchains' -// 'update:Update Rust toolchains' -fn subcommands_of(p: &Parser) -> String { - debugln!("ZshGen::subcommands_of;"); - let mut ret = vec![]; - fn add_sc(sc: &App, n: &str, ret: &mut Vec<String>) { - debugln!("ZshGen::add_sc;"); - let s = format!( - "\"{name}:{help}\" \\", - name = n, - help = sc.p - .meta - .about - .unwrap_or("") - .replace("[", "\\[") - .replace("]", "\\]") - ); - if !s.is_empty() { - ret.push(s); - } - } - - // The subcommands - for sc in p.subcommands() { - debugln!( - "ZshGen::subcommands_of:iter: subcommand={}", - sc.p.meta.name - ); - add_sc(sc, &sc.p.meta.name, &mut ret); - if let Some(ref v) = sc.p.meta.aliases { - for alias in v.iter().filter(|&&(_, vis)| vis).map(|&(n, _)| n) { - add_sc(sc, alias, &mut ret); - } - } - } - - ret.join("\n") -} - -// Get's the subcommand section of a completion file -// This looks roughly like: -// -// case $state in -// ([bin_name]_args) -// curcontext=\"${curcontext%:*:*}:[name_hyphen]-command-$words[1]:\" -// case $line[1] in -// -// ([name]) -// _arguments -C -s -S \ -// [subcommand_args] -// && ret=0 -// -// [RECURSIVE_CALLS] -// -// ;;", -// -// [repeat] -// -// esac -// ;; -// esac", -// -// Where the following variables are present: -// [name] = The subcommand name in the form of "install" for "rustup toolchain install" -// [bin_name] = The full space delineated bin_name such as "rustup toolchain install" -// [name_hyphen] = The full space delineated bin_name, but replace spaces with hyphens -// [repeat] = From the same recursive calls, but for all subcommands -// [subcommand_args] = The same as zsh::get_args_of -fn get_subcommands_of(p: &Parser) -> String { - debugln!("get_subcommands_of;"); - - debugln!( - "get_subcommands_of: Has subcommands...{:?}", - p.has_subcommands() - ); - if !p.has_subcommands() { - return String::new(); - } - - let sc_names = completions::subcommands_of(p); - - let mut subcmds = vec![]; - for &(ref name, ref bin_name) in &sc_names { - let mut v = vec![format!("({})", name)]; - let subcommand_args = get_args_of(parser_of(p, &*bin_name)); - if !subcommand_args.is_empty() { - v.push(subcommand_args); - } - let subcommands = get_subcommands_of(parser_of(p, &*bin_name)); - if !subcommands.is_empty() { - v.push(subcommands); - } - v.push(String::from(";;")); - subcmds.push(v.join("\n")); - } - - format!( - "case $state in - ({name}) - words=($line[{pos}] \"${{words[@]}}\") - (( CURRENT += 1 )) - curcontext=\"${{curcontext%:*:*}}:{name_hyphen}-command-$line[{pos}]:\" - case $line[{pos}] in - {subcommands} - esac - ;; -esac", - name = p.meta.name, - name_hyphen = p.meta.bin_name.as_ref().unwrap().replace(" ", "-"), - subcommands = subcmds.join("\n"), - pos = p.positionals().len() + 1 - ) -} - -fn parser_of<'a, 'b>(p: &'b Parser<'a, 'b>, sc: &str) -> &'b Parser<'a, 'b> { - debugln!("parser_of: sc={}", sc); - if sc == p.meta.bin_name.as_ref().unwrap_or(&String::new()) { - return p; - } - &p.find_subcommand(sc).expect(INTERNAL_ERROR_MSG).p -} - -// Writes out the args section, which ends up being the flags, opts and postionals, and a jump to -// another ZSH function if there are subcommands. -// The structer works like this: -// ([conflicting_args]) [multiple] arg [takes_value] [[help]] [: :(possible_values)] -// ^-- list '-v -h' ^--'*' ^--'+' ^-- list 'one two three' -// -// An example from the rustup command: -// -// _arguments -C -s -S \ -// '(-h --help --verbose)-v[Enable verbose output]' \ -// '(-V -v --version --verbose --help)-h[Prints help information]' \ -// # ... snip for brevity -// ':: :_rustup_commands' \ # <-- displays subcommands -// '*::: :->rustup' \ # <-- displays subcommand args and child subcommands -// && ret=0 -// -// The args used for _arguments are as follows: -// -C: modify the $context internal variable -// -s: Allow stacking of short args (i.e. -a -b -c => -abc) -// -S: Do not complete anything after '--' and treat those as argument values -fn get_args_of(p: &Parser) -> String { - debugln!("get_args_of;"); - let mut ret = vec![String::from("_arguments \"${_arguments_options[@]}\" \\")]; - let opts = write_opts_of(p); - let flags = write_flags_of(p); - let positionals = write_positionals_of(p); - let sc_or_a = if p.has_subcommands() { - format!( - "\":: :_{name}_commands\" \\", - name = p.meta.bin_name.as_ref().unwrap().replace(" ", "__") - ) - } else { - String::new() - }; - let sc = if p.has_subcommands() { - format!("\"*::: :->{name}\" \\", name = p.meta.name) - } else { - String::new() - }; - - if !opts.is_empty() { - ret.push(opts); - } - if !flags.is_empty() { - ret.push(flags); - } - if !positionals.is_empty() { - ret.push(positionals); - } - if !sc_or_a.is_empty() { - ret.push(sc_or_a); - } - if !sc.is_empty() { - ret.push(sc); - } - ret.push(String::from("&& ret=0")); - - ret.join("\n") -} - -// Escape help string inside single quotes and brackets -fn escape_help(string: &str) -> String { - string - .replace("\\", "\\\\") - .replace("'", "'\\''") - .replace("[", "\\[") - .replace("]", "\\]") -} - -// Escape value string inside single quotes and parentheses -fn escape_value(string: &str) -> String { - string - .replace("\\", "\\\\") - .replace("'", "'\\''") - .replace("(", "\\(") - .replace(")", "\\)") - .replace(" ", "\\ ") -} - -fn write_opts_of(p: &Parser) -> String { - debugln!("write_opts_of;"); - let mut ret = vec![]; - for o in p.opts() { - debugln!("write_opts_of:iter: o={}", o.name()); - let help = o.help().map_or(String::new(), escape_help); - let mut conflicts = get_zsh_arg_conflicts!(p, o, INTERNAL_ERROR_MSG); - conflicts = if conflicts.is_empty() { - String::new() - } else { - format!("({})", conflicts) - }; - - let multiple = if o.is_set(ArgSettings::Multiple) { - "*" - } else { - "" - }; - let pv = if let Some(pv_vec) = o.possible_vals() { - format!(": :({})", pv_vec.iter().map( - |v| escape_value(*v)).collect::<Vec<String>>().join(" ")) - } else { - String::new() - }; - if let Some(short) = o.short() { - let s = format!( - "'{conflicts}{multiple}-{arg}+[{help}]{possible_values}' \\", - conflicts = conflicts, - multiple = multiple, - arg = short, - possible_values = pv, - help = help - ); - - debugln!("write_opts_of:iter: Wrote...{}", &*s); - ret.push(s); - } - if let Some(long) = o.long() { - let l = format!( - "'{conflicts}{multiple}--{arg}=[{help}]{possible_values}' \\", - conflicts = conflicts, - multiple = multiple, - arg = long, - possible_values = pv, - help = help - ); - - debugln!("write_opts_of:iter: Wrote...{}", &*l); - ret.push(l); - } - } - - ret.join("\n") -} - -fn write_flags_of(p: &Parser) -> String { - debugln!("write_flags_of;"); - let mut ret = vec![]; - for f in p.flags() { - debugln!("write_flags_of:iter: f={}", f.name()); - let help = f.help().map_or(String::new(), escape_help); - let mut conflicts = get_zsh_arg_conflicts!(p, f, INTERNAL_ERROR_MSG); - conflicts = if conflicts.is_empty() { - String::new() - } else { - format!("({})", conflicts) - }; - - let multiple = if f.is_set(ArgSettings::Multiple) { - "*" - } else { - "" - }; - if let Some(short) = f.short() { - let s = format!( - "'{conflicts}{multiple}-{arg}[{help}]' \\", - multiple = multiple, - conflicts = conflicts, - arg = short, - help = help - ); - - debugln!("write_flags_of:iter: Wrote...{}", &*s); - ret.push(s); - } - - if let Some(long) = f.long() { - let l = format!( - "'{conflicts}{multiple}--{arg}[{help}]' \\", - conflicts = conflicts, - multiple = multiple, - arg = long, - help = help - ); - - debugln!("write_flags_of:iter: Wrote...{}", &*l); - ret.push(l); - } - } - - ret.join("\n") -} - -fn write_positionals_of(p: &Parser) -> String { - debugln!("write_positionals_of;"); - let mut ret = vec![]; - for arg in p.positionals() { - debugln!("write_positionals_of:iter: arg={}", arg.b.name); - let a = format!( - "'{optional}:{name}{help}:{action}' \\", - optional = if !arg.b.is_set(ArgSettings::Required) { ":" } else { "" }, - name = arg.b.name, - help = arg.b - .help - .map_or("".to_owned(), |v| " -- ".to_owned() + v) - .replace("[", "\\[") - .replace("]", "\\]"), - action = arg.possible_vals().map_or("_files".to_owned(), |values| { - format!("({})", - values.iter().map(|v| escape_value(*v)).collect::<Vec<String>>().join(" ")) - }) - ); - - debugln!("write_positionals_of:iter: Wrote...{}", a); - ret.push(a); - } - - ret.join("\n") -} diff --git a/clap/src/errors.rs b/clap/src/errors.rs deleted file mode 100644 index c6087c0..0000000 --- a/clap/src/errors.rs +++ /dev/null @@ -1,912 +0,0 @@ -// Std -use std::convert::From; -use std::error::Error as StdError; -use std::fmt as std_fmt; -use std::fmt::Display; -use std::io::{self, Write}; -use std::process; -use std::result::Result as StdResult; - -// Internal -use args::AnyArg; -use fmt::{ColorWhen, Colorizer, ColorizerOption}; -use suggestions; - -/// Short hand for [`Result`] type -/// -/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html -pub type Result<T> = StdResult<T, Error>; - -/// Command line argument parser kind of error -#[derive(Debug, Copy, Clone, PartialEq)] -pub enum ErrorKind { - /// Occurs when an [`Arg`] has a set of possible values, - /// and the user provides a value which isn't in that set. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("speed") - /// .possible_value("fast") - /// .possible_value("slow")) - /// .get_matches_from_safe(vec!["prog", "other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidValue); - /// ``` - /// [`Arg`]: ./struct.Arg.html - InvalidValue, - - /// Occurs when a user provides a flag, option, argument or subcommand which isn't defined. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::from_usage("--flag 'some flag'")) - /// .get_matches_from_safe(vec!["prog", "--other"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnknownArgument); - /// ``` - UnknownArgument, - - /// Occurs when the user provides an unrecognized [`SubCommand`] which meets the threshold for - /// being similar enough to an existing subcommand. - /// If it doesn't meet the threshold, or the 'suggestions' feature is disabled, - /// the more general [`UnknownArgument`] error is returned. - /// - /// # Examples - /// - #[cfg_attr(not(feature = "suggestions"), doc = " ```no_run")] - #[cfg_attr(feature = "suggestions", doc = " ```")] - /// # use clap::{App, Arg, ErrorKind, SubCommand}; - /// let result = App::new("prog") - /// .subcommand(SubCommand::with_name("config") - /// .about("Used for configuration") - /// .arg(Arg::with_name("config_file") - /// .help("The configuration file to use") - /// .index(1))) - /// .get_matches_from_safe(vec!["prog", "confi"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidSubcommand); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument - InvalidSubcommand, - - /// Occurs when the user provides an unrecognized [`SubCommand`] which either - /// doesn't meet the threshold for being similar enough to an existing subcommand, - /// or the 'suggestions' feature is disabled. - /// Otherwise the more detailed [`InvalidSubcommand`] error is returned. - /// - /// This error typically happens when passing additional subcommand names to the `help` - /// subcommand. Otherwise, the more general [`UnknownArgument`] error is used. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind, SubCommand}; - /// let result = App::new("prog") - /// .subcommand(SubCommand::with_name("config") - /// .about("Used for configuration") - /// .arg(Arg::with_name("config_file") - /// .help("The configuration file to use") - /// .index(1))) - /// .get_matches_from_safe(vec!["prog", "help", "nothing"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnrecognizedSubcommand); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`InvalidSubcommand`]: ./enum.ErrorKind.html#variant.InvalidSubcommand - /// [`UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument - UnrecognizedSubcommand, - - /// Occurs when the user provides an empty value for an option that does not allow empty - /// values. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let res = App::new("prog") - /// .arg(Arg::with_name("color") - /// .long("color") - /// .empty_values(false)) - /// .get_matches_from_safe(vec!["prog", "--color="]); - /// assert!(res.is_err()); - /// assert_eq!(res.unwrap_err().kind, ErrorKind::EmptyValue); - /// ``` - EmptyValue, - - /// Occurs when the user provides a value for an argument with a custom validation and the - /// value fails that validation. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// fn is_numeric(val: String) -> Result<(), String> { - /// match val.parse::<i64>() { - /// Ok(..) => Ok(()), - /// Err(..) => Err(String::from("Value wasn't a number!")), - /// } - /// } - /// - /// let result = App::new("prog") - /// .arg(Arg::with_name("num") - /// .validator(is_numeric)) - /// .get_matches_from_safe(vec!["prog", "NotANumber"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::ValueValidation); - /// ``` - ValueValidation, - - /// Occurs when a user provides more values for an argument than were defined by setting - /// [`Arg::max_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("arg") - /// .multiple(true) - /// .max_values(2)) - /// .get_matches_from_safe(vec!["prog", "too", "many", "values"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooManyValues); - /// ``` - /// [`Arg::max_values`]: ./struct.Arg.html#method.max_values - TooManyValues, - - /// Occurs when the user provides fewer values for an argument than were defined by setting - /// [`Arg::min_values`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("some_opt") - /// .long("opt") - /// .min_values(3)) - /// .get_matches_from_safe(vec!["prog", "--opt", "too", "few"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::TooFewValues); - /// ``` - /// [`Arg::min_values`]: ./struct.Arg.html#method.min_values - TooFewValues, - - /// Occurs when the user provides a different number of values for an argument than what's - /// been defined by setting [`Arg::number_of_values`] or than was implicitly set by - /// [`Arg::value_names`]. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("some_opt") - /// .long("opt") - /// .takes_value(true) - /// .number_of_values(2)) - /// .get_matches_from_safe(vec!["prog", "--opt", "wrong"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::WrongNumberOfValues); - /// ``` - /// - /// [`Arg::number_of_values`]: ./struct.Arg.html#method.number_of_values - /// [`Arg::value_names`]: ./struct.Arg.html#method.value_names - WrongNumberOfValues, - - /// Occurs when the user provides two values which conflict with each other and can't be used - /// together. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .long("debug") - /// .conflicts_with("color")) - /// .arg(Arg::with_name("color") - /// .long("color")) - /// .get_matches_from_safe(vec!["prog", "--debug", "--color"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::ArgumentConflict); - /// ``` - ArgumentConflict, - - /// Occurs when the user does not provide one or more required arguments. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .required(true)) - /// .get_matches_from_safe(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingRequiredArgument); - /// ``` - MissingRequiredArgument, - - /// Occurs when a subcommand is required (as defined by [`AppSettings::SubcommandRequired`]), - /// but the user does not provide one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, AppSettings, SubCommand, ErrorKind}; - /// let err = App::new("prog") - /// .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); - /// # ; - /// ``` - /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired - MissingSubcommand, - - /// Occurs when either an argument or [`SubCommand`] is required, as defined by - /// [`AppSettings::ArgRequiredElseHelp`], but the user did not provide one. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, AppSettings, ErrorKind, SubCommand}; - /// let result = App::new("prog") - /// .setting(AppSettings::ArgRequiredElseHelp) - /// .subcommand(SubCommand::with_name("config") - /// .about("Used for configuration") - /// .arg(Arg::with_name("config_file") - /// .help("The configuration file to use"))) - /// .get_matches_from_safe(vec!["prog"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::MissingArgumentOrSubcommand); - /// ``` - /// [`SubCommand`]: ./struct.SubCommand.html - /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp - MissingArgumentOrSubcommand, - - /// Occurs when the user provides multiple values to an argument which doesn't allow that. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .arg(Arg::with_name("debug") - /// .long("debug") - /// .multiple(false)) - /// .get_matches_from_safe(vec!["prog", "--debug", "--debug"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::UnexpectedMultipleUsage); - /// ``` - UnexpectedMultipleUsage, - - /// Occurs when the user provides a value containing invalid UTF-8 for an argument and - /// [`AppSettings::StrictUtf8`] is set. - /// - /// # Platform Specific - /// - /// Non-Windows platforms only (such as Linux, Unix, macOS, etc.) - /// - /// # Examples - /// - #[cfg_attr(not(unix), doc = " ```ignore")] - #[cfg_attr(unix, doc = " ```")] - /// # use clap::{App, Arg, ErrorKind, AppSettings}; - /// # use std::os::unix::ffi::OsStringExt; - /// # use std::ffi::OsString; - /// let result = App::new("prog") - /// .setting(AppSettings::StrictUtf8) - /// .arg(Arg::with_name("utf8") - /// .short("u") - /// .takes_value(true)) - /// .get_matches_from_safe(vec![OsString::from("myprog"), - /// OsString::from("-u"), - /// OsString::from_vec(vec![0xE9])]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::InvalidUtf8); - /// ``` - /// [`AppSettings::StrictUtf8`]: ./enum.AppSettings.html#variant.StrictUtf8 - InvalidUtf8, - - /// Not a true "error" as it means `--help` or similar was used. - /// The help message will be sent to `stdout`. - /// - /// **Note**: If the help is displayed due to an error (such as missing subcommands) it will - /// be sent to `stderr` instead of `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .get_matches_from_safe(vec!["prog", "--help"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::HelpDisplayed); - /// ``` - HelpDisplayed, - - /// Not a true "error" as it means `--version` or similar was used. - /// The message will be sent to `stdout`. - /// - /// # Examples - /// - /// ```rust - /// # use clap::{App, Arg, ErrorKind}; - /// let result = App::new("prog") - /// .get_matches_from_safe(vec!["prog", "--version"]); - /// assert!(result.is_err()); - /// assert_eq!(result.unwrap_err().kind, ErrorKind::VersionDisplayed); - /// ``` - VersionDisplayed, - - /// Occurs when using the [`value_t!`] and [`values_t!`] macros to convert an argument value - /// into type `T`, but the argument you requested wasn't used. I.e. you asked for an argument - /// with name `config` to be converted, but `config` wasn't used by the user. - /// [`value_t!`]: ./macro.value_t!.html - /// [`values_t!`]: ./macro.values_t!.html - ArgumentNotFound, - - /// Represents an [I/O error]. - /// Can occur when writing to `stderr` or `stdout` or reading a configuration file. - /// [I/O error]: https://doc.rust-lang.org/std/io/struct.Error.html - Io, - - /// Represents a [Format error] (which is a part of [`Display`]). - /// Typically caused by writing to `stderr` or `stdout`. - /// - /// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html - /// [Format error]: https://doc.rust-lang.org/std/fmt/struct.Error.html - Format, -} - -/// Command Line Argument Parser Error -#[derive(Debug)] -pub struct Error { - /// Formatted error message - pub message: String, - /// The type of error - pub kind: ErrorKind, - /// Any additional information passed along, such as the argument name that caused the error - pub info: Option<Vec<String>>, -} - -impl Error { - /// Should the message be written to `stdout` or not - pub fn use_stderr(&self) -> bool { - match self.kind { - ErrorKind::HelpDisplayed | ErrorKind::VersionDisplayed => false, - _ => true, - } - } - - /// Prints the error to `stderr` and exits with a status of `1` - pub fn exit(&self) -> ! { - if self.use_stderr() { - wlnerr!("{}", self.message); - process::exit(1); - } - let out = io::stdout(); - writeln!(&mut out.lock(), "{}", self.message).expect("Error writing Error to stdout"); - process::exit(0); - } - - #[doc(hidden)] - pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> { write!(w, "{}", self.message) } - - #[doc(hidden)] - pub fn argument_conflict<O, U>( - arg: &AnyArg, - other: Option<O>, - usage: U, - color: ColorWhen, - ) -> Self - where - O: Into<String>, - U: Display, - { - let mut v = vec![arg.name().to_owned()]; - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The argument '{}' cannot be used with {}\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(&*arg.to_string()), - match other { - Some(name) => { - let n = name.into(); - v.push(n.clone()); - c.warning(format!("'{}'", n)) - } - None => c.none("one or more of the other specified arguments".to_owned()), - }, - usage, - c.good("--help") - ), - kind: ErrorKind::ArgumentConflict, - info: Some(v), - } - } - - #[doc(hidden)] - pub fn empty_value<U>(arg: &AnyArg, usage: U, color: ColorWhen) -> Self - where - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The argument '{}' requires a value but none was supplied\ - \n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(arg.to_string()), - usage, - c.good("--help") - ), - kind: ErrorKind::EmptyValue, - info: Some(vec![arg.name().to_owned()]), - } - } - - #[doc(hidden)] - pub fn invalid_value<B, G, U>( - bad_val: B, - good_vals: &[G], - arg: &AnyArg, - usage: U, - color: ColorWhen, - ) -> Self - where - B: AsRef<str>, - G: AsRef<str> + Display, - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - let suffix = suggestions::did_you_mean_value_suffix(bad_val.as_ref(), good_vals.iter()); - - let mut sorted = vec![]; - for v in good_vals { - let val = format!("{}", c.good(v)); - sorted.push(val); - } - sorted.sort(); - let valid_values = sorted.join(", "); - Error { - message: format!( - "{} '{}' isn't a valid value for '{}'\n\t\ - [possible values: {}]\n\ - {}\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(bad_val.as_ref()), - c.warning(arg.to_string()), - valid_values, - suffix.0, - usage, - c.good("--help") - ), - kind: ErrorKind::InvalidValue, - info: Some(vec![arg.name().to_owned(), bad_val.as_ref().to_owned()]), - } - } - - #[doc(hidden)] - pub fn invalid_subcommand<S, D, N, U>( - subcmd: S, - did_you_mean: D, - name: N, - usage: U, - color: ColorWhen, - ) -> Self - where - S: Into<String>, - D: AsRef<str> + Display, - N: Display, - U: Display, - { - let s = subcmd.into(); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The subcommand '{}' wasn't recognized\n\t\ - Did you mean '{}'?\n\n\ - If you believe you received this message in error, try \ - re-running with '{} {} {}'\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(&*s), - c.good(did_you_mean.as_ref()), - name, - c.good("--"), - &*s, - usage, - c.good("--help") - ), - kind: ErrorKind::InvalidSubcommand, - info: Some(vec![s]), - } - } - - #[doc(hidden)] - pub fn unrecognized_subcommand<S, N>(subcmd: S, name: N, color: ColorWhen) -> Self - where - S: Into<String>, - N: Display, - { - let s = subcmd.into(); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The subcommand '{}' wasn't recognized\n\n\ - {}\n\t\ - {} help <subcommands>...\n\n\ - For more information try {}", - c.error("error:"), - c.warning(&*s), - c.warning("USAGE:"), - name, - c.good("--help") - ), - kind: ErrorKind::UnrecognizedSubcommand, - info: Some(vec![s]), - } - } - - #[doc(hidden)] - pub fn missing_required_argument<R, U>(required: R, usage: U, color: ColorWhen) -> Self - where - R: Display, - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The following required arguments were not provided:{}\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - required, - usage, - c.good("--help") - ), - kind: ErrorKind::MissingRequiredArgument, - info: None, - } - } - - #[doc(hidden)] - pub fn missing_subcommand<N, U>(name: N, usage: U, color: ColorWhen) -> Self - where - N: AsRef<str> + Display, - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} '{}' requires a subcommand, but one was not provided\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(name), - usage, - c.good("--help") - ), - kind: ErrorKind::MissingSubcommand, - info: None, - } - } - - - #[doc(hidden)] - pub fn invalid_utf8<U>(usage: U, color: ColorWhen) -> Self - where - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} Invalid UTF-8 was detected in one or more arguments\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - usage, - c.good("--help") - ), - kind: ErrorKind::InvalidUtf8, - info: None, - } - } - - #[doc(hidden)] - pub fn too_many_values<V, U>(val: V, arg: &AnyArg, usage: U, color: ColorWhen) -> Self - where - V: AsRef<str> + Display + ToOwned, - U: Display, - { - let v = val.as_ref(); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The value '{}' was provided to '{}', but it wasn't expecting \ - any more values\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(v), - c.warning(arg.to_string()), - usage, - c.good("--help") - ), - kind: ErrorKind::TooManyValues, - info: Some(vec![arg.name().to_owned(), v.to_owned()]), - } - } - - #[doc(hidden)] - pub fn too_few_values<U>( - arg: &AnyArg, - min_vals: u64, - curr_vals: usize, - usage: U, - color: ColorWhen, - ) -> Self - where - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The argument '{}' requires at least {} values, but only {} w{} \ - provided\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(arg.to_string()), - c.warning(min_vals.to_string()), - c.warning(curr_vals.to_string()), - if curr_vals > 1 { "ere" } else { "as" }, - usage, - c.good("--help") - ), - kind: ErrorKind::TooFewValues, - info: Some(vec![arg.name().to_owned()]), - } - } - - #[doc(hidden)] - pub fn value_validation(arg: Option<&AnyArg>, err: String, color: ColorWhen) -> Self - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} Invalid value{}: {}", - c.error("error:"), - if let Some(a) = arg { - format!(" for '{}'", c.warning(a.to_string())) - } else { - "".to_string() - }, - err - ), - kind: ErrorKind::ValueValidation, - info: None, - } - } - - #[doc(hidden)] - pub fn value_validation_auto(err: String) -> Self { - let n: Option<&AnyArg> = None; - Error::value_validation(n, err, ColorWhen::Auto) - } - - #[doc(hidden)] - pub fn wrong_number_of_values<S, U>( - arg: &AnyArg, - num_vals: u64, - curr_vals: usize, - suffix: S, - usage: U, - color: ColorWhen, - ) -> Self - where - S: Display, - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The argument '{}' requires {} values, but {} w{} \ - provided\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(arg.to_string()), - c.warning(num_vals.to_string()), - c.warning(curr_vals.to_string()), - suffix, - usage, - c.good("--help") - ), - kind: ErrorKind::WrongNumberOfValues, - info: Some(vec![arg.name().to_owned()]), - } - } - - #[doc(hidden)] - pub fn unexpected_multiple_usage<U>(arg: &AnyArg, usage: U, color: ColorWhen) -> Self - where - U: Display, - { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} The argument '{}' was provided more than once, but cannot \ - be used multiple times\n\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(arg.to_string()), - usage, - c.good("--help") - ), - kind: ErrorKind::UnexpectedMultipleUsage, - info: Some(vec![arg.name().to_owned()]), - } - } - - #[doc(hidden)] - pub fn unknown_argument<A, U>(arg: A, did_you_mean: &str, usage: U, color: ColorWhen) -> Self - where - A: Into<String>, - U: Display, - { - let a = arg.into(); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!( - "{} Found argument '{}' which wasn't expected, or isn't valid in \ - this context{}\n\ - {}\n\n\ - For more information try {}", - c.error("error:"), - c.warning(&*a), - if did_you_mean.is_empty() { - "\n".to_owned() - } else { - format!("{}\n", did_you_mean) - }, - usage, - c.good("--help") - ), - kind: ErrorKind::UnknownArgument, - info: Some(vec![a]), - } - } - - #[doc(hidden)] - pub fn io_error(e: &Error, color: ColorWhen) -> Self { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: color, - }); - Error { - message: format!("{} {}", c.error("error:"), e.description()), - kind: ErrorKind::Io, - info: None, - } - } - - #[doc(hidden)] - pub fn argument_not_found_auto<A>(arg: A) -> Self - where - A: Into<String>, - { - let a = arg.into(); - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: ColorWhen::Auto, - }); - Error { - message: format!( - "{} The argument '{}' wasn't found", - c.error("error:"), - a.clone() - ), - kind: ErrorKind::ArgumentNotFound, - info: Some(vec![a]), - } - } - - /// Create an error with a custom description. - /// - /// This can be used in combination with `Error::exit` to exit your program - /// with a custom error message. - pub fn with_description(description: &str, kind: ErrorKind) -> Self { - let c = Colorizer::new(ColorizerOption { - use_stderr: true, - when: ColorWhen::Auto, - }); - Error { - message: format!("{} {}", c.error("error:"), description), - kind: kind, - info: None, - } - } -} - -impl StdError for Error { - fn description(&self) -> &str { &*self.message } -} - -impl Display for Error { - fn fmt(&self, f: &mut std_fmt::Formatter) -> std_fmt::Result { writeln!(f, "{}", self.message) } -} - -impl From<io::Error> for Error { - fn from(e: io::Error) -> Self { Error::with_description(e.description(), ErrorKind::Io) } -} - -impl From<std_fmt::Error> for Error { - fn from(e: std_fmt::Error) -> Self { - Error::with_description(e.description(), ErrorKind::Format) - } -} diff --git a/clap/src/fmt.rs b/clap/src/fmt.rs deleted file mode 100644 index 108a635..0000000 --- a/clap/src/fmt.rs +++ /dev/null @@ -1,189 +0,0 @@ -#[cfg(all(feature = "color", not(target_os = "windows")))] -use ansi_term::ANSIString; - -#[cfg(all(feature = "color", not(target_os = "windows")))] -use ansi_term::Colour::{Green, Red, Yellow}; - -#[cfg(feature = "color")] -use atty; -use std::fmt; -use std::env; - -#[doc(hidden)] -#[derive(Debug, Copy, Clone, PartialEq)] -pub enum ColorWhen { - Auto, - Always, - Never, -} - -#[cfg(feature = "color")] -pub fn is_a_tty(stderr: bool) -> bool { - debugln!("is_a_tty: stderr={:?}", stderr); - let stream = if stderr { - atty::Stream::Stderr - } else { - atty::Stream::Stdout - }; - atty::is(stream) -} - -#[cfg(not(feature = "color"))] -pub fn is_a_tty(_: bool) -> bool { - debugln!("is_a_tty;"); - false -} - -pub fn is_term_dumb() -> bool { env::var("TERM").ok() == Some(String::from("dumb")) } - -#[doc(hidden)] -pub struct ColorizerOption { - pub use_stderr: bool, - pub when: ColorWhen, -} - -#[doc(hidden)] -pub struct Colorizer { - when: ColorWhen, -} - -macro_rules! color { - ($_self:ident, $c:ident, $m:expr) => { - match $_self.when { - ColorWhen::Auto => Format::$c($m), - ColorWhen::Always => Format::$c($m), - ColorWhen::Never => Format::None($m), - } - }; -} - -impl Colorizer { - pub fn new(option: ColorizerOption) -> Colorizer { - let is_a_tty = is_a_tty(option.use_stderr); - let is_term_dumb = is_term_dumb(); - Colorizer { - when: match option.when { - ColorWhen::Auto if is_a_tty && !is_term_dumb => ColorWhen::Auto, - ColorWhen::Auto => ColorWhen::Never, - when => when, - } - } - } - - pub fn good<T>(&self, msg: T) -> Format<T> - where - T: fmt::Display + AsRef<str>, - { - debugln!("Colorizer::good;"); - color!(self, Good, msg) - } - - pub fn warning<T>(&self, msg: T) -> Format<T> - where - T: fmt::Display + AsRef<str>, - { - debugln!("Colorizer::warning;"); - color!(self, Warning, msg) - } - - pub fn error<T>(&self, msg: T) -> Format<T> - where - T: fmt::Display + AsRef<str>, - { - debugln!("Colorizer::error;"); - color!(self, Error, msg) - } - - pub fn none<T>(&self, msg: T) -> Format<T> - where - T: fmt::Display + AsRef<str>, - { - debugln!("Colorizer::none;"); - Format::None(msg) - } -} - -impl Default for Colorizer { - fn default() -> Self { - Colorizer::new(ColorizerOption { - use_stderr: true, - when: ColorWhen::Auto, - }) - } -} - -/// Defines styles for different types of error messages. Defaults to Error=Red, Warning=Yellow, -/// and Good=Green -#[derive(Debug)] -#[doc(hidden)] -pub enum Format<T> { - /// Defines the style used for errors, defaults to Red - Error(T), - /// Defines the style used for warnings, defaults to Yellow - Warning(T), - /// Defines the style used for good values, defaults to Green - Good(T), - /// Defines no formatting style - None(T), -} - -#[cfg(all(feature = "color", not(target_os = "windows")))] -impl<T: AsRef<str>> Format<T> { - fn format(&self) -> ANSIString { - match *self { - Format::Error(ref e) => Red.bold().paint(e.as_ref()), - Format::Warning(ref e) => Yellow.paint(e.as_ref()), - Format::Good(ref e) => Green.paint(e.as_ref()), - Format::None(ref e) => ANSIString::from(e.as_ref()), - } - } -} - -#[cfg(any(not(feature = "color"), target_os = "windows"))] -#[cfg_attr(feature = "lints", allow(match_same_arms))] -impl<T: fmt::Display> Format<T> { - fn format(&self) -> &T { - match *self { - Format::Error(ref e) => e, - Format::Warning(ref e) => e, - Format::Good(ref e) => e, - Format::None(ref e) => e, - } - } -} - - -#[cfg(all(feature = "color", not(target_os = "windows")))] -impl<T: AsRef<str>> fmt::Display for Format<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } -} - -#[cfg(any(not(feature = "color"), target_os = "windows"))] -impl<T: fmt::Display> fmt::Display for Format<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.format()) } -} - -#[cfg(all(test, feature = "color", not(target_os = "windows")))] -mod test { - use ansi_term::ANSIString; - use ansi_term::Colour::{Green, Red, Yellow}; - use super::Format; - - #[test] - fn colored_output() { - let err = Format::Error("error"); - assert_eq!( - &*format!("{}", err), - &*format!("{}", Red.bold().paint("error")) - ); - let good = Format::Good("good"); - assert_eq!(&*format!("{}", good), &*format!("{}", Green.paint("good"))); - let warn = Format::Warning("warn"); - assert_eq!(&*format!("{}", warn), &*format!("{}", Yellow.paint("warn"))); - let none = Format::None("none"); - assert_eq!( - &*format!("{}", none), - &*format!("{}", ANSIString::from("none")) - ); - } -} diff --git a/clap/src/lib.rs b/clap/src/lib.rs deleted file mode 100644 index 0a3e1bb..0000000 --- a/clap/src/lib.rs +++ /dev/null @@ -1,629 +0,0 @@ -// Copyright ⓒ 2015-2016 Kevin B. Knapp and [`clap-rs` contributors](https://github.com/clap-rs/clap/blob/master/CONTRIBUTORS.md). -// Licensed under the MIT license -// (see LICENSE or <http://opensource.org/licenses/MIT>) All files in the project carrying such -// notice may not be copied, modified, or distributed except according to those terms. - -//! `clap` is a simple-to-use, efficient, and full-featured library for parsing command line -//! arguments and subcommands when writing console/terminal applications. -//! -//! ## About -//! -//! `clap` is used to parse *and validate* the string of command line arguments provided by the user -//! at runtime. You provide the list of valid possibilities, and `clap` handles the rest. This means -//! you focus on your *applications* functionality, and less on the parsing and validating of -//! arguments. -//! -//! `clap` also provides the traditional version and help switches (or flags) 'for free' meaning -//! automatically with no configuration. It does this by checking list of valid possibilities you -//! supplied and adding only the ones you haven't already defined. If you are using subcommands, -//! `clap` will also auto-generate a `help` subcommand for you in addition to the traditional flags. -//! -//! Once `clap` parses the user provided string of arguments, it returns the matches along with any -//! applicable values. If the user made an error or typo, `clap` informs them of the mistake and -//! exits gracefully (or returns a `Result` type and allows you to perform any clean up prior to -//! exit). Because of this, you can make reasonable assumptions in your code about the validity of -//! the arguments. -//! -//! -//! ## Quick Example -//! -//! The following examples show a quick example of some of the very basic functionality of `clap`. -//! For more advanced usage, such as requirements, conflicts, groups, multiple values and -//! occurrences see the [documentation](https://docs.rs/clap/), [examples/] directory of -//! this repository or the [video tutorials]. -//! -//! **NOTE:** All of these examples are functionally the same, but show different styles in which to -//! use `clap` -//! -//! The first example shows a method that allows more advanced configuration options (not shown in -//! this small example), or even dynamically generating arguments when desired. The downside is it's -//! more verbose. -//! -//! ```no_run -//! // (Full example with detailed comments in examples/01b_quick_example.rs) -//! // -//! // This example demonstrates clap's full 'builder pattern' style of creating arguments which is -//! // more verbose, but allows easier editing, and at times more advanced options, or the possibility -//! // to generate arguments dynamically. -//! extern crate clap; -//! use clap::{Arg, App, SubCommand}; -//! -//! fn main() { -//! let matches = App::new("My Super Program") -//! .version("1.0") -//! .author("Kevin K. <kbknapp@gmail.com>") -//! .about("Does awesome things") -//! .arg(Arg::with_name("config") -//! .short("c") -//! .long("config") -//! .value_name("FILE") -//! .help("Sets a custom config file") -//! .takes_value(true)) -//! .arg(Arg::with_name("INPUT") -//! .help("Sets the input file to use") -//! .required(true) -//! .index(1)) -//! .arg(Arg::with_name("v") -//! .short("v") -//! .multiple(true) -//! .help("Sets the level of verbosity")) -//! .subcommand(SubCommand::with_name("test") -//! .about("controls testing features") -//! .version("1.3") -//! .author("Someone E. <someone_else@other.com>") -//! .arg(Arg::with_name("debug") -//! .short("d") -//! .help("print debug information verbosely"))) -//! .get_matches(); -//! -//! // Gets a value for config if supplied by user, or defaults to "default.conf" -//! let config = matches.value_of("config").unwrap_or("default.conf"); -//! println!("Value for config: {}", config); -//! -//! // Calling .unwrap() is safe here because "INPUT" is required (if "INPUT" wasn't -//! // required we could have used an 'if let' to conditionally get the value) -//! println!("Using input file: {}", matches.value_of("INPUT").unwrap()); -//! -//! // Vary the output based on how many times the user used the "verbose" flag -//! // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v' -//! match matches.occurrences_of("v") { -//! 0 => println!("No verbose info"), -//! 1 => println!("Some verbose info"), -//! 2 => println!("Tons of verbose info"), -//! 3 | _ => println!("Don't be crazy"), -//! } -//! -//! // You can handle information about subcommands by requesting their matches by name -//! // (as below), requesting just the name used, or both at the same time -//! if let Some(matches) = matches.subcommand_matches("test") { -//! if matches.is_present("debug") { -//! println!("Printing debug info..."); -//! } else { -//! println!("Printing normally..."); -//! } -//! } -//! -//! // more program logic goes here... -//! } -//! ``` -//! -//! The next example shows a far less verbose method, but sacrifices some of the advanced -//! configuration options (not shown in this small example). This method also takes a *very* minor -//! runtime penalty. -//! -//! ```no_run -//! // (Full example with detailed comments in examples/01a_quick_example.rs) -//! // -//! // This example demonstrates clap's "usage strings" method of creating arguments -//! // which is less verbose -//! extern crate clap; -//! use clap::{Arg, App, SubCommand}; -//! -//! fn main() { -//! let matches = App::new("myapp") -//! .version("1.0") -//! .author("Kevin K. <kbknapp@gmail.com>") -//! .about("Does awesome things") -//! .args_from_usage( -//! "-c, --config=[FILE] 'Sets a custom config file' -//! <INPUT> 'Sets the input file to use' -//! -v... 'Sets the level of verbosity'") -//! .subcommand(SubCommand::with_name("test") -//! .about("controls testing features") -//! .version("1.3") -//! .author("Someone E. <someone_else@other.com>") -//! .arg_from_usage("-d, --debug 'Print debug information'")) -//! .get_matches(); -//! -//! // Same as previous example... -//! } -//! ``` -//! -//! This third method shows how you can use a YAML file to build your CLI and keep your Rust source -//! tidy or support multiple localized translations by having different YAML files for each -//! localization. -//! -//! First, create the `cli.yml` file to hold your CLI options, but it could be called anything we -//! like: -//! -//! ```yaml -//! name: myapp -//! version: "1.0" -//! author: Kevin K. <kbknapp@gmail.com> -//! about: Does awesome things -//! args: -//! - config: -//! short: c -//! long: config -//! value_name: FILE -//! help: Sets a custom config file -//! takes_value: true -//! - INPUT: -//! help: Sets the input file to use -//! required: true -//! index: 1 -//! - verbose: -//! short: v -//! multiple: true -//! help: Sets the level of verbosity -//! subcommands: -//! - test: -//! about: controls testing features -//! version: "1.3" -//! author: Someone E. <someone_else@other.com> -//! args: -//! - debug: -//! short: d -//! help: print debug information -//! ``` -//! -//! Since this feature requires additional dependencies that not everyone may want, it is *not* -//! compiled in by default and we need to enable a feature flag in Cargo.toml: -//! -//! Simply change your `clap = "~2.27.0"` to `clap = {version = "~2.27.0", features = ["yaml"]}`. -//! -//! At last we create our `main.rs` file just like we would have with the previous two examples: -//! -//! ```ignore -//! // (Full example with detailed comments in examples/17_yaml.rs) -//! // -//! // This example demonstrates clap's building from YAML style of creating arguments which is far -//! // more clean, but takes a very small performance hit compared to the other two methods. -//! #[macro_use] -//! extern crate clap; -//! use clap::App; -//! -//! fn main() { -//! // The YAML file is found relative to the current file, similar to how modules are found -//! let yaml = load_yaml!("cli.yml"); -//! let matches = App::from_yaml(yaml).get_matches(); -//! -//! // Same as previous examples... -//! } -//! ``` -//! -//! Finally there is a macro version, which is like a hybrid approach offering the speed of the -//! builder pattern (the first example), but without all the verbosity. -//! -//! ```no_run -//! #[macro_use] -//! extern crate clap; -//! -//! fn main() { -//! let matches = clap_app!(myapp => -//! (version: "1.0") -//! (author: "Kevin K. <kbknapp@gmail.com>") -//! (about: "Does awesome things") -//! (@arg CONFIG: -c --config +takes_value "Sets a custom config file") -//! (@arg INPUT: +required "Sets the input file to use") -//! (@arg debug: -d ... "Sets the level of debugging information") -//! (@subcommand test => -//! (about: "controls testing features") -//! (version: "1.3") -//! (author: "Someone E. <someone_else@other.com>") -//! (@arg verbose: -v --verbose "Print test information verbosely") -//! ) -//! ).get_matches(); -//! -//! // Same as before... -//! } -//! ``` -//! -//! If you were to compile any of the above programs and run them with the flag `--help` or `-h` (or -//! `help` subcommand, since we defined `test` as a subcommand) the following would be output -//! -//! ```text -//! $ myprog --help -//! My Super Program 1.0 -//! Kevin K. <kbknapp@gmail.com> -//! Does awesome things -//! -//! USAGE: -//! MyApp [FLAGS] [OPTIONS] <INPUT> [SUBCOMMAND] -//! -//! FLAGS: -//! -h, --help Prints this message -//! -v Sets the level of verbosity -//! -V, --version Prints version information -//! -//! OPTIONS: -//! -c, --config <FILE> Sets a custom config file -//! -//! ARGS: -//! INPUT The input file to use -//! -//! SUBCOMMANDS: -//! help Prints this message -//! test Controls testing features -//! ``` -//! -//! **NOTE:** You could also run `myapp test --help` to see similar output and options for the -//! `test` subcommand. -//! -//! ## Try it! -//! -//! ### Pre-Built Test -//! -//! To try out the pre-built example, use the following steps: -//! -//! * Clone the repository `$ git clone https://github.com/clap-rs/clap && cd clap-rs/tests` -//! * Compile the example `$ cargo build --release` -//! * Run the help info `$ ./target/release/claptests --help` -//! * Play with the arguments! -//! -//! ### BYOB (Build Your Own Binary) -//! -//! To test out `clap`'s default auto-generated help/version follow these steps: -//! -//! * Create a new cargo project `$ cargo new fake --bin && cd fake` -//! * Add `clap` to your `Cargo.toml` -//! -//! ```toml -//! [dependencies] -//! clap = "2" -//! ``` -//! -//! * Add the following to your `src/main.rs` -//! -//! ```no_run -//! extern crate clap; -//! use clap::App; -//! -//! fn main() { -//! App::new("fake").version("v1.0-beta").get_matches(); -//! } -//! ``` -//! -//! * Build your program `$ cargo build --release` -//! * Run with help or version `$ ./target/release/fake --help` or `$ ./target/release/fake -//! --version` -//! -//! ## Usage -//! -//! For full usage, add `clap` as a dependency in your `Cargo.toml` (it is **highly** recommended to -//! use the `~major.minor.patch` style versions in your `Cargo.toml`, for more information see -//! [Compatibility Policy](#compatibility-policy)) to use from crates.io: -//! -//! ```toml -//! [dependencies] -//! clap = "~2.27.0" -//! ``` -//! -//! Or get the latest changes from the master branch at github: -//! -//! ```toml -//! [dependencies.clap] -//! git = "https://github.com/clap-rs/clap.git" -//! ``` -//! -//! Add `extern crate clap;` to your crate root. -//! -//! Define a list of valid arguments for your program (see the -//! [documentation](https://docs.rs/clap/) or [examples/] directory of this repo) -//! -//! Then run `cargo build` or `cargo update && cargo build` for your project. -//! -//! ### Optional Dependencies / Features -//! -//! #### Features enabled by default -//! -//! * `suggestions`: Turns on the `Did you mean '--myoption'?` feature for when users make typos. (builds dependency `strsim`) -//! * `color`: Turns on colored error messages. This feature only works on non-Windows OSs. (builds dependency `ansi-term` and `atty`) -//! * `wrap_help`: Wraps the help at the actual terminal width when -//! available, instead of 120 characters. (builds dependency `textwrap` -//! with feature `term_size`) -//! -//! To disable these, add this to your `Cargo.toml`: -//! -//! ```toml -//! [dependencies.clap] -//! version = "~2.27.0" -//! default-features = false -//! ``` -//! -//! You can also selectively enable only the features you'd like to include, by adding: -//! -//! ```toml -//! [dependencies.clap] -//! version = "~2.27.0" -//! default-features = false -//! -//! # Cherry-pick the features you'd like to use -//! features = [ "suggestions", "color" ] -//! ``` -//! -//! #### Opt-in features -//! -//! * **"yaml"**: Enables building CLIs from YAML documents. (builds dependency `yaml-rust`) -//! * **"unstable"**: Enables unstable `clap` features that may change from release to release -//! -//! ### Dependencies Tree -//! -//! The following graphic depicts `clap`s dependency graph (generated using -//! [cargo-graph](https://github.com/kbknapp/cargo-graph)). -//! -//! * **Dashed** Line: Optional dependency -//! * **Red** Color: **NOT** included by default (must use cargo `features` to enable) -//! * **Blue** Color: Dev dependency, only used while developing. -//! -//! ![clap dependencies](https://raw.githubusercontent.com/clap-rs/clap/master/clap_dep_graph.png) -//! -//! ### More Information -//! -//! You can find complete documentation on the [docs.rs](https://docs.rs/clap/) for this project. -//! -//! You can also find usage examples in the [examples/] directory of this repo. -//! -//! #### Video Tutorials -//! -//! There's also the video tutorial series [Argument Parsing with Rust v2][video tutorials]. -//! -//! These videos slowly trickle out as I finish them and currently a work in progress. -//! -//! ## How to Contribute -//! -//! Contributions are always welcome! And there is a multitude of ways in which you can help -//! depending on what you like to do, or are good at. Anything from documentation, code cleanup, -//! issue completion, new features, you name it, even filing issues is contributing and greatly -//! appreciated! -//! -//! Another really great way to help is if you find an interesting, or helpful way in which to use -//! `clap`. You can either add it to the [examples/] directory, or file an issue and tell -//! me. I'm all about giving credit where credit is due :) -//! -//! Please read [CONTRIBUTING.md](https://raw.githubusercontent.com/clap-rs/clap/master/.github/CONTRIBUTING.md) before you start contributing. -//! -//! -//! ### Testing Code -//! -//! To test with all features both enabled and disabled, you can run theese commands: -//! -//! ```text -//! $ cargo test --no-default-features -//! $ cargo test --features "yaml unstable" -//! ``` -//! -//! Alternatively, if you have [`just`](https://github.com/casey/just) installed you can run the -//! prebuilt recipes. *Not* using `just` is perfectly fine as well, it simply bundles commands -//! automatically. -//! -//! For example, to test the code, as above simply run: -//! -//! ```text -//! $ just run-tests -//! ``` -//! -//! From here on, I will list the appropriate `cargo` command as well as the `just` command. -//! -//! Sometimes it's helpful to only run a subset of the tests, which can be done via: -//! -//! ```text -//! $ cargo test --test <test_name> -//! -//! # Or -//! -//! $ just run-test <test_name> -//! ``` -//! -//! ### Linting Code -//! -//! During the CI process `clap` runs against many different lints using -//! [`clippy`](https://github.com/Manishearth/rust-clippy). In order to check if these lints pass on -//! your own computer prior to submitting a PR you'll need a nightly compiler. -//! -//! In order to check the code for lints run either: -//! -//! ```text -//! $ rustup override add nightly -//! $ cargo build --features lints -//! $ rustup override remove -//! -//! # Or -//! -//! $ just lint -//! ``` -//! -//! ### Debugging Code -//! -//! Another helpful technique is to see the `clap` debug output while developing features. In order -//! to see the debug output while running the full test suite or individual tests, run: -//! -//! ```text -//! $ cargo test --features debug -//! -//! # Or for individual tests -//! $ cargo test --test <test_name> --features debug -//! -//! # The corresponding just command for individual debugging tests is: -//! $ just debug <test_name> -//! ``` -//! -//! ### Goals -//! -//! There are a few goals of `clap` that I'd like to maintain throughout contributions. If your -//! proposed changes break, or go against any of these goals we'll discuss the changes further -//! before merging (but will *not* be ignored, all contributes are welcome!). These are by no means -//! hard-and-fast rules, as I'm no expert and break them myself from time to time (even if by -//! mistake or ignorance). -//! -//! * Remain backwards compatible when possible -//! - If backwards compatibility *must* be broken, use deprecation warnings if at all possible before -//! removing legacy code - This does not apply for security concerns -//! * Parse arguments quickly -//! - Parsing of arguments shouldn't slow down usage of the main program - This is also true of -//! generating help and usage information (although *slightly* less stringent, as the program is about -//! to exit) -//! * Try to be cognizant of memory usage -//! - Once parsing is complete, the memory footprint of `clap` should be low since the main program -//! is the star of the show -//! * `panic!` on *developer* error, exit gracefully on *end-user* error -//! -//! ### Compatibility Policy -//! -//! Because `clap` takes `SemVer` and compatibility seriously, this is the official policy regarding -//! breaking changes and previous versions of Rust. -//! -//! `clap` will pin the minimum required version of Rust to the CI builds. Bumping the minimum -//! version of Rust is considered a minor breaking change, meaning *at a minimum* the minor version -//! of `clap` will be bumped. -//! -//! In order to keep from being surprised by breaking changes, it is **highly** recommended to use -//! the `~major.minor.patch` style in your `Cargo.toml`: -//! -//! ```toml -//! [dependencies] clap = "~2.27.0" -//! ``` -//! -//! This will cause *only* the patch version to be updated upon a `cargo update` call, and therefore -//! cannot break due to new features, or bumped minimum versions of Rust. -//! -//! #### Minimum Version of Rust -//! -//! `clap` will officially support current stable Rust, minus two releases, but may work with prior -//! releases as well. For example, current stable Rust at the time of this writing is 1.21.0, -//! meaning `clap` is guaranteed to compile with 1.19.0 and beyond. At the 1.22.0 release, `clap` -//! will be guaranteed to compile with 1.20.0 and beyond, etc. -//! -//! Upon bumping the minimum version of Rust (assuming it's within the stable-2 range), it *must* be -//! clearly annotated in the `CHANGELOG.md` -//! -//! ## License -//! -//! `clap` is licensed under the MIT license. Please read the [LICENSE-MIT][license] file in -//! this repository for more information. -//! -//! [examples/]: https://github.com/clap-rs/clap/tree/master/examples -//! [video tutorials]: https://www.youtube.com/playlist?list=PLza5oFLQGTl2Z5T8g1pRkIynR3E0_pc7U -//! [license]: https://raw.githubusercontent.com/clap-rs/clap/master/LICENSE-MIT - -#![crate_type = "lib"] -#![doc(html_root_url = "https://docs.rs/clap/2.33.0")] -#![deny(missing_docs, missing_debug_implementations, missing_copy_implementations, trivial_casts, - unused_import_braces, unused_allocation)] -// Lints we'd like to deny but are currently failing for upstream crates -// unused_qualifications (bitflags, clippy) -// trivial_numeric_casts (bitflags) -#![cfg_attr(not(any(feature = "lints", feature = "nightly")), forbid(unstable_features))] -#![cfg_attr(feature = "lints", feature(plugin))] -#![cfg_attr(feature = "lints", plugin(clippy))] -// Need to disable deny(warnings) while deprecations are active -// #![cfg_attr(feature = "lints", deny(warnings))] -#![cfg_attr(feature = "lints", allow(cyclomatic_complexity))] -#![cfg_attr(feature = "lints", allow(doc_markdown))] -#![cfg_attr(feature = "lints", allow(explicit_iter_loop))] - -#[cfg(all(feature = "color", not(target_os = "windows")))] -extern crate ansi_term; -#[cfg(feature = "color")] -extern crate atty; -#[macro_use] -extern crate bitflags; -#[cfg(feature = "suggestions")] -extern crate strsim; -#[cfg(feature = "wrap_help")] -extern crate term_size; -extern crate textwrap; -extern crate unicode_width; -#[cfg(feature = "vec_map")] -extern crate vec_map; -#[cfg(feature = "yaml")] -extern crate yaml_rust; - -#[cfg(feature = "yaml")] -pub use yaml_rust::YamlLoader; -pub use args::{Arg, ArgGroup, ArgMatches, ArgSettings, OsValues, SubCommand, Values}; -pub use app::{App, AppSettings}; -pub use fmt::Format; -pub use errors::{Error, ErrorKind, Result}; -pub use completions::Shell; - -#[macro_use] -mod macros; -mod app; -mod args; -mod usage_parser; -mod fmt; -mod suggestions; -mod errors; -mod osstringext; -mod strext; -mod completions; -mod map; - -const INTERNAL_ERROR_MSG: &'static str = "Fatal internal error. Please consider filing a bug \ - report at https://github.com/clap-rs/clap/issues"; -const INVALID_UTF8: &'static str = "unexpected invalid UTF-8 code point"; - -#[cfg(unstable)] -pub use derive::{ArgEnum, ClapApp, FromArgMatches, IntoApp}; - -#[cfg(unstable)] -mod derive { - /// @TODO @release @docs - pub trait ClapApp: IntoApp + FromArgMatches + Sized { - /// @TODO @release @docs - fn parse() -> Self { Self::from_argmatches(Self::into_app().get_matches()) } - - /// @TODO @release @docs - fn parse_from<I, T>(argv: I) -> Self - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - Self::from_argmatches(Self::into_app().get_matches_from(argv)) - } - - /// @TODO @release @docs - fn try_parse() -> Result<Self, clap::Error> { - Self::try_from_argmatches(Self::into_app().get_matches_safe()?) - } - - - /// @TODO @release @docs - fn try_parse_from<I, T>(argv: I) -> Result<Self, clap::Error> - where - I: IntoIterator<Item = T>, - T: Into<OsString> + Clone, - { - Self::try_from_argmatches(Self::into_app().get_matches_from_safe(argv)?) - } - } - - /// @TODO @release @docs - pub trait IntoApp { - /// @TODO @release @docs - fn into_app<'a, 'b>() -> clap::App<'a, 'b>; - } - - /// @TODO @release @docs - pub trait FromArgMatches: Sized { - /// @TODO @release @docs - fn from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Self; - - /// @TODO @release @docs - fn try_from_argmatches<'a>(matches: clap::ArgMatches<'a>) -> Result<Self, clap::Error>; - } - - /// @TODO @release @docs - pub trait ArgEnum {} -} diff --git a/clap/src/macros.rs b/clap/src/macros.rs deleted file mode 100644 index 8198e19..0000000 --- a/clap/src/macros.rs +++ /dev/null @@ -1,1108 +0,0 @@ -/// 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. -/// # } -/// ``` -#[cfg(feature = "yaml")] -#[macro_export] -macro_rules! load_yaml { - ($yml:expr) => ( - &::clap::YamlLoader::load_from_str(include_str!($yml)).expect("failed to load YAML file")[0] - ); -} - -/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] from an -/// argument value. This macro returns a `Result<T,String>` which allows you as the developer to -/// decide what you'd like to do on a failed parse. There are two types of errors, parse failures -/// and those where the argument wasn't present (such as a non-required argument). You can use -/// it to get a single value, or a iterator as with the [`ArgMatches::values_of`] -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") -/// .get_matches(); -/// -/// let len = value_t!(matches.value_of("length"), u32).unwrap_or_else(|e| e.exit()); -/// let also_len = value_t!(matches, "length", u32).unwrap_or_else(|e| e.exit()); -/// -/// println!("{} + 2: {}", len, len + 2); -/// # } -/// ``` -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`ArgMatches::values_of`]: ./struct.ArgMatches.html#method.values_of -/// [`Result<T,String>`]: https://doc.rust-lang.org/std/result/enum.Result.html -#[macro_export] -macro_rules! value_t { - ($m:ident, $v:expr, $t:ty) => { - value_t!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - if let Some(v) = $m.value_of($v) { - match v.parse::<$t>() { - Ok(val) => Ok(val), - Err(_) => - Err(::clap::Error::value_validation_auto( - format!("The argument '{}' isn't a valid value", v))), - } - } else { - Err(::clap::Error::argument_not_found_auto($v)) - } - }; -} - -/// Convenience macro getting a typed value `T` where `T` implements [`std::str::FromStr`] or -/// exiting upon error, instead of returning a [`Result`] type. -/// -/// **NOTE:** This macro is for backwards compatibility sake. Prefer -/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`] -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[length] 'Set the length to use as a pos whole num, i.e. 20'") -/// .get_matches(); -/// -/// let len = value_t_or_exit!(matches.value_of("length"), u32); -/// let also_len = value_t_or_exit!(matches, "length", u32); -/// -/// println!("{} + 2: {}", len, len + 2); -/// # } -/// ``` -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Result`]: https://doc.rust-lang.org/std/result/enum.Result.html -/// [`value_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.value_t!.html -#[macro_export] -macro_rules! value_t_or_exit { - ($m:ident, $v:expr, $t:ty) => { - value_t_or_exit!($m.value_of($v), $t) - }; - ($m:ident.value_of($v:expr), $t:ty) => { - if let Some(v) = $m.value_of($v) { - match v.parse::<$t>() { - Ok(val) => val, - Err(_) => - ::clap::Error::value_validation_auto( - format!("The argument '{}' isn't a valid value", v)).exit(), - } - } else { - ::clap::Error::argument_not_found_auto($v).exit() - } - }; -} - -/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`] -/// This macro returns a [`clap::Result<Vec<T>>`] which allows you as the developer to decide -/// what you'd like to do on a failed parse. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") -/// .get_matches(); -/// -/// let vals = values_t!(matches.values_of("seq"), u32).unwrap_or_else(|e| e.exit()); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// -/// let vals = values_t!(matches, "seq", u32).unwrap_or_else(|e| e.exit()); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// # } -/// ``` -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html -/// [`clap::Result<Vec<T>>`]: ./type.Result.html -#[macro_export] -macro_rules! values_t { - ($m:ident, $v:expr, $t:ty) => { - values_t!($m.values_of($v), $t) - }; - ($m:ident.values_of($v:expr), $t:ty) => { - if let Some(vals) = $m.values_of($v) { - let mut tmp = vec![]; - let mut err = None; - for pv in vals { - match pv.parse::<$t>() { - Ok(rv) => tmp.push(rv), - Err(..) => { - err = Some(::clap::Error::value_validation_auto( - format!("The argument '{}' isn't a valid value", pv))); - break - } - } - } - match err { - Some(e) => Err(e), - None => Ok(tmp), - } - } else { - Err(::clap::Error::argument_not_found_auto($v)) - } - }; -} - -/// Convenience macro getting a typed value [`Vec<T>`] where `T` implements [`std::str::FromStr`] -/// or exiting upon error. -/// -/// **NOTE:** This macro is for backwards compatibility sake. Prefer -/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`] -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let matches = App::new("myapp") -/// .arg_from_usage("[seq]... 'A sequence of pos whole nums, i.e. 20 45'") -/// .get_matches(); -/// -/// let vals = values_t_or_exit!(matches.values_of("seq"), u32); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// -/// // type for example only -/// let vals: Vec<u32> = values_t_or_exit!(matches, "seq", u32); -/// for v in &vals { -/// println!("{} + 2: {}", v, v + 2); -/// } -/// # } -/// ``` -/// [`values_t!(/* ... */).unwrap_or_else(|e| e.exit())`]: ./macro.values_t!.html -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Vec<T>`]: https://doc.rust-lang.org/std/vec/struct.Vec.html -#[macro_export] -macro_rules! values_t_or_exit { - ($m:ident, $v:expr, $t:ty) => { - values_t_or_exit!($m.values_of($v), $t) - }; - ($m:ident.values_of($v:expr), $t:ty) => { - if let Some(vals) = $m.values_of($v) { - vals.map(|v| v.parse::<$t>().unwrap_or_else(|_|{ - ::clap::Error::value_validation_auto( - format!("One or more arguments aren't valid values")).exit() - })).collect::<Vec<$t>>() - } else { - ::clap::Error::argument_not_found_auto($v).exit() - } - }; -} - -// _clap_count_exprs! is derived from https://github.com/DanielKeep/rust-grabbag -// commit: 82a35ca5d9a04c3b920622d542104e3310ee5b07 -// License: MIT -// Copyright ⓒ 2015 grabbag contributors. -// Licensed under the MIT license (see LICENSE or <http://opensource.org -// /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of -// <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All -// files in the project carrying such notice may not be copied, modified, -// or distributed except according to those terms. -// -/// Counts the number of comma-delimited expressions passed to it. The result is a compile-time -/// evaluable expression, suitable for use as a static array size, or the value of a `const`. -/// -/// # Examples -/// -/// ``` -/// # #[macro_use] extern crate clap; -/// # fn main() { -/// const COUNT: usize = _clap_count_exprs!(a, 5+1, "hi there!".into_string()); -/// assert_eq!(COUNT, 3); -/// # } -/// ``` -#[macro_export] -macro_rules! _clap_count_exprs { - () => { 0 }; - ($e:expr) => { 1 }; - ($e:expr, $($es:expr),+) => { 1 + $crate::_clap_count_exprs!($($es),*) }; -} - -/// Convenience macro to generate more complete enums with variants to be used as a type when -/// parsing arguments. This enum also provides a `variants()` function which can be used to -/// retrieve a `Vec<&'static str>` of the variant names, as well as implementing [`FromStr`] and -/// [`Display`] automatically. -/// -/// **NOTE:** Case insensitivity is supported for ASCII characters only. It's highly recommended to -/// use [`Arg::case_insensitive(true)`] for args that will be used with these enums -/// -/// **NOTE:** This macro automatically implements [`std::str::FromStr`] and [`std::fmt::Display`] -/// -/// **NOTE:** These enums support pub (or not) and uses of the `#[derive()]` traits -/// -/// # Examples -/// -/// ```rust -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::{App, Arg}; -/// arg_enum!{ -/// #[derive(PartialEq, Debug)] -/// pub enum Foo { -/// Bar, -/// Baz, -/// Qux -/// } -/// } -/// // Foo enum can now be used via Foo::Bar, or Foo::Baz, etc -/// // and implements std::str::FromStr to use with the value_t! macros -/// fn main() { -/// let m = App::new("app") -/// .arg(Arg::from_usage("<foo> 'the foo'") -/// .possible_values(&Foo::variants()) -/// .case_insensitive(true)) -/// .get_matches_from(vec![ -/// "app", "baz" -/// ]); -/// let f = value_t!(m, "foo", Foo).unwrap_or_else(|e| e.exit()); -/// -/// assert_eq!(f, Foo::Baz); -/// } -/// ``` -/// [`FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`std::str::FromStr`]: https://doc.rust-lang.org/std/str/trait.FromStr.html -/// [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html -/// [`std::fmt::Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html -/// [`Arg::case_insensitive(true)`]: ./struct.Arg.html#method.case_insensitive -#[macro_export] -macro_rules! arg_enum { - (@as_item $($i:item)*) => ($($i)*); - (@impls ( $($tts:tt)* ) -> ($e:ident, $($v:ident),+)) => { - arg_enum!(@as_item - $($tts)* - - impl ::std::str::FromStr for $e { - type Err = String; - - fn from_str(s: &str) -> ::std::result::Result<Self,Self::Err> { - #[allow(deprecated, unused_imports)] - use ::std::ascii::AsciiExt; - match s { - $(stringify!($v) | - _ if s.eq_ignore_ascii_case(stringify!($v)) => Ok($e::$v)),+, - _ => Err({ - let v = vec![ - $(stringify!($v),)+ - ]; - format!("valid values: {}", - v.join(", ")) - }), - } - } - } - impl ::std::fmt::Display for $e { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { - $($e::$v => write!(f, stringify!($v)),)+ - } - } - } - impl $e { - #[allow(dead_code)] - pub fn variants() -> [&'static str; $crate::_clap_count_exprs!($(stringify!($v)),+)] { - [ - $(stringify!($v),)+ - ] - } - }); - }; - ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls - ($(#[$($m),+])+ - pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls - ($(#[$($m),+])+ - pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls - ($(#[$($m),+])+ - enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - ($(#[$($m:meta),+])+ enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls - ($(#[$($m),+])+ - enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (pub enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls - (pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (pub enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls - (pub enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (enum $e:ident { $($v:ident $(=$val:expr)*,)+ } ) => { - arg_enum!(@impls - (enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; - (enum $e:ident { $($v:ident $(=$val:expr)*),+ } ) => { - arg_enum!(@impls - (enum $e { - $($v$(=$val)*),+ - }) -> ($e, $($v),+) - ); - }; -} - -/// Allows you to pull the version from your Cargo.toml at compile time as -/// `MAJOR.MINOR.PATCH_PKGVERSION_PRE` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let m = App::new("app") -/// .version(crate_version!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(not(feature = "no_cargo"))] -#[macro_export] -macro_rules! crate_version { - () => { - env!("CARGO_PKG_VERSION") - }; -} - -/// Allows you to pull the authors for the app from your Cargo.toml at -/// compile time in the form: -/// `"author1 lastname <author1@example.com>:author2 lastname <author2@example.com>"` -/// -/// You can replace the colons with a custom separator by supplying a -/// replacement string, so, for example, -/// `crate_authors!(",\n")` would become -/// `"author1 lastname <author1@example.com>,\nauthor2 lastname <author2@example.com>,\nauthor3 lastname <author3@example.com>"` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let m = App::new("app") -/// .author(crate_authors!("\n")) -/// .get_matches(); -/// # } -/// ``` -#[cfg(not(feature = "no_cargo"))] -#[macro_export] -macro_rules! crate_authors { - ($sep:expr) => {{ - use std::ops::Deref; - use std::sync::{ONCE_INIT, Once}; - - #[allow(missing_copy_implementations)] - #[allow(dead_code)] - struct CargoAuthors { __private_field: () }; - - impl Deref for CargoAuthors { - type Target = str; - - #[allow(unsafe_code)] - fn deref(&self) -> &'static str { - static ONCE: Once = ONCE_INIT; - static mut VALUE: *const String = 0 as *const String; - - unsafe { - ONCE.call_once(|| { - let s = env!("CARGO_PKG_AUTHORS").replace(':', $sep); - VALUE = Box::into_raw(Box::new(s)); - }); - - &(*VALUE)[..] - } - } - } - - &*CargoAuthors { __private_field: () } - }}; - () => { - env!("CARGO_PKG_AUTHORS") - }; -} - -/// Allows you to pull the description from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let m = App::new("app") -/// .about(crate_description!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(not(feature = "no_cargo"))] -#[macro_export] -macro_rules! crate_description { - () => { - env!("CARGO_PKG_DESCRIPTION") - }; -} - -/// Allows you to pull the name from your Cargo.toml at compile time. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # use clap::App; -/// # fn main() { -/// let m = App::new(crate_name!()) -/// .get_matches(); -/// # } -/// ``` -#[cfg(not(feature = "no_cargo"))] -#[macro_export] -macro_rules! crate_name { - () => { - env!("CARGO_PKG_NAME") - }; -} - -/// Allows you to build the `App` instance from your Cargo.toml at compile time. -/// -/// Equivalent to using the `crate_*!` macros with their respective fields. -/// -/// Provided separator is for the [`crate_authors!`](macro.crate_authors.html) macro, -/// refer to the documentation therefor. -/// -/// **NOTE:** Changing the values in your `Cargo.toml` does not trigger a re-build automatically, -/// and therefore won't change the generated output until you recompile. -/// -/// **Pro Tip:** In some cases you can "trick" the compiler into triggering a rebuild when your -/// `Cargo.toml` is changed by including this in your `src/main.rs` file -/// `include_str!("../Cargo.toml");` -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # fn main() { -/// let m = app_from_crate!().get_matches(); -/// # } -/// ``` -#[cfg(not(feature = "no_cargo"))] -#[macro_export] -macro_rules! app_from_crate { - () => { - $crate::App::new(crate_name!()) - .version(crate_version!()) - .author(crate_authors!()) - .about(crate_description!()) - }; - ($sep:expr) => { - $crate::App::new(crate_name!()) - .version(crate_version!()) - .author(crate_authors!($sep)) - .about(crate_description!()) - }; -} - -/// Build `App`, `Arg`s, `SubCommand`s and `Group`s with Usage-string like input -/// but without the associated parsing runtime cost. -/// -/// `clap_app!` also supports several shorthand syntaxes. -/// -/// # Examples -/// -/// ```no_run -/// # #[macro_use] -/// # extern crate clap; -/// # fn main() { -/// let matches = clap_app!(myapp => -/// (version: "1.0") -/// (author: "Kevin K. <kbknapp@gmail.com>") -/// (about: "Does awesome things") -/// (@arg CONFIG: -c --config +takes_value "Sets a custom config file") -/// (@arg INPUT: +required "Sets the input file to use") -/// (@arg debug: -d ... "Sets the level of debugging information") -/// (@group difficulty => -/// (@arg hard: -h --hard "Sets hard mode") -/// (@arg normal: -n --normal "Sets normal mode") -/// (@arg easy: -e --easy "Sets easy mode") -/// ) -/// (@subcommand test => -/// (about: "controls testing features") -/// (version: "1.3") -/// (author: "Someone E. <someone_else@other.com>") -/// (@arg verbose: -v --verbose "Print test information verbosely") -/// ) -/// ) -/// .get_matches(); -/// # } -/// ``` -/// # Shorthand Syntax for Args -/// -/// * A single hyphen followed by a character (such as `-c`) sets the [`Arg::short`] -/// * A double hyphen followed by a character or word (such as `--config`) sets [`Arg::long`] -/// * If one wishes to use a [`Arg::long`] with a hyphen inside (i.e. `--config-file`), you -/// must use `--("config-file")` due to limitations of the Rust macro system. -/// * Three dots (`...`) sets [`Arg::multiple(true)`] -/// * Angled brackets after either a short or long will set [`Arg::value_name`] and -/// `Arg::required(true)` such as `--config <FILE>` = `Arg::value_name("FILE")` and -/// `Arg::required(true)` -/// * Square brackets after either a short or long will set [`Arg::value_name`] and -/// `Arg::required(false)` such as `--config [FILE]` = `Arg::value_name("FILE")` and -/// `Arg::required(false)` -/// * There are short hand syntaxes for Arg methods that accept booleans -/// * A plus sign will set that method to `true` such as `+required` = `Arg::required(true)` -/// * An exclamation will set that method to `false` such as `!required` = `Arg::required(false)` -/// * A `#{min, max}` will set [`Arg::min_values(min)`] and [`Arg::max_values(max)`] -/// * An asterisk (`*`) will set `Arg::required(true)` -/// * Curly brackets around a `fn` will set [`Arg::validator`] as in `{fn}` = `Arg::validator(fn)` -/// * An Arg method that accepts a string followed by square brackets will set that method such as -/// `conflicts_with[FOO]` will set `Arg::conflicts_with("FOO")` (note the lack of quotes around -/// `FOO` in the macro) -/// * An Arg method that takes a string and can be set multiple times (such as -/// [`Arg::conflicts_with`]) followed by square brackets and a list of values separated by spaces -/// will set that method such as `conflicts_with[FOO BAR BAZ]` will set -/// `Arg::conflicts_with("FOO")`, `Arg::conflicts_with("BAR")`, and `Arg::conflicts_with("BAZ")` -/// (note the lack of quotes around the values in the macro) -/// -/// # Shorthand Syntax for Groups -/// -/// * There are short hand syntaxes for `ArgGroup` methods that accept booleans -/// * A plus sign will set that method to `true` such as `+required` = `ArgGroup::required(true)` -/// * An exclamation will set that method to `false` such as `!required` = `ArgGroup::required(false)` -/// -/// [`Arg::short`]: ./struct.Arg.html#method.short -/// [`Arg::long`]: ./struct.Arg.html#method.long -/// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple -/// [`Arg::value_name`]: ./struct.Arg.html#method.value_name -/// [`Arg::min_values(min)`]: ./struct.Arg.html#method.min_values -/// [`Arg::max_values(max)`]: ./struct.Arg.html#method.max_values -/// [`Arg::validator`]: ./struct.Arg.html#method.validator -/// [`Arg::conflicts_with`]: ./struct.Arg.html#method.conflicts_with -#[macro_export] -macro_rules! clap_app { - (@app ($builder:expr)) => { $builder }; - (@app ($builder:expr) (@arg ($name:expr): $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - ($builder.arg( - clap_app!{ @arg ($crate::Arg::with_name($name)) (-) $($tail)* })) - $($tt)* - } - }; - (@app ($builder:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - ($builder.arg( - clap_app!{ @arg ($crate::Arg::with_name(stringify!($name))) (-) $($tail)* })) - $($tt)* - } - }; - (@app ($builder:expr) (@setting $setting:ident) $($tt:tt)*) => { - clap_app!{ @app - ($builder.setting($crate::AppSettings::$setting)) - $($tt)* - } - }; -// Treat the application builder as an argument to set its attributes - (@app ($builder:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { - clap_app!{ @app (clap_app!{ @arg ($builder) $($attr)* }) $($tt)* } - }; - (@app ($builder:expr) (@group $name:ident => $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name))) $($tail)* }) - $($tt)* - } - }; - (@app ($builder:expr) (@group $name:ident !$ident:ident => $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(false)) $($tail)* }) - $($tt)* - } - }; - (@app ($builder:expr) (@group $name:ident +$ident:ident => $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - (clap_app!{ @group ($builder, $crate::ArgGroup::with_name(stringify!($name)).$ident(true)) $($tail)* }) - $($tt)* - } - }; -// Handle subcommand creation - (@app ($builder:expr) (@subcommand $name:ident => $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @app - ($builder.subcommand( - clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* } - )) - $($tt)* - } - }; -// Yaml like function calls - used for setting various meta directly against the app - (@app ($builder:expr) ($ident:ident: $($v:expr),*) $($tt:tt)*) => { -// clap_app!{ @app ($builder.$ident($($v),*)) $($tt)* } - clap_app!{ @app - ($builder.$ident($($v),*)) - $($tt)* - } - }; - -// Add members to group and continue argument handling with the parent builder - (@group ($builder:expr, $group:expr)) => { $builder.group($group) }; - // Treat the group builder as an argument to set its attributes - (@group ($builder:expr, $group:expr) (@attributes $($attr:tt)*) $($tt:tt)*) => { - clap_app!{ @group ($builder, clap_app!{ @arg ($group) (-) $($attr)* }) $($tt)* } - }; - (@group ($builder:expr, $group:expr) (@arg $name:ident: $($tail:tt)*) $($tt:tt)*) => { - clap_app!{ @group - (clap_app!{ @app ($builder) (@arg $name: $($tail)*) }, - $group.arg(stringify!($name))) - $($tt)* - } - }; - -// No more tokens to munch - (@arg ($arg:expr) $modes:tt) => { $arg }; -// Shorthand tokens influenced by the usage_string - (@arg ($arg:expr) $modes:tt --($long:expr) $($tail:tt)*) => { - clap_app!{ @arg ($arg.long($long)) $modes $($tail)* } - }; - (@arg ($arg:expr) $modes:tt --$long:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.long(stringify!($long))) $modes $($tail)* } - }; - (@arg ($arg:expr) $modes:tt -$short:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.short(stringify!($short))) $modes $($tail)* } - }; - (@arg ($arg:expr) (-) <$var:ident> $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value +required $($tail)* } - }; - (@arg ($arg:expr) (+) <$var:ident> $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } - }; - (@arg ($arg:expr) (-) [$var:ident] $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) +takes_value $($tail)* } - }; - (@arg ($arg:expr) (+) [$var:ident] $($tail:tt)*) => { - clap_app!{ @arg ($arg.value_name(stringify!($var))) (+) $($tail)* } - }; - (@arg ($arg:expr) $modes:tt ... $($tail:tt)*) => { - clap_app!{ @arg ($arg) $modes +multiple $($tail)* } - }; -// Shorthand magic - (@arg ($arg:expr) $modes:tt #{$n:expr, $m:expr} $($tail:tt)*) => { - clap_app!{ @arg ($arg) $modes min_values($n) max_values($m) $($tail)* } - }; - (@arg ($arg:expr) $modes:tt * $($tail:tt)*) => { - clap_app!{ @arg ($arg) $modes +required $($tail)* } - }; -// !foo -> .foo(false) - (@arg ($arg:expr) $modes:tt !$ident:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.$ident(false)) $modes $($tail)* } - }; -// +foo -> .foo(true) - (@arg ($arg:expr) $modes:tt +$ident:ident $($tail:tt)*) => { - clap_app!{ @arg ($arg.$ident(true)) $modes $($tail)* } - }; -// Validator - (@arg ($arg:expr) $modes:tt {$fn_:expr} $($tail:tt)*) => { - clap_app!{ @arg ($arg.validator($fn_)) $modes $($tail)* } - }; - (@as_expr $expr:expr) => { $expr }; -// Help - (@arg ($arg:expr) $modes:tt $desc:tt) => { $arg.help(clap_app!{ @as_expr $desc }) }; -// Handle functions that need to be called multiple times for each argument - (@arg ($arg:expr) $modes:tt $ident:ident[$($target:ident)*] $($tail:tt)*) => { - clap_app!{ @arg ($arg $( .$ident(stringify!($target)) )*) $modes $($tail)* } - }; -// Inherit builder's functions, e.g. `index(2)`, `requires_if("val", "arg")` - (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr),*) $($tail:tt)*) => { - clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } - }; -// Inherit builder's functions with trailing comma, e.g. `index(2,)`, `requires_if("val", "arg",)` - (@arg ($arg:expr) $modes:tt $ident:ident($($expr:expr,)*) $($tail:tt)*) => { - clap_app!{ @arg ($arg.$ident($($expr),*)) $modes $($tail)* } - }; - -// Build a subcommand outside of an app. - (@subcommand $name:ident => $($tail:tt)*) => { - clap_app!{ @app ($crate::SubCommand::with_name(stringify!($name))) $($tail)* } - }; -// Start the magic - (($name:expr) => $($tail:tt)*) => {{ - clap_app!{ @app ($crate::App::new($name)) $($tail)*} - }}; - - ($name:ident => $($tail:tt)*) => {{ - clap_app!{ @app ($crate::App::new(stringify!($name))) $($tail)*} - }}; -} - -macro_rules! impl_settings { - ($n:ident, $($v:ident => $c:path),+) => { - pub fn set(&mut self, s: $n) { - match s { - $($n::$v => self.0.insert($c)),+ - } - } - - pub fn unset(&mut self, s: $n) { - match s { - $($n::$v => self.0.remove($c)),+ - } - } - - pub fn is_set(&self, s: $n) -> bool { - match s { - $($n::$v => self.0.contains($c)),+ - } - } - }; -} - -// Convenience for writing to stderr thanks to https://github.com/BurntSushi -macro_rules! wlnerr( - ($($arg:tt)*) => ({ - use std::io::{Write, stderr}; - writeln!(&mut stderr(), $($arg)*).ok(); - }) -); - -#[cfg(feature = "debug")] -#[cfg_attr(feature = "debug", macro_use)] -#[cfg_attr(feature = "debug", allow(unused_macros))] -mod debug_macros { - macro_rules! debugln { - ($fmt:expr) => (println!(concat!("DEBUG:clap:", $fmt))); - ($fmt:expr, $($arg:tt)*) => (println!(concat!("DEBUG:clap:",$fmt), $($arg)*)); - } - macro_rules! sdebugln { - ($fmt:expr) => (println!($fmt)); - ($fmt:expr, $($arg:tt)*) => (println!($fmt, $($arg)*)); - } - macro_rules! debug { - ($fmt:expr) => (print!(concat!("DEBUG:clap:", $fmt))); - ($fmt:expr, $($arg:tt)*) => (print!(concat!("DEBUG:clap:",$fmt), $($arg)*)); - } - macro_rules! sdebug { - ($fmt:expr) => (print!($fmt)); - ($fmt:expr, $($arg:tt)*) => (print!($fmt, $($arg)*)); - } -} - -#[cfg(not(feature = "debug"))] -#[cfg_attr(not(feature = "debug"), macro_use)] -mod debug_macros { - macro_rules! debugln { - ($fmt:expr) => (); - ($fmt:expr, $($arg:tt)*) => (); - } - macro_rules! sdebugln { - ($fmt:expr) => (); - ($fmt:expr, $($arg:tt)*) => (); - } - macro_rules! debug { - ($fmt:expr) => (); - ($fmt:expr, $($arg:tt)*) => (); - } -} - -// Helper/deduplication macro for printing the correct number of spaces in help messages -// used in: -// src/args/arg_builder/*.rs -// src/app/mod.rs -macro_rules! write_nspaces { - ($dst:expr, $num:expr) => ({ - debugln!("write_spaces!: num={}", $num); - for _ in 0..$num { - $dst.write_all(b" ")?; - } - }) -} - -// convenience macro for remove an item from a vec -//macro_rules! vec_remove_all { -// ($vec:expr, $to_rem:expr) => { -// debugln!("vec_remove_all! to_rem={:?}", $to_rem); -// for i in (0 .. $vec.len()).rev() { -// let should_remove = $to_rem.any(|name| name == &$vec[i]); -// if should_remove { $vec.swap_remove(i); } -// } -// }; -//} -macro_rules! find_from { - ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{ - let mut ret = None; - for k in $matcher.arg_names() { - if let Some(f) = find_by_name!($_self, k, flags, iter) { - if let Some(ref v) = f.$from() { - if v.contains($arg_name) { - ret = Some(f.to_string()); - } - } - } - if let Some(o) = find_by_name!($_self, k, opts, iter) { - if let Some(ref v) = o.$from() { - if v.contains(&$arg_name) { - ret = Some(o.to_string()); - } - } - } - if let Some(pos) = find_by_name!($_self, k, positionals, values) { - if let Some(ref v) = pos.$from() { - if v.contains($arg_name) { - ret = Some(pos.b.name.to_owned()); - } - } - } - } - ret - }}; -} - -//macro_rules! find_name_from { -// ($_self:expr, $arg_name:expr, $from:ident, $matcher:expr) => {{ -// let mut ret = None; -// for k in $matcher.arg_names() { -// if let Some(f) = find_by_name!($_self, k, flags, iter) { -// if let Some(ref v) = f.$from() { -// if v.contains($arg_name) { -// ret = Some(f.b.name); -// } -// } -// } -// if let Some(o) = find_by_name!($_self, k, opts, iter) { -// if let Some(ref v) = o.$from() { -// if v.contains(&$arg_name) { -// ret = Some(o.b.name); -// } -// } -// } -// if let Some(pos) = find_by_name!($_self, k, positionals, values) { -// if let Some(ref v) = pos.$from() { -// if v.contains($arg_name) { -// ret = Some(pos.b.name); -// } -// } -// } -// } -// ret -// }}; -//} - - -macro_rules! find_any_by_name { - ($p:expr, $name:expr) => { - { - fn as_trait_obj<'a, 'b, T: AnyArg<'a, 'b>>(x: &T) -> &AnyArg<'a, 'b> { x } - find_by_name!($p, $name, flags, iter).map(as_trait_obj).or( - find_by_name!($p, $name, opts, iter).map(as_trait_obj).or( - find_by_name!($p, $name, positionals, values).map(as_trait_obj) - ) - ) - } - } -} -// Finds an arg by name -macro_rules! find_by_name { - ($p:expr, $name:expr, $what:ident, $how:ident) => { - $p.$what.$how().find(|o| o.b.name == $name) - } -} - -// Finds an option including if it's aliased -macro_rules! find_opt_by_long { - (@os $_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, opts) - }}; - ($_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, opts) - }}; -} - -macro_rules! find_flag_by_long { - (@os $_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, flags) - }}; - ($_self:ident, $long:expr) => {{ - _find_by_long!($_self, $long, flags) - }}; -} - -macro_rules! _find_by_long { - ($_self:ident, $long:expr, $what:ident) => {{ - $_self.$what - .iter() - .filter(|a| a.s.long.is_some()) - .find(|a| { - a.s.long.unwrap() == $long || - (a.s.aliases.is_some() && - a.s - .aliases - .as_ref() - .unwrap() - .iter() - .any(|&(alias, _)| alias == $long)) - }) - }} -} - -// Finds an option -macro_rules! find_opt_by_short { - ($_self:ident, $short:expr) => {{ - _find_by_short!($_self, $short, opts) - }} -} - -macro_rules! find_flag_by_short { - ($_self:ident, $short:expr) => {{ - _find_by_short!($_self, $short, flags) - }} -} - -macro_rules! _find_by_short { - ($_self:ident, $short:expr, $what:ident) => {{ - $_self.$what - .iter() - .filter(|a| a.s.short.is_some()) - .find(|a| a.s.short.unwrap() == $short) - }} -} - -macro_rules! find_subcmd { - ($_self:expr, $sc:expr) => {{ - $_self.subcommands - .iter() - .find(|s| { - &*s.p.meta.name == $sc || - (s.p.meta.aliases.is_some() && - s.p - .meta - .aliases - .as_ref() - .unwrap() - .iter() - .any(|&(n, _)| n == $sc)) - }) - }}; -} - -macro_rules! shorts { - ($_self:ident) => {{ - _shorts_longs!($_self, short) - }}; -} - - -macro_rules! longs { - ($_self:ident) => {{ - _shorts_longs!($_self, long) - }}; -} - -macro_rules! _shorts_longs { - ($_self:ident, $what:ident) => {{ - $_self.flags - .iter() - .filter(|f| f.s.$what.is_some()) - .map(|f| f.s.$what.as_ref().unwrap()) - .chain($_self.opts.iter() - .filter(|o| o.s.$what.is_some()) - .map(|o| o.s.$what.as_ref().unwrap())) - }}; -} - -macro_rules! arg_names { - ($_self:ident) => {{ - _names!(@args $_self) - }}; -} - -macro_rules! sc_names { - ($_self:ident) => {{ - _names!(@sc $_self) - }}; -} - -macro_rules! _names { - (@args $_self:ident) => {{ - $_self.flags - .iter() - .map(|f| &*f.b.name) - .chain($_self.opts.iter() - .map(|o| &*o.b.name) - .chain($_self.positionals.values() - .map(|p| &*p.b.name))) - }}; - (@sc $_self:ident) => {{ - $_self.subcommands - .iter() - .map(|s| &*s.p.meta.name) - .chain($_self.subcommands - .iter() - .filter(|s| s.p.meta.aliases.is_some()) - .flat_map(|s| s.p.meta.aliases.as_ref().unwrap().iter().map(|&(n, _)| n))) - - }} -} diff --git a/clap/src/map.rs b/clap/src/map.rs deleted file mode 100644 index 063a860..0000000 --- a/clap/src/map.rs +++ /dev/null @@ -1,74 +0,0 @@ -#[cfg(feature = "vec_map")] -pub use vec_map::{Values, VecMap}; - -#[cfg(not(feature = "vec_map"))] -pub use self::vec_map::{Values, VecMap}; - -#[cfg(not(feature = "vec_map"))] -mod vec_map { - use std::collections::BTreeMap; - use std::collections::btree_map; - use std::fmt::{self, Debug, Formatter}; - - #[derive(Clone, Default, Debug)] - pub struct VecMap<V> { - inner: BTreeMap<usize, V>, - } - - impl<V> VecMap<V> { - pub fn new() -> Self { - VecMap { - inner: Default::default(), - } - } - - pub fn len(&self) -> usize { self.inner.len() } - - pub fn is_empty(&self) -> bool { self.inner.is_empty() } - - pub fn insert(&mut self, key: usize, value: V) -> Option<V> { - self.inner.insert(key, value) - } - - pub fn values(&self) -> Values<V> { self.inner.values() } - - pub fn iter(&self) -> Iter<V> { - Iter { - inner: self.inner.iter(), - } - } - - pub fn contains_key(&self, key: usize) -> bool { self.inner.contains_key(&key) } - - pub fn entry(&mut self, key: usize) -> Entry<V> { self.inner.entry(key) } - - pub fn get(&self, key: usize) -> Option<&V> { self.inner.get(&key) } - } - - pub type Values<'a, V> = btree_map::Values<'a, usize, V>; - - pub type Entry<'a, V> = btree_map::Entry<'a, usize, V>; - - #[derive(Clone)] - pub struct Iter<'a, V: 'a> { - inner: btree_map::Iter<'a, usize, V>, - } - - impl<'a, V: 'a + Debug> Debug for Iter<'a, V> { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - f.debug_list().entries(self.inner.clone()).finish() - } - } - - impl<'a, V: 'a> Iterator for Iter<'a, V> { - type Item = (usize, &'a V); - - fn next(&mut self) -> Option<Self::Item> { self.inner.next().map(|(k, v)| (*k, v)) } - } - - impl<'a, V: 'a> DoubleEndedIterator for Iter<'a, V> { - fn next_back(&mut self) -> Option<Self::Item> { - self.inner.next_back().map(|(k, v)| (*k, v)) - } - } -} diff --git a/clap/src/osstringext.rs b/clap/src/osstringext.rs deleted file mode 100644 index 061c01d..0000000 --- a/clap/src/osstringext.rs +++ /dev/null @@ -1,119 +0,0 @@ -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -use INVALID_UTF8; -use std::ffi::OsStr; -#[cfg(not(any(target_os = "windows", target_arch = "wasm32")))] -use std::os::unix::ffi::OsStrExt; - -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -pub trait OsStrExt3 { - fn from_bytes(b: &[u8]) -> &Self; - fn as_bytes(&self) -> &[u8]; -} - -#[doc(hidden)] -pub trait OsStrExt2 { - fn starts_with(&self, s: &[u8]) -> bool; - fn split_at_byte(&self, b: u8) -> (&OsStr, &OsStr); - fn split_at(&self, i: usize) -> (&OsStr, &OsStr); - fn trim_left_matches(&self, b: u8) -> &OsStr; - fn contains_byte(&self, b: u8) -> bool; - fn split(&self, b: u8) -> OsSplit; -} - -#[cfg(any(target_os = "windows", target_arch = "wasm32"))] -impl OsStrExt3 for OsStr { - fn from_bytes(b: &[u8]) -> &Self { - use std::mem; - unsafe { mem::transmute(b) } - } - fn as_bytes(&self) -> &[u8] { - self.to_str().map(|s| s.as_bytes()).expect(INVALID_UTF8) - } -} - -impl OsStrExt2 for OsStr { - fn starts_with(&self, s: &[u8]) -> bool { - self.as_bytes().starts_with(s) - } - - fn contains_byte(&self, byte: u8) -> bool { - for b in self.as_bytes() { - if b == &byte { - return true; - } - } - false - } - - fn split_at_byte(&self, byte: u8) -> (&OsStr, &OsStr) { - for (i, b) in self.as_bytes().iter().enumerate() { - if b == &byte { - return ( - OsStr::from_bytes(&self.as_bytes()[..i]), - OsStr::from_bytes(&self.as_bytes()[i + 1..]), - ); - } - } - ( - &*self, - OsStr::from_bytes(&self.as_bytes()[self.len()..self.len()]), - ) - } - - fn trim_left_matches(&self, byte: u8) -> &OsStr { - let mut found = false; - for (i, b) in self.as_bytes().iter().enumerate() { - if b != &byte { - return OsStr::from_bytes(&self.as_bytes()[i..]); - } else { - found = true; - } - } - if found { - return OsStr::from_bytes(&self.as_bytes()[self.len()..]); - } - &*self - } - - fn split_at(&self, i: usize) -> (&OsStr, &OsStr) { - ( - OsStr::from_bytes(&self.as_bytes()[..i]), - OsStr::from_bytes(&self.as_bytes()[i..]), - ) - } - - fn split(&self, b: u8) -> OsSplit { - OsSplit { - sep: b, - val: self.as_bytes(), - pos: 0, - } - } -} - -#[doc(hidden)] -#[derive(Clone, Debug)] -pub struct OsSplit<'a> { - sep: u8, - val: &'a [u8], - pos: usize, -} - -impl<'a> Iterator for OsSplit<'a> { - type Item = &'a OsStr; - - fn next(&mut self) -> Option<&'a OsStr> { - debugln!("OsSplit::next: self={:?}", self); - if self.pos == self.val.len() { - return None; - } - let start = self.pos; - for b in &self.val[start..] { - self.pos += 1; - if *b == self.sep { - return Some(OsStr::from_bytes(&self.val[start..self.pos - 1])); - } - } - Some(OsStr::from_bytes(&self.val[start..])) - } -} diff --git a/clap/src/strext.rs b/clap/src/strext.rs deleted file mode 100644 index 6f81367..0000000 --- a/clap/src/strext.rs +++ /dev/null @@ -1,16 +0,0 @@ -pub trait _StrExt { - fn _is_char_boundary(&self, index: usize) -> bool; -} - -impl _StrExt for str { - #[inline] - fn _is_char_boundary(&self, index: usize) -> bool { - if index == self.len() { - return true; - } - match self.as_bytes().get(index) { - None => false, - Some(&b) => b < 128 || b >= 192, - } - } -} diff --git a/clap/src/suggestions.rs b/clap/src/suggestions.rs deleted file mode 100644 index 06071d2..0000000 --- a/clap/src/suggestions.rs +++ /dev/null @@ -1,147 +0,0 @@ -use app::App; -// Third Party -#[cfg(feature = "suggestions")] -use strsim; - -// Internal -use fmt::Format; - -/// Produces a string from a given list of possible values which is similar to -/// the passed in value `v` with a certain confidence. -/// Thus in a list of possible values like ["foo", "bar"], the value "fop" will yield -/// `Some("foo")`, whereas "blark" would yield `None`. -#[cfg(feature = "suggestions")] -#[cfg_attr(feature = "lints", allow(needless_lifetimes))] -pub fn did_you_mean<'a, T: ?Sized, I>(v: &str, possible_values: I) -> Option<&'a str> -where - T: AsRef<str> + 'a, - I: IntoIterator<Item = &'a T>, -{ - let mut candidate: Option<(f64, &str)> = None; - for pv in possible_values { - let confidence = strsim::jaro_winkler(v, pv.as_ref()); - if confidence > 0.8 && (candidate.is_none() || (candidate.as_ref().unwrap().0 < confidence)) - { - candidate = Some((confidence, pv.as_ref())); - } - } - match candidate { - None => None, - Some((_, candidate)) => Some(candidate), - } -} - -#[cfg(not(feature = "suggestions"))] -pub fn did_you_mean<'a, T: ?Sized, I>(_: &str, _: I) -> Option<&'a str> -where - T: AsRef<str> + 'a, - I: IntoIterator<Item = &'a T>, -{ - None -} - -/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase -#[cfg_attr(feature = "lints", allow(needless_lifetimes))] -pub fn did_you_mean_flag_suffix<'z, T, I>( - arg: &str, - args_rest: &'z [&str], - longs: I, - subcommands: &'z [App], -) -> (String, Option<&'z str>) -where - T: AsRef<str> + 'z, - I: IntoIterator<Item = &'z T>, -{ - if let Some(candidate) = did_you_mean(arg, longs) { - let suffix = format!( - "\n\tDid you mean {}{}?", - Format::Good("--"), - Format::Good(candidate) - ); - return (suffix, Some(candidate)); - } - - subcommands - .into_iter() - .filter_map(|subcommand| { - let opts = subcommand - .p - .flags - .iter() - .filter_map(|f| f.s.long) - .chain(subcommand.p.opts.iter().filter_map(|o| o.s.long)); - - let candidate = match did_you_mean(arg, opts) { - Some(candidate) => candidate, - None => return None - }; - let score = match args_rest.iter().position(|x| *x == subcommand.get_name()) { - Some(score) => score, - None => return None - }; - - let suffix = format!( - "\n\tDid you mean to put '{}{}' after the subcommand '{}'?", - Format::Good("--"), - Format::Good(candidate), - Format::Good(subcommand.get_name()) - ); - - Some((score, (suffix, Some(candidate)))) - }) - .min_by_key(|&(score, _)| score) - .map(|(_, suggestion)| suggestion) - .unwrap_or_else(|| (String::new(), None)) -} - -/// Returns a suffix that can be empty, or is the standard 'did you mean' phrase -pub fn did_you_mean_value_suffix<'z, T, I>(arg: &str, values: I) -> (String, Option<&'z str>) -where - T: AsRef<str> + 'z, - I: IntoIterator<Item = &'z T>, -{ - match did_you_mean(arg, values) { - Some(candidate) => { - let suffix = format!("\n\tDid you mean '{}'?", Format::Good(candidate)); - (suffix, Some(candidate)) - } - None => (String::new(), None), - } -} - -#[cfg(all(test, features = "suggestions"))] -mod test { - use super::*; - - #[test] - fn possible_values_match() { - let p_vals = ["test", "possible", "values"]; - assert_eq!(did_you_mean("tst", p_vals.iter()), Some("test")); - } - - #[test] - fn possible_values_nomatch() { - let p_vals = ["test", "possible", "values"]; - assert!(did_you_mean("hahaahahah", p_vals.iter()).is_none()); - } - - #[test] - fn suffix_long() { - let p_vals = ["test", "possible", "values"]; - let suffix = "\n\tDid you mean \'--test\'?"; - assert_eq!( - did_you_mean_flag_suffix("tst", p_vals.iter(), []), - (suffix, Some("test")) - ); - } - - #[test] - fn suffix_enum() { - let p_vals = ["test", "possible", "values"]; - let suffix = "\n\tDid you mean \'test\'?"; - assert_eq!( - did_you_mean_value_suffix("tst", p_vals.iter()), - (suffix, Some("test")) - ); - } -} diff --git a/clap/src/usage_parser.rs b/clap/src/usage_parser.rs deleted file mode 100644 index f6d5ac6..0000000 --- a/clap/src/usage_parser.rs +++ /dev/null @@ -1,1347 +0,0 @@ -// Internal -use INTERNAL_ERROR_MSG; -use args::Arg; -use args::settings::ArgSettings; -use map::VecMap; - -#[derive(PartialEq, Debug)] -enum UsageToken { - Name, - ValName, - Short, - Long, - Help, - Multiple, - Unknown, -} - -#[doc(hidden)] -#[derive(Debug)] -pub struct UsageParser<'a> { - usage: &'a str, - pos: usize, - start: usize, - prev: UsageToken, - explicit_name_set: bool, -} - -impl<'a> UsageParser<'a> { - fn new(usage: &'a str) -> Self { - debugln!("UsageParser::new: usage={:?}", usage); - UsageParser { - usage: usage, - pos: 0, - start: 0, - prev: UsageToken::Unknown, - explicit_name_set: false, - } - } - - pub fn from_usage(usage: &'a str) -> Self { - debugln!("UsageParser::from_usage;"); - UsageParser::new(usage) - } - - pub fn parse(mut self) -> Arg<'a, 'a> { - debugln!("UsageParser::parse;"); - let mut arg = Arg::default(); - loop { - debugln!("UsageParser::parse:iter: pos={};", self.pos); - self.stop_at(token); - if let Some(&c) = self.usage.as_bytes().get(self.pos) { - match c { - b'-' => self.short_or_long(&mut arg), - b'.' => self.multiple(&mut arg), - b'\'' => self.help(&mut arg), - _ => self.name(&mut arg), - } - } else { - break; - } - } - debug_assert!( - !arg.b.name.is_empty(), - format!( - "No name found for Arg when parsing usage string: {}", - self.usage - ) - ); - arg.v.num_vals = match arg.v.val_names { - Some(ref v) if v.len() >= 2 => Some(v.len() as u64), - _ => None, - }; - debugln!("UsageParser::parse: vals...{:?}", arg.v.val_names); - arg - } - - fn name(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::name;"); - if *self.usage - .as_bytes() - .get(self.pos) - .expect(INTERNAL_ERROR_MSG) == b'<' && !self.explicit_name_set - { - arg.setb(ArgSettings::Required); - } - self.pos += 1; - self.stop_at(name_end); - let name = &self.usage[self.start..self.pos]; - if self.prev == UsageToken::Unknown { - debugln!("UsageParser::name: setting name...{}", name); - arg.b.name = name; - if arg.s.long.is_none() && arg.s.short.is_none() { - debugln!("UsageParser::name: explicit name set..."); - self.explicit_name_set = true; - self.prev = UsageToken::Name; - } - } else { - debugln!("UsageParser::name: setting val name...{}", name); - if let Some(ref mut v) = arg.v.val_names { - let len = v.len(); - v.insert(len, name); - } else { - let mut v = VecMap::new(); - v.insert(0, name); - arg.v.val_names = Some(v); - arg.setb(ArgSettings::TakesValue); - } - self.prev = UsageToken::ValName; - } - } - - fn stop_at<F>(&mut self, f: F) - where - F: Fn(u8) -> bool, - { - debugln!("UsageParser::stop_at;"); - self.start = self.pos; - self.pos += self.usage[self.start..] - .bytes() - .take_while(|&b| f(b)) - .count(); - } - - fn short_or_long(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::short_or_long;"); - self.pos += 1; - if *self.usage - .as_bytes() - .get(self.pos) - .expect(INTERNAL_ERROR_MSG) == b'-' - { - self.pos += 1; - self.long(arg); - return; - } - self.short(arg) - } - - fn long(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::long;"); - self.stop_at(long_end); - let name = &self.usage[self.start..self.pos]; - if !self.explicit_name_set { - debugln!("UsageParser::long: setting name...{}", name); - arg.b.name = name; - } - debugln!("UsageParser::long: setting long...{}", name); - arg.s.long = Some(name); - self.prev = UsageToken::Long; - } - - fn short(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::short;"); - let start = &self.usage[self.pos..]; - let short = start.chars().nth(0).expect(INTERNAL_ERROR_MSG); - debugln!("UsageParser::short: setting short...{}", short); - arg.s.short = Some(short); - if arg.b.name.is_empty() { - // --long takes precedence but doesn't set self.explicit_name_set - let name = &start[..short.len_utf8()]; - debugln!("UsageParser::short: setting name...{}", name); - arg.b.name = name; - } - self.prev = UsageToken::Short; - } - - // "something..." - fn multiple(&mut self, arg: &mut Arg) { - debugln!("UsageParser::multiple;"); - let mut dot_counter = 1; - let start = self.pos; - let mut bytes = self.usage[start..].bytes(); - while bytes.next() == Some(b'.') { - dot_counter += 1; - self.pos += 1; - if dot_counter == 3 { - debugln!("UsageParser::multiple: setting multiple"); - arg.setb(ArgSettings::Multiple); - if arg.is_set(ArgSettings::TakesValue) { - arg.setb(ArgSettings::UseValueDelimiter); - arg.unsetb(ArgSettings::ValueDelimiterNotSet); - if arg.v.val_delim.is_none() { - arg.v.val_delim = Some(','); - } - } - self.prev = UsageToken::Multiple; - self.pos += 1; - break; - } - } - } - - fn help(&mut self, arg: &mut Arg<'a, 'a>) { - debugln!("UsageParser::help;"); - self.stop_at(help_start); - self.start = self.pos + 1; - self.pos = self.usage.len() - 1; - debugln!( - "UsageParser::help: setting help...{}", - &self.usage[self.start..self.pos] - ); - arg.b.help = Some(&self.usage[self.start..self.pos]); - self.pos += 1; // Move to next byte to keep from thinking ending ' is a start - self.prev = UsageToken::Help; - } -} - -#[inline] -fn name_end(b: u8) -> bool { b != b']' && b != b'>' } - -#[inline] -fn token(b: u8) -> bool { b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'-' } - -#[inline] -fn long_end(b: u8) -> bool { - b != b'\'' && b != b'.' && b != b'<' && b != b'[' && b != b'=' && b != b' ' -} - -#[inline] -fn help_start(b: u8) -> bool { b != b'\'' } - -#[cfg(test)] -mod test { - use args::Arg; - use args::ArgSettings; - - #[test] - fn create_flag_usage() { - let a = Arg::from_usage("[flag] -f 'some help info'"); - assert_eq!(a.b.name, "flag"); - assert_eq!(a.s.short.unwrap(), 'f'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - - let b = Arg::from_usage("[flag] --flag 'some help info'"); - assert_eq!(b.b.name, "flag"); - assert_eq!(b.s.long.unwrap(), "flag"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - - let b = Arg::from_usage("--flag 'some help info'"); - assert_eq!(b.b.name, "flag"); - assert_eq!(b.s.long.unwrap(), "flag"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.v.val_names.is_none()); - assert!(b.v.num_vals.is_none()); - - let c = Arg::from_usage("[flag] -f --flag 'some help info'"); - assert_eq!(c.b.name, "flag"); - assert_eq!(c.s.short.unwrap(), 'f'); - assert_eq!(c.s.long.unwrap(), "flag"); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - - let d = Arg::from_usage("[flag] -f... 'some help info'"); - assert_eq!(d.b.name, "flag"); - assert_eq!(d.s.short.unwrap(), 'f'); - assert!(d.s.long.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.v.val_names.is_none()); - assert!(d.v.num_vals.is_none()); - - let e = Arg::from_usage("[flag] -f --flag... 'some help info'"); - assert_eq!(e.b.name, "flag"); - assert_eq!(e.s.long.unwrap(), "flag"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert_eq!(e.b.help.unwrap(), "some help info"); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("-f --flag... 'some help info'"); - assert_eq!(e.b.name, "flag"); - assert_eq!(e.s.long.unwrap(), "flag"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert_eq!(e.b.help.unwrap(), "some help info"); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("--flags"); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.long.unwrap(), "flags"); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("--flags..."); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.long.unwrap(), "flags"); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("[flags] -f"); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("[flags] -f..."); - assert_eq!(e.b.name, "flags"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let a = Arg::from_usage("-f 'some help info'"); - assert_eq!(a.b.name, "f"); - assert_eq!(a.s.short.unwrap(), 'f'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - - let e = Arg::from_usage("-f"); - assert_eq!(e.b.name, "f"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - - let e = Arg::from_usage("-f..."); - assert_eq!(e.b.name, "f"); - assert_eq!(e.s.short.unwrap(), 'f'); - assert!(e.is_set(ArgSettings::Multiple)); - assert!(e.v.val_names.is_none()); - assert!(e.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage0() { - // Short only - let a = Arg::from_usage("[option] -o [opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage1() { - let b = Arg::from_usage("-o [opt] 'some help info'"); - assert_eq!(b.b.name, "o"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert!(b.s.long.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage2() { - let c = Arg::from_usage("<option> -o <opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert!(c.s.long.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage3() { - let d = Arg::from_usage("-o <opt> 'some help info'"); - assert_eq!(d.b.name, "o"); - assert_eq!(d.s.short.unwrap(), 'o'); - assert!(d.s.long.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage4() { - let a = Arg::from_usage("[option] -o [opt]... 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage5() { - let a = Arg::from_usage("[option]... -o [opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert!(a.s.long.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage6() { - let b = Arg::from_usage("-o [opt]... 'some help info'"); - assert_eq!(b.b.name, "o"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert!(b.s.long.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage7() { - let c = Arg::from_usage("<option> -o <opt>... 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert!(c.s.long.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage8() { - let c = Arg::from_usage("<option>... -o <opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert!(c.s.long.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage9() { - let d = Arg::from_usage("-o <opt>... 'some help info'"); - assert_eq!(d.b.name, "o"); - assert_eq!(d.s.short.unwrap(), 'o'); - assert!(d.s.long.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long1() { - let a = Arg::from_usage("[option] --opt [opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert!(a.s.short.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long2() { - let b = Arg::from_usage("--opt [option] 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long3() { - let c = Arg::from_usage("<option> --opt <opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert!(c.s.short.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long4() { - let d = Arg::from_usage("--opt <option> 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert!(d.s.short.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long5() { - let a = Arg::from_usage("[option] --opt [opt]... 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert!(a.s.short.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long6() { - let a = Arg::from_usage("[option]... --opt [opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert!(a.s.short.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long7() { - let b = Arg::from_usage("--opt [option]... 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long8() { - let c = Arg::from_usage("<option> --opt <opt>... 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert!(c.s.short.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long9() { - let c = Arg::from_usage("<option>... --opt <opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert!(c.s.short.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long10() { - let d = Arg::from_usage("--opt <option>... 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert!(d.s.short.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals1() { - let a = Arg::from_usage("[option] --opt=[opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert!(a.s.short.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals2() { - let b = Arg::from_usage("--opt=[option] 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals3() { - let c = Arg::from_usage("<option> --opt=<opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert!(c.s.short.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals4() { - let d = Arg::from_usage("--opt=<option> 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert!(d.s.short.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals5() { - let a = Arg::from_usage("[option] --opt=[opt]... 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert!(a.s.short.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals6() { - let a = Arg::from_usage("[option]... --opt=[opt] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert!(a.s.short.is_none()); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals7() { - let b = Arg::from_usage("--opt=[option]... 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert!(b.s.short.is_none()); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals8() { - let c = Arg::from_usage("<option> --opt=<opt>... 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert!(c.s.short.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals9() { - let c = Arg::from_usage("<option>... --opt=<opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert!(c.s.short.is_none()); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_long_equals10() { - let d = Arg::from_usage("--opt=<option>... 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert!(d.s.short.is_none()); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both1() { - let a = Arg::from_usage("[option] -o --opt [option] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both2() { - let b = Arg::from_usage("-o --opt [option] 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both3() { - let c = Arg::from_usage("<option> -o --opt <opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both4() { - let d = Arg::from_usage("-o --opt <option> 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.s.short.unwrap(), 'o'); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both5() { - let a = Arg::from_usage("[option]... -o --opt [option] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both6() { - let b = Arg::from_usage("-o --opt [option]... 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both7() { - let c = Arg::from_usage("<option>... -o --opt <opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both8() { - let d = Arg::from_usage("-o --opt <option>... 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.s.short.unwrap(), 'o'); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals1() { - let a = Arg::from_usage("[option] -o --opt=[option] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals2() { - let b = Arg::from_usage("-o --opt=[option] 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals3() { - let c = Arg::from_usage("<option> -o --opt=<opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(!c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals4() { - let d = Arg::from_usage("-o --opt=<option> 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.s.short.unwrap(), 'o'); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals5() { - let a = Arg::from_usage("[option]... -o --opt=[option] 'some help info'"); - assert_eq!(a.b.name, "option"); - assert_eq!(a.s.long.unwrap(), "opt"); - assert_eq!(a.s.short.unwrap(), 'o'); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(a.is_set(ArgSettings::Multiple)); - assert!(a.is_set(ArgSettings::TakesValue)); - assert!(!a.is_set(ArgSettings::Required)); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals6() { - let b = Arg::from_usage("-o --opt=[option]... 'some help info'"); - assert_eq!(b.b.name, "opt"); - assert_eq!(b.s.long.unwrap(), "opt"); - assert_eq!(b.s.short.unwrap(), 'o'); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::TakesValue)); - assert!(!b.is_set(ArgSettings::Required)); - assert_eq!( - b.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals7() { - let c = Arg::from_usage("<option>... -o --opt=<opt> 'some help info'"); - assert_eq!(c.b.name, "option"); - assert_eq!(c.s.long.unwrap(), "opt"); - assert_eq!(c.s.short.unwrap(), 'o'); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(c.is_set(ArgSettings::TakesValue)); - assert!(c.is_set(ArgSettings::Required)); - assert_eq!( - c.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"opt"] - ); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn create_option_usage_both_equals8() { - let d = Arg::from_usage("-o --opt=<option>... 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.s.short.unwrap(), 'o'); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"option"] - ); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn create_option_with_vals1() { - let d = Arg::from_usage("-o <file> <mode> 'some help info'"); - assert_eq!(d.b.name, "o"); - assert!(d.s.long.is_none()); - assert_eq!(d.s.short.unwrap(), 'o'); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"file", &"mode"] - ); - assert_eq!(d.v.num_vals.unwrap(), 2); - } - - #[test] - fn create_option_with_vals2() { - let d = Arg::from_usage("-o <file> <mode>... 'some help info'"); - assert_eq!(d.b.name, "o"); - assert!(d.s.long.is_none()); - assert_eq!(d.s.short.unwrap(), 'o'); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"file", &"mode"] - ); - assert_eq!(d.v.num_vals.unwrap(), 2); - } - - #[test] - fn create_option_with_vals3() { - let d = Arg::from_usage("--opt <file> <mode>... 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert!(d.s.short.is_none()); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"file", &"mode"] - ); - assert_eq!(d.v.num_vals.unwrap(), 2); - } - - #[test] - fn create_option_with_vals4() { - let d = Arg::from_usage("[myopt] --opt <file> <mode> 'some help info'"); - assert_eq!(d.b.name, "myopt"); - assert!(d.s.short.is_none()); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(!d.is_set(ArgSettings::Required)); - assert_eq!( - d.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"file", &"mode"] - ); - assert_eq!(d.v.num_vals.unwrap(), 2); - } - - #[test] - fn create_option_with_vals5() { - let d = Arg::from_usage("--opt <file> <mode> 'some help info'"); - assert_eq!(d.b.name, "opt"); - assert!(d.s.short.is_none()); - assert_eq!(d.s.long.unwrap(), "opt"); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(!d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::TakesValue)); - assert!(d.is_set(ArgSettings::Required)); - assert_eq!(d.v.num_vals.unwrap(), 2); - } - - #[test] - fn create_positional_usage() { - let a = Arg::from_usage("[pos] 'some help info'"); - assert_eq!(a.b.name, "pos"); - assert_eq!(a.b.help.unwrap(), "some help info"); - assert!(!a.is_set(ArgSettings::Multiple)); - assert!(!a.is_set(ArgSettings::Required)); - assert!(a.v.val_names.is_none()); - assert!(a.v.num_vals.is_none()); - } - - #[test] - fn create_positional_usage0() { - let b = Arg::from_usage("<pos> 'some help info'"); - assert_eq!(b.b.name, "pos"); - assert_eq!(b.b.help.unwrap(), "some help info"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::Required)); - assert!(b.v.val_names.is_none()); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn pos_mult_help() { - let c = Arg::from_usage("[pos]... 'some help info'"); - assert_eq!(c.b.name, "pos"); - assert_eq!(c.b.help.unwrap(), "some help info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(!c.is_set(ArgSettings::Required)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn pos_help_lit_single_quote() { - let c = Arg::from_usage("[pos]... 'some help\' info'"); - assert_eq!(c.b.name, "pos"); - assert_eq!(c.b.help.unwrap(), "some help' info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(!c.is_set(ArgSettings::Required)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn pos_help_double_lit_single_quote() { - let c = Arg::from_usage("[pos]... 'some \'help\' info'"); - assert_eq!(c.b.name, "pos"); - assert_eq!(c.b.help.unwrap(), "some 'help' info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(!c.is_set(ArgSettings::Required)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn pos_help_newline() { - let c = Arg::from_usage( - "[pos]... 'some help{n}\ - info'", - ); - assert_eq!(c.b.name, "pos"); - assert_eq!(c.b.help.unwrap(), "some help{n}info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(!c.is_set(ArgSettings::Required)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn pos_help_newline_lit_sq() { - let c = Arg::from_usage( - "[pos]... 'some help\' stuff{n}\ - info'", - ); - assert_eq!(c.b.name, "pos"); - assert_eq!(c.b.help.unwrap(), "some help' stuff{n}info"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(!c.is_set(ArgSettings::Required)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn pos_req_mult_help() { - let d = Arg::from_usage("<pos>... 'some help info'"); - assert_eq!(d.b.name, "pos"); - assert_eq!(d.b.help.unwrap(), "some help info"); - assert!(d.is_set(ArgSettings::Multiple)); - assert!(d.is_set(ArgSettings::Required)); - assert!(d.v.val_names.is_none()); - assert!(d.v.num_vals.is_none()); - } - - #[test] - fn pos_req() { - let b = Arg::from_usage("<pos>"); - assert_eq!(b.b.name, "pos"); - assert!(!b.is_set(ArgSettings::Multiple)); - assert!(b.is_set(ArgSettings::Required)); - assert!(b.v.val_names.is_none()); - assert!(b.v.num_vals.is_none()); - } - - #[test] - fn pos_mult() { - let c = Arg::from_usage("[pos]..."); - assert_eq!(c.b.name, "pos"); - assert!(c.is_set(ArgSettings::Multiple)); - assert!(!c.is_set(ArgSettings::Required)); - assert!(c.v.val_names.is_none()); - assert!(c.v.num_vals.is_none()); - } - - #[test] - fn nonascii() { - let a = Arg::from_usage("<ASCII> 'üñíčöĐ€'"); - assert_eq!(a.b.name, "ASCII"); - assert_eq!(a.b.help, Some("üñíčöĐ€")); - let a = Arg::from_usage("<üñíčöĐ€> 'ASCII'"); - assert_eq!(a.b.name, "üñíčöĐ€"); - assert_eq!(a.b.help, Some("ASCII")); - let a = Arg::from_usage("<üñíčöĐ€> 'üñíčöĐ€'"); - assert_eq!(a.b.name, "üñíčöĐ€"); - assert_eq!(a.b.help, Some("üñíčöĐ€")); - let a = Arg::from_usage("-ø 'ø'"); - assert_eq!(a.b.name, "ø"); - assert_eq!(a.s.short, Some('ø')); - assert_eq!(a.b.help, Some("ø")); - let a = Arg::from_usage("--üñíčöĐ€ 'Nōṫ ASCII'"); - assert_eq!(a.b.name, "üñíčöĐ€"); - assert_eq!(a.s.long, Some("üñíčöĐ€")); - assert_eq!(a.b.help, Some("Nōṫ ASCII")); - let a = Arg::from_usage("[ñämê] --ôpt=[üñíčöĐ€] 'hælp'"); - assert_eq!(a.b.name, "ñämê"); - assert_eq!(a.s.long, Some("ôpt")); - assert_eq!( - a.v.val_names.unwrap().values().collect::<Vec<_>>(), - [&"üñíčöĐ€"] - ); - assert_eq!(a.b.help, Some("hælp")); - } -} |