]> git.proxmox.com Git - rustc.git/blob - src/vendor/clap/src/app/settings.rs
New upstream version 1.17.0+dfsg1
[rustc.git] / src / vendor / clap / src / app / settings.rs
1 // Std
2 use std::ascii::AsciiExt;
3 use std::str::FromStr;
4 use std::ops::BitOr;
5
6 bitflags! {
7 flags Flags: u64 {
8 const SC_NEGATE_REQS = 0b0000000000000000000000000000000001,
9 const SC_REQUIRED = 0b0000000000000000000000000000000010,
10 const A_REQUIRED_ELSE_HELP = 0b0000000000000000000000000000000100,
11 const GLOBAL_VERSION = 0b0000000000000000000000000000001000,
12 const VERSIONLESS_SC = 0b0000000000000000000000000000010000,
13 const UNIFIED_HELP = 0b0000000000000000000000000000100000,
14 const WAIT_ON_ERROR = 0b0000000000000000000000000001000000,
15 const SC_REQUIRED_ELSE_HELP= 0b0000000000000000000000000010000000,
16 const NEEDS_LONG_HELP = 0b0000000000000000000000000100000000,
17 const NEEDS_LONG_VERSION = 0b0000000000000000000000001000000000,
18 const NEEDS_SC_HELP = 0b0000000000000000000000010000000000,
19 const DISABLE_VERSION = 0b0000000000000000000000100000000000,
20 const HIDDEN = 0b0000000000000000000001000000000000,
21 const TRAILING_VARARG = 0b0000000000000000000010000000000000,
22 const NO_BIN_NAME = 0b0000000000000000000100000000000000,
23 const ALLOW_UNK_SC = 0b0000000000000000001000000000000000,
24 const UTF8_STRICT = 0b0000000000000000010000000000000000,
25 const UTF8_NONE = 0b0000000000000000100000000000000000,
26 const LEADING_HYPHEN = 0b0000000000000001000000000000000000,
27 const NO_POS_VALUES = 0b0000000000000010000000000000000000,
28 const NEXT_LINE_HELP = 0b0000000000000100000000000000000000,
29 const DERIVE_DISP_ORDER = 0b0000000000001000000000000000000000,
30 const COLORED_HELP = 0b0000000000010000000000000000000000,
31 const COLOR_ALWAYS = 0b0000000000100000000000000000000000,
32 const COLOR_AUTO = 0b0000000001000000000000000000000000,
33 const COLOR_NEVER = 0b0000000010000000000000000000000000,
34 const DONT_DELIM_TRAIL = 0b0000000100000000000000000000000000,
35 const ALLOW_NEG_NUMS = 0b0000001000000000000000000000000000,
36 const LOW_INDEX_MUL_POS = 0b0000010000000000000000000000000000,
37 const DISABLE_HELP_SC = 0b0000100000000000000000000000000000,
38 const DONT_COLLAPSE_ARGS = 0b0001000000000000000000000000000000,
39 const ARGS_NEGATE_SCS = 0b0010000000000000000000000000000000,
40 const PROPAGATE_VALS_DOWN = 0b0100000000000000000000000000000000,
41 const ALLOW_MISSING_POS = 0b1000000000000000000000000000000000,
42 }
43 }
44
45 #[doc(hidden)]
46 #[derive(Debug, Copy, Clone, PartialEq)]
47 pub struct AppFlags(Flags);
48
49 impl BitOr for AppFlags {
50 type Output = Self;
51 fn bitor(self, rhs: Self) -> Self {
52 AppFlags(self.0 | rhs.0)
53 }
54 }
55
56 impl Default for AppFlags {
57 fn default() -> Self {
58 AppFlags(NEEDS_LONG_VERSION | NEEDS_LONG_HELP | NEEDS_SC_HELP | UTF8_NONE | COLOR_AUTO)
59 }
60 }
61
62 impl AppFlags {
63 pub fn new() -> Self { AppFlags::default() }
64
65 impl_settings! { AppSettings,
66 ArgRequiredElseHelp => A_REQUIRED_ELSE_HELP,
67 ArgsNegateSubcommands => ARGS_NEGATE_SCS,
68 AllowExternalSubcommands => ALLOW_UNK_SC,
69 AllowInvalidUtf8 => UTF8_NONE,
70 AllowLeadingHyphen => LEADING_HYPHEN,
71 AllowNegativeNumbers => ALLOW_NEG_NUMS,
72 AllowMissingPositional => ALLOW_MISSING_POS,
73 ColoredHelp => COLORED_HELP,
74 ColorAlways => COLOR_ALWAYS,
75 ColorAuto => COLOR_AUTO,
76 ColorNever => COLOR_NEVER,
77 DontDelimitTrailingValues => DONT_DELIM_TRAIL,
78 DontCollapseArgsInUsage => DONT_COLLAPSE_ARGS,
79 DeriveDisplayOrder => DERIVE_DISP_ORDER,
80 DisableHelpSubcommand => DISABLE_HELP_SC,
81 DisableVersion => DISABLE_VERSION,
82 GlobalVersion => GLOBAL_VERSION,
83 HidePossibleValuesInHelp => NO_POS_VALUES,
84 Hidden => HIDDEN,
85 LowIndexMultiplePositional => LOW_INDEX_MUL_POS,
86 NeedsLongHelp => NEEDS_LONG_HELP,
87 NeedsLongVersion => NEEDS_LONG_VERSION,
88 NeedsSubcommandHelp => NEEDS_SC_HELP,
89 NoBinaryName => NO_BIN_NAME,
90 PropagateGlobalValuesDown=> PROPAGATE_VALS_DOWN,
91 StrictUtf8 => UTF8_STRICT,
92 SubcommandsNegateReqs => SC_NEGATE_REQS,
93 SubcommandRequired => SC_REQUIRED,
94 SubcommandRequiredElseHelp => SC_REQUIRED_ELSE_HELP,
95 TrailingVarArg => TRAILING_VARARG,
96 UnifiedHelpMessage => UNIFIED_HELP,
97 NextLineHelp => NEXT_LINE_HELP,
98 VersionlessSubcommands => VERSIONLESS_SC,
99 WaitOnError => WAIT_ON_ERROR
100 }
101 }
102
103 /// Application level settings, which affect how [`App`] operates
104 ///
105 /// **NOTE:** When these settings are used, they apply only to current command, and are *not*
106 /// propagated down or up through child or parent subcommands
107 ///
108 /// [`App`]: ./struct.App.html
109 #[derive(Debug, PartialEq, Copy, Clone)]
110 pub enum AppSettings {
111 /// Specifies that any invalid UTF-8 code points should *not* be treated as an error.
112 /// This is the default behavior of `clap`.
113 ///
114 /// **NOTE:** Using argument values with invalid UTF-8 code points requires using
115 /// [`ArgMatches::os_value_of`], [`ArgMatches::os_values_of`], [`ArgMatches::lossy_value_of`],
116 /// or [`ArgMatches::lossy_values_of`] for those particular arguments which may contain invalid
117 /// UTF-8 values
118 ///
119 /// **NOTE:** This rule only applies to argument values, as flags, options, and
120 /// [`SubCommand`]s themselves only allow valid UTF-8 code points.
121 ///
122 /// # Platform Specific
123 ///
124 /// Non Windows systems only
125 ///
126 /// # Examples
127 ///
128 #[cfg_attr(not(unix), doc=" ```ignore")]
129 #[cfg_attr( unix , doc=" ```")]
130 /// # use clap::{App, AppSettings};
131 /// use std::ffi::OsString;
132 /// use std::os::unix::ffi::{OsStrExt,OsStringExt};
133 ///
134 /// let r = App::new("myprog")
135 /// //.setting(AppSettings::AllowInvalidUtf8)
136 /// .arg_from_usage("<arg> 'some positional arg'")
137 /// .get_matches_from_safe(
138 /// vec![
139 /// OsString::from("myprog"),
140 /// OsString::from_vec(vec![0xe9])]);
141 ///
142 /// assert!(r.is_ok());
143 /// let m = r.unwrap();
144 /// assert_eq!(m.value_of_os("arg").unwrap().as_bytes(), &[0xe9]);
145 /// ```
146 /// [`ArgMatches::os_value_of`]: ./struct.ArgMatches.html#method.os_value_of
147 /// [`ArgMatches::os_values_of`]: ./struct.ArgMatches.html#method.os_values_of
148 /// [`ArgMatches::lossy_value_of`]: ./struct.ArgMatches.html#method.lossy_value_of
149 /// [`ArgMatches::lossy_values_of`]: ./struct.ArgMatches.html#method.lossy_values_of
150 AllowInvalidUtf8,
151
152 /// Specifies that leading hyphens are allowed in argument *values*, such as negative numbers
153 /// like `-10`. (which would otherwise be parsed as another flag or option)
154 ///
155 /// **NOTE:** This can only be set application wide and not on a per argument basis.
156 ///
157 /// **NOTE:** Use this setting with caution as it silences certain circumstances which would
158 /// otherwise be an error (such as accidentally forgetting to specify a value for leading
159 /// option)
160 ///
161 /// # Examples
162 ///
163 /// ```rust
164 /// # use clap::{Arg, App, AppSettings};
165 /// // Imagine you needed to represent negative numbers as well, such as -10
166 /// let m = App::new("nums")
167 /// .setting(AppSettings::AllowLeadingHyphen)
168 /// .arg(Arg::with_name("neg").index(1))
169 /// .get_matches_from(vec![
170 /// "nums", "-20"
171 /// ]);
172 ///
173 /// assert_eq!(m.value_of("neg"), Some("-20"));
174 /// # ;
175 /// ```
176 AllowLeadingHyphen,
177
178 /// Allows negative numbers to pass as values. This is similar to
179 /// `AllowLeadingHyphen` except that it only allows numbers, all
180 /// other undefined leading hyphens will fail to parse.
181 ///
182 /// # Examples
183 ///
184 /// ```rust
185 /// # use clap::{App, Arg, AppSettings};
186 /// let res = App::new("myprog")
187 /// .version("v1.1")
188 /// .setting(AppSettings::AllowNegativeNumbers)
189 /// .arg(Arg::with_name("num"))
190 /// .get_matches_from_safe(vec![
191 /// "myprog", "-20"
192 /// ]);
193 /// assert!(res.is_ok());
194 /// let m = res.unwrap();
195 /// assert_eq!(m.value_of("num").unwrap(), "-20");
196 /// ```
197 /// [`AllowLeadingHyphen`]: ./enum.AppSettings.html#variant.AllowLeadingHyphen
198 AllowNegativeNumbers,
199
200 /// Allows one to implement a CLI where the second to last positional argument is optional, but
201 /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
202 /// of the two following usages is allowed:
203 ///
204 /// * `$ prog [optional] <required>`
205 /// * `$ prog <required>`
206 ///
207 /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
208 ///
209 /// **Note:** In addition to using this setting, the second positional argument *must* be
210 /// [required]
211 ///
212 /// # Examples
213 ///
214 /// ```rust
215 /// # use clap::{App, Arg, AppSettings};
216 /// // Assume there is an external subcommand named "subcmd"
217 /// let m = App::new("myprog")
218 /// .setting(AppSettings::AllowMissingPositional)
219 /// .arg(Arg::with_name("arg1")
220 /// .default_value("something"))
221 /// .arg(Arg::with_name("arg2")
222 /// .required(true))
223 /// .get_matches_from(vec![
224 /// "myprog", "other"
225 /// ]);
226 ///
227 /// assert_eq!(m.value_of("arg1"), Some("something"));
228 /// assert_eq!(m.value_of("arg2"), Some("other"));
229 /// ```
230 /// [required]: ./struct.Arg.html#method.required
231 AllowMissingPositional,
232
233 /// Specifies that an unexpected positional argument,
234 /// which would otherwise cause a [`ErrorKind::UnknownArgument`] error,
235 /// should instead be treated as a [`SubCommand`] within the [`ArgMatches`] struct.
236 ///
237 /// **NOTE:** Use this setting with caution,
238 /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
239 /// will **not** cause an error and instead be treated as a potential subcommand.
240 /// One should check for such cases manually and inform the user appropriately.
241 ///
242 /// # Examples
243 ///
244 /// ```rust
245 /// # use clap::{App, AppSettings};
246 /// // Assume there is an external subcommand named "subcmd"
247 /// let m = App::new("myprog")
248 /// .setting(AppSettings::AllowExternalSubcommands)
249 /// .get_matches_from(vec![
250 /// "myprog", "subcmd", "--option", "value", "-fff", "--flag"
251 /// ]);
252 ///
253 /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
254 /// // string argument name
255 /// match m.subcommand() {
256 /// (external, Some(ext_m)) => {
257 /// let ext_args: Vec<&str> = ext_m.values_of("").unwrap().collect();
258 /// assert_eq!(external, "subcmd");
259 /// assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
260 /// },
261 /// _ => {},
262 /// }
263 /// ```
264 /// [`ErrorKind::UnknownArgument`]: ./enum.ErrorKind.html#variant.UnknownArgument
265 /// [`SubCommand`]: ./struct.SubCommand.html
266 /// [`ArgMatches`]: ./struct.ArgMatches.html
267 AllowExternalSubcommands,
268
269 /// Specifies that use of a valid [argument] negates [subcomands] being used after. By default
270 /// `clap` allows arguments between subcommands such as
271 /// `<cmd> [cmd_args] <cmd2> [cmd2_args] <cmd3> [cmd3_args]`. This setting disables that
272 /// functionality and says that arguments can only follow the *final* subcommand. For instance
273 /// using this setting makes only the following invocations possible:
274 ///
275 /// * `<cmd> <cmd2> <cmd3> [cmd3_args]`
276 /// * `<cmd> <cmd2> [cmd2_args]`
277 /// * `<cmd> [cmd_args]`
278 ///
279 /// # Examples
280 ///
281 /// ```rust
282 /// # use clap::{App, AppSettings};
283 /// App::new("myprog")
284 /// .setting(AppSettings::ArgsNegateSubcommands)
285 /// # ;
286 /// ```
287 /// [subcommands]: ./struct.SubCommand.html
288 /// [argument]: ./struct.Arg.html
289 ArgsNegateSubcommands,
290
291 /// Specifies that the help text should be displayed (and then exit gracefully),
292 /// if no arguments are present at runtime (i.e. an empty run such as, `$ myprog`.
293 ///
294 /// **NOTE:** [`SubCommand`]s count as arguments
295 ///
296 /// **NOTE:** Setting [`Arg::default_value`] effectively disables this option as it will
297 /// ensure that some argument is always present.
298 ///
299 /// # Examples
300 ///
301 /// ```rust
302 /// # use clap::{App, AppSettings};
303 /// App::new("myprog")
304 /// .setting(AppSettings::ArgRequiredElseHelp)
305 /// # ;
306 /// ```
307 /// [`SubCommand`]: ./struct.SubCommand.html
308 /// [`Arg::default_value`]: ./struct.Arg.html#method.default_value
309 ArgRequiredElseHelp,
310
311 /// Uses colorized help messages.
312 ///
313 /// **NOTE:** Must be compiled with the `color` cargo feature
314 ///
315 /// # Platform Specific
316 ///
317 /// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms)
318 ///
319 /// # Examples
320 ///
321 /// ```no_run
322 /// # use clap::{App, Arg, SubCommand, AppSettings};
323 /// App::new("myprog")
324 /// .setting(AppSettings::ColoredHelp)
325 /// .get_matches();
326 /// ```
327 ColoredHelp,
328
329 /// Enables colored output only when the output is going to a terminal or TTY.
330 ///
331 /// **NOTE:** This is the default behavior of `clap`.
332 ///
333 /// **NOTE:** Must be compiled with the `color` cargo feature.
334 ///
335 /// # Platform Specific
336 ///
337 /// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms).
338 ///
339 /// # Examples
340 ///
341 /// ```no_run
342 /// # use clap::{App, Arg, SubCommand, AppSettings};
343 /// App::new("myprog")
344 /// .setting(AppSettings::ColorAuto)
345 /// .get_matches();
346 /// ```
347 ColorAuto,
348
349 /// Enables colored output regardless of whether or not the output is going to a terminal/TTY.
350 ///
351 /// **NOTE:** Must be compiled with the `color` cargo feature.
352 ///
353 /// # Platform Specific
354 ///
355 /// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms).
356 ///
357 /// # Examples
358 ///
359 /// ```no_run
360 /// # use clap::{App, Arg, SubCommand, AppSettings};
361 /// App::new("myprog")
362 /// .setting(AppSettings::ColorAlways)
363 /// .get_matches();
364 /// ```
365 ColorAlways,
366
367 /// Disables colored output no matter if the output is going to a terminal/TTY, or not.
368 ///
369 /// **NOTE:** Must be compiled with the `color` cargo feature
370 ///
371 /// # Platform Specific
372 ///
373 /// This setting only applies to Unix, Linux, and OSX (i.e. non-Windows platforms)
374 ///
375 /// # Examples
376 ///
377 /// ```no_run
378 /// # use clap::{App, Arg, SubCommand, AppSettings};
379 /// App::new("myprog")
380 /// .setting(AppSettings::ColorNever)
381 /// .get_matches();
382 /// ```
383 ColorNever,
384
385 /// Disables the automatic collapsing of positional args into `[ARGS]` inside the usage string
386 ///
387 /// # Examples
388 ///
389 /// ```no_run
390 /// # use clap::{App, Arg, SubCommand, AppSettings};
391 /// App::new("myprog")
392 /// .setting(AppSettings::DontCollapseArgsInUsage)
393 /// .get_matches();
394 /// ```
395 DontCollapseArgsInUsage,
396
397 /// Disables the automatic delimiting of values when `--` or [`AppSettings::TrailingVarArg`]
398 /// was used.
399 ///
400 /// **NOTE:** The same thing can be done manually by setting the final positional argument to
401 /// [`Arg::use_delimiter(false)`]. Using this setting is safer, because it's easier to locate
402 /// when making changes.
403 ///
404 /// # Examples
405 ///
406 /// ```no_run
407 /// # use clap::{App, Arg, SubCommand, AppSettings};
408 /// App::new("myprog")
409 /// .setting(AppSettings::DontDelimitTrailingValues)
410 /// .get_matches();
411 /// ```
412 /// [`AppSettings::TrailingVarArg`]: ./enum.AppSettings.html#variant.TrailingVarArg
413 /// [`Arg::use_delimiter(false)`]: ./struct.Arg.html#method.use_delimiter
414 DontDelimitTrailingValues,
415
416 /// Disables the `help` subcommand
417 ///
418 /// # Examples
419 ///
420 /// ```rust
421 /// # use clap::{App, AppSettings, ErrorKind, SubCommand};
422 /// let res = App::new("myprog")
423 /// .version("v1.1")
424 /// .setting(AppSettings::DisableHelpSubcommand)
425 /// // Normally, creating a subcommand causes a `help` subcommand to automaticaly
426 /// // be generated as well
427 /// .subcommand(SubCommand::with_name("test"))
428 /// .get_matches_from_safe(vec![
429 /// "myprog", "help"
430 /// ]);
431 /// assert!(res.is_err());
432 /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
433 /// ```
434 /// [`SubCommand`]: ./struct.SubCommand.html
435 DisableHelpSubcommand,
436
437 /// Disables `-V` and `--version` [`App`] without affecting any of the [`SubCommand`]s
438 /// (Defaults to `false`; application *does* have a version flag)
439 ///
440 /// # Examples
441 ///
442 /// ```rust
443 /// # use clap::{App, AppSettings, ErrorKind};
444 /// let res = App::new("myprog")
445 /// .version("v1.1")
446 /// .setting(AppSettings::DisableVersion)
447 /// .get_matches_from_safe(vec![
448 /// "myprog", "-V"
449 /// ]);
450 /// assert!(res.is_err());
451 /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
452 /// ```
453 ///
454 /// ```rust
455 /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
456 /// let res = App::new("myprog")
457 /// .version("v1.1")
458 /// .setting(AppSettings::DisableVersion)
459 /// .subcommand(SubCommand::with_name("test"))
460 /// .get_matches_from_safe(vec![
461 /// "myprog", "test", "-V"
462 /// ]);
463 /// assert!(res.is_err());
464 /// assert_eq!(res.unwrap_err().kind, ErrorKind::VersionDisplayed);
465 /// ```
466 /// [`SubCommand`]: ./struct.SubCommand.html
467 DisableVersion,
468
469 /// Displays the arguments and [`SubCommand`]s in the help message in the order that they were
470 /// declared in, and not alphabetically which is the default.
471 ///
472 /// # Examples
473 ///
474 /// ```no_run
475 /// # use clap::{App, Arg, SubCommand, AppSettings};
476 /// App::new("myprog")
477 /// .setting(AppSettings::DeriveDisplayOrder)
478 /// .get_matches();
479 /// ```
480 /// [`SubCommand`]: ./struct.SubCommand.html
481 DeriveDisplayOrder,
482
483 /// Specifies to use the version of the current command for all child [`SubCommand`]s.
484 /// (Defaults to `false`; subcommands have independant version strings from their parents.)
485 ///
486 /// **NOTE:** The version for the current command **and** this setting must be set **prior** to
487 /// adding any child subcommands
488 ///
489 /// # Examples
490 ///
491 /// ```no_run
492 /// # use clap::{App, Arg, SubCommand, AppSettings};
493 /// App::new("myprog")
494 /// .version("v1.1")
495 /// .setting(AppSettings::GlobalVersion)
496 /// .subcommand(SubCommand::with_name("test"))
497 /// .get_matches();
498 /// // running `$ myprog test --version` will display
499 /// // "myprog-test v1.1"
500 /// ```
501 /// [`SubCommand`]: ./struct.SubCommand.html
502 GlobalVersion,
503
504 /// Specifies that this [`SubCommand`] should be hidden from help messages
505 ///
506 /// # Examples
507 ///
508 /// ```rust
509 /// # use clap::{App, Arg, AppSettings, SubCommand};
510 /// App::new("myprog")
511 /// .subcommand(SubCommand::with_name("test")
512 /// .setting(AppSettings::Hidden))
513 /// # ;
514 /// ```
515 /// [`SubCommand`]: ./struct.SubCommand.html
516 Hidden,
517
518 /// Tells `clap` *not* to print possible values when displaying help information.
519 /// This can be useful if there are many values, or they are explained elsewhere.
520 HidePossibleValuesInHelp,
521
522 /// Specifies that the parser should not assume the first argument passed is the binary name.
523 /// This is normally the case when using a "daemon" style mode, or an interactive CLI where one
524 /// one would not normally type the binary or program name for each command.
525 ///
526 /// # Examples
527 ///
528 /// ```rust
529 /// # use clap::{App, Arg, AppSettings};
530 /// let m = App::new("myprog")
531 /// .setting(AppSettings::NoBinaryName)
532 /// .arg(Arg::from_usage("<cmd>... 'commands to run'"))
533 /// .get_matches_from(vec!["command", "set"]);
534 ///
535 /// let cmds: Vec<&str> = m.values_of("cmd").unwrap().collect();
536 /// assert_eq!(cmds, ["command", "set"]);
537 /// ```
538 NoBinaryName,
539
540 /// Places the help string for all arguments on the line after the argument.
541 ///
542 /// # Examples
543 ///
544 /// ```no_run
545 /// # use clap::{App, Arg, SubCommand, AppSettings};
546 /// App::new("myprog")
547 /// .setting(AppSettings::NextLineHelp)
548 /// .get_matches();
549 /// ```
550 NextLineHelp,
551
552 /// Specifies that the parser should propagate global arg's values down through any *used* child
553 /// subcommands. Meaning, if a subcommand wasn't used, the values won't be propagated down to
554 /// said subcommand.
555 ///
556 /// **NOTE:** Values are only propagated *down* through futher child commands, not up
557 ///
558 /// # Examples
559 ///
560 /// ```rust
561 /// # use clap::{App, Arg, AppSettings, SubCommand};
562 /// let m = App::new("myprog")
563 /// .setting(AppSettings::PropagateGlobalValuesDown)
564 /// .arg(Arg::from_usage("[cmd] 'command to run'")
565 /// .global(true))
566 /// .subcommand(SubCommand::with_name("foo"))
567 /// .get_matches_from(vec!["myprog", "set", "foo"]);
568 ///
569 /// assert_eq!(m.value_of("cmd"), Some("set"));
570 ///
571 /// let sub_m = m.subcommand_matches("foo").unwrap();
572 /// assert_eq!(sub_m.value_of("cmd"), Some("set"));
573 /// ```
574 /// Now doing the same thing, but *not* using any subcommands will result in the value not being
575 /// propagated down.
576 /// ```rust
577 /// # use clap::{App, Arg, AppSettings};
578 /// let m = App::new("myprog")
579 /// .setting(AppSettings::PropagateGlobalValuesDown)
580 /// .global_arg(Arg::from_usage("<cmd> 'command to run'"))
581 /// .subcommand(SubCommand::with_name("foo"))
582 /// .get_matches_from(vec!["myprog", "set"]);
583 ///
584 /// assert_eq!(m.value_of("cmd"), Some("set"));
585 ///
586 /// assert!(m.subcommand_matches("foo").is_none());
587 /// ```
588 PropagateGlobalValuesDown,
589
590 /// Allows [`SubCommand`]s to override all requirements of the parent command.
591 /// For example if you had a subcommand or top level application with a required argument
592 /// that is only required as long as there is no subcommand present,
593 /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
594 /// and yet receive no error so long as the user uses a valid subcommand instead.
595 ///
596 /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
597 ///
598 /// # Examples
599 ///
600 /// This first example shows that it is an error to not use a required argument
601 ///
602 /// ```rust
603 /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind};
604 /// let err = App::new("myprog")
605 /// .setting(AppSettings::SubcommandsNegateReqs)
606 /// .arg(Arg::with_name("opt").required(true))
607 /// .subcommand(SubCommand::with_name("test"))
608 /// .get_matches_from_safe(vec![
609 /// "myprog"
610 /// ]);
611 /// assert!(err.is_err());
612 /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingRequiredArgument);
613 /// # ;
614 /// ```
615 ///
616 /// This next example shows that it is no longer error to not use a required argument if a
617 /// valid subcommand is used.
618 ///
619 /// ```rust
620 /// # use clap::{App, Arg, AppSettings, SubCommand, ErrorKind};
621 /// let noerr = App::new("myprog")
622 /// .setting(AppSettings::SubcommandsNegateReqs)
623 /// .arg(Arg::with_name("opt").required(true))
624 /// .subcommand(SubCommand::with_name("test"))
625 /// .get_matches_from_safe(vec![
626 /// "myprog", "test"
627 /// ]);
628 /// assert!(noerr.is_ok());
629 /// # ;
630 /// ```
631 /// [`Arg::required(true)`]: ./struct.Arg.html#method.required
632 /// [`SubCommand`]: ./struct.SubCommand.html
633 SubcommandsNegateReqs,
634
635 /// Specifies that the help text should be displayed (before exiting gracefully) if no
636 /// [`SubCommand`]s are present at runtime (i.e. an empty run such as `$ myprog`).
637 ///
638 /// **NOTE:** This should *not* be used with [`AppSettings::SubcommandRequired`] as they do
639 /// nearly same thing; this prints the help text, and the other prints an error.
640 ///
641 /// **NOTE:** If the user specifies arguments at runtime, but no subcommand the help text will
642 /// still be displayed and exit. If this is *not* the desired result, consider using
643 /// [`AppSettings::ArgRequiredElseHelp`] instead.
644 ///
645 /// # Examples
646 ///
647 /// ```rust
648 /// # use clap::{App, Arg, AppSettings};
649 /// App::new("myprog")
650 /// .setting(AppSettings::SubcommandRequiredElseHelp)
651 /// # ;
652 /// ```
653 /// [`SubCommand`]: ./struct.SubCommand.html
654 /// [`AppSettings::SubcommandRequired`]: ./enum.AppSettings.html#variant.SubcommandRequired
655 /// [`AppSettings::ArgRequiredElseHelp`]: ./enum.AppSettings.html#variant.ArgRequiredElseHelp
656 SubcommandRequiredElseHelp,
657
658 /// Specifies that any invalid UTF-8 code points should be treated as an error and fail
659 /// with a [`ErrorKind::InvalidUtf8`] error.
660 ///
661 /// **NOTE:** This rule only applies to argument values; Things such as flags, options, and
662 /// [`SubCommand`]s themselves only allow valid UTF-8 code points.
663 ///
664 /// # Platform Specific
665 ///
666 /// Non Windows systems only
667 ///
668 /// # Examples
669 ///
670 #[cfg_attr(not(unix), doc=" ```ignore")]
671 #[cfg_attr( unix , doc=" ```")]
672 /// # use clap::{App, AppSettings, ErrorKind};
673 /// use std::ffi::OsString;
674 /// use std::os::unix::ffi::OsStringExt;
675 ///
676 /// let m = App::new("myprog")
677 /// .setting(AppSettings::StrictUtf8)
678 /// .arg_from_usage("<arg> 'some positional arg'")
679 /// .get_matches_from_safe(
680 /// vec![
681 /// OsString::from("myprog"),
682 /// OsString::from_vec(vec![0xe9])]);
683 ///
684 /// assert!(m.is_err());
685 /// assert_eq!(m.unwrap_err().kind, ErrorKind::InvalidUtf8);
686 /// ```
687 /// [`SubCommand`]: ./struct.SubCommand.html
688 /// [`ErrorKind::InvalidUtf8`]: ./enum.ErrorKind.html#variant.InvalidUtf8
689 StrictUtf8,
690
691 /// Allows specifying that if no [`SubCommand`] is present at runtime,
692 /// error and exit gracefully.
693 ///
694 /// **NOTE:** This defaults to `false` (subcommands do *not* need to be present)
695 ///
696 /// # Examples
697 ///
698 /// ```rust
699 /// # use clap::{App, AppSettings, SubCommand, ErrorKind};
700 /// let err = App::new("myprog")
701 /// .setting(AppSettings::SubcommandRequired)
702 /// .subcommand(SubCommand::with_name("test"))
703 /// .get_matches_from_safe(vec![
704 /// "myprog",
705 /// ]);
706 /// assert!(err.is_err());
707 /// assert_eq!(err.unwrap_err().kind, ErrorKind::MissingSubcommand);
708 /// # ;
709 /// ```
710 /// [`SubCommand`]: ./struct.SubCommand.html
711 SubcommandRequired,
712
713 /// Specifies that the final positional argument is a "VarArg" and that `clap` should not
714 /// attempt to parse any further args.
715 ///
716 /// The values of the trailing positional argument will contain all args from itself on.
717 ///
718 /// **NOTE:** The final positional argument **must** have [`Arg::multiple(true)`] or the usage
719 /// string equivalent.
720 ///
721 /// # Examples
722 ///
723 /// ```rust
724 /// # use clap::{App, Arg, AppSettings};
725 /// let m = App::new("myprog")
726 /// .setting(AppSettings::TrailingVarArg)
727 /// .arg(Arg::from_usage("<cmd>... 'commands to run'"))
728 /// .get_matches_from(vec!["myprog", "arg1", "-r", "val1"]);
729 ///
730 /// let trail: Vec<&str> = m.values_of("cmd").unwrap().collect();
731 /// assert_eq!(trail, ["arg1", "-r", "val1"]);
732 /// ```
733 /// [`Arg::multiple(true)`]: ./struct.Arg.html#method.multiple
734 TrailingVarArg,
735
736 /// Groups flags and options together, presenting a more unified help message
737 /// (a la `getopts` or `docopt` style).
738 ///
739 /// The default is that the auto-generated help message will group flags, and options
740 /// separately.
741 ///
742 /// **NOTE:** This setting is cosmetic only and does not affect any functionality.
743 ///
744 /// # Examples
745 ///
746 /// ```no_run
747 /// # use clap::{App, Arg, SubCommand, AppSettings};
748 /// App::new("myprog")
749 /// .setting(AppSettings::UnifiedHelpMessage)
750 /// .get_matches();
751 /// // running `myprog --help` will display a unified "docopt" or "getopts" style help message
752 /// ```
753 UnifiedHelpMessage,
754
755 /// Disables `-V` and `--version` for all [`SubCommand`]s
756 /// (Defaults to `false`; subcommands *do* have version flags.)
757 ///
758 /// **NOTE:** This setting must be set **prior** adding any subcommands
759 ///
760 /// # Examples
761 ///
762 /// ```rust
763 /// # use clap::{App, SubCommand, AppSettings, ErrorKind};
764 /// let res = App::new("myprog")
765 /// .version("v1.1")
766 /// .setting(AppSettings::VersionlessSubcommands)
767 /// .subcommand(SubCommand::with_name("test"))
768 /// .get_matches_from_safe(vec![
769 /// "myprog", "test", "-V"
770 /// ]);
771 /// assert!(res.is_err());
772 /// assert_eq!(res.unwrap_err().kind, ErrorKind::UnknownArgument);
773 /// ```
774 /// [`SubCommand`]: ./struct.SubCommand.html
775 VersionlessSubcommands,
776
777 /// Will display a message "Press [ENTER]/[RETURN] to continue..." and wait for user before
778 /// exiting
779 ///
780 /// This is most useful when writing an application which is run from a GUI shortcut, or on
781 /// Windows where a user tries to open the binary by double-clicking instead of using the
782 /// command line.
783 ///
784 /// **NOTE:** This setting is **not** recursive with [`SubCommand`]s, meaning if you wish this
785 /// behavior for all subcommands, you must set this on each command (needing this is extremely
786 /// rare)
787 ///
788 /// # Examples
789 ///
790 /// ```rust
791 /// # use clap::{App, Arg, AppSettings};
792 /// App::new("myprog")
793 /// .setting(AppSettings::WaitOnError)
794 /// # ;
795 /// ```
796 /// [`SubCommand`]: ./struct.SubCommand.html
797 WaitOnError,
798
799 #[doc(hidden)]
800 NeedsLongVersion,
801
802 #[doc(hidden)]
803 NeedsLongHelp,
804
805 #[doc(hidden)]
806 NeedsSubcommandHelp,
807
808 #[doc(hidden)]
809 LowIndexMultiplePositional,
810 }
811
812 impl FromStr for AppSettings {
813 type Err = String;
814 fn from_str(s: &str) -> Result<Self, <Self as FromStr>::Err> {
815 match &*s.to_ascii_lowercase() {
816 "argrequiredelsehelp" => Ok(AppSettings::ArgRequiredElseHelp),
817 "argsnegatesubcommands" => Ok(AppSettings::ArgsNegateSubcommands),
818 "allowinvalidutf8" => Ok(AppSettings::AllowInvalidUtf8),
819 "allowleadinghyphen" => Ok(AppSettings::AllowLeadingHyphen),
820 "allowexternalsubcommands" => Ok(AppSettings::AllowExternalSubcommands),
821 "allownegativenumbers" => Ok(AppSettings::AllowNegativeNumbers),
822 "colorauto" => Ok(AppSettings::ColorAuto),
823 "coloralways" => Ok(AppSettings::ColorAlways),
824 "colornever" => Ok(AppSettings::ColorNever),
825 "coloredhelp" => Ok(AppSettings::ColoredHelp),
826 "derivedisplayorder" => Ok(AppSettings::DeriveDisplayOrder),
827 "dontcollapseargsinusage" => Ok(AppSettings::DontCollapseArgsInUsage),
828 "dontdelimittrailingvalues" => Ok(AppSettings::DontDelimitTrailingValues),
829 "disablehelpsubcommand" => Ok(AppSettings::DisableHelpSubcommand),
830 "disableversion" => Ok(AppSettings::DisableVersion),
831 "globalversion" => Ok(AppSettings::GlobalVersion),
832 "hidden" => Ok(AppSettings::Hidden),
833 "hidepossiblevaluesinhelp" => Ok(AppSettings::HidePossibleValuesInHelp),
834 "lowindexmultiplepositional" => Ok(AppSettings::LowIndexMultiplePositional),
835 "nobinaryname" => Ok(AppSettings::NoBinaryName),
836 "nextlinehelp" => Ok(AppSettings::NextLineHelp),
837 "strictutf8" => Ok(AppSettings::StrictUtf8),
838 "subcommandsnegatereqs" => Ok(AppSettings::SubcommandsNegateReqs),
839 "subcommandrequired" => Ok(AppSettings::SubcommandRequired),
840 "subcommandrequiredelsehelp" => Ok(AppSettings::SubcommandRequiredElseHelp),
841 "trailingvararg" => Ok(AppSettings::TrailingVarArg),
842 "unifiedhelpmessage" => Ok(AppSettings::UnifiedHelpMessage),
843 "versionlesssubcommands" => Ok(AppSettings::VersionlessSubcommands),
844 "waitonerror" => Ok(AppSettings::WaitOnError),
845 _ => Err("unknown AppSetting, cannot convert from str".to_owned()),
846 }
847 }
848 }
849
850 #[cfg(test)]
851 mod test {
852 use super::AppSettings;
853
854 #[test]
855 fn app_settings_fromstr() {
856 assert_eq!("argsnegatesubcommands".parse::<AppSettings>().unwrap(),
857 AppSettings::ArgsNegateSubcommands);
858 assert_eq!("argrequiredelsehelp".parse::<AppSettings>().unwrap(),
859 AppSettings::ArgRequiredElseHelp);
860 assert_eq!("allowexternalsubcommands".parse::<AppSettings>().unwrap(),
861 AppSettings::AllowExternalSubcommands);
862 assert_eq!("allowinvalidutf8".parse::<AppSettings>().unwrap(),
863 AppSettings::AllowInvalidUtf8);
864 assert_eq!("allowleadinghyphen".parse::<AppSettings>().unwrap(),
865 AppSettings::AllowLeadingHyphen);
866 assert_eq!("allownegativenumbers".parse::<AppSettings>().unwrap(),
867 AppSettings::AllowNegativeNumbers);
868 assert_eq!("coloredhelp".parse::<AppSettings>().unwrap(),
869 AppSettings::ColoredHelp);
870 assert_eq!("colorauto".parse::<AppSettings>().unwrap(),
871 AppSettings::ColorAuto);
872 assert_eq!("coloralways".parse::<AppSettings>().unwrap(),
873 AppSettings::ColorAlways);
874 assert_eq!("colornever".parse::<AppSettings>().unwrap(),
875 AppSettings::ColorNever);
876 assert_eq!("disablehelpsubcommand".parse::<AppSettings>().unwrap(),
877 AppSettings::DisableHelpSubcommand);
878 assert_eq!("disableversion".parse::<AppSettings>().unwrap(),
879 AppSettings::DisableVersion);
880 assert_eq!("dontcollapseargsinusage".parse::<AppSettings>().unwrap(),
881 AppSettings::DontCollapseArgsInUsage);
882 assert_eq!("dontdelimittrailingvalues".parse::<AppSettings>().unwrap(),
883 AppSettings::DontDelimitTrailingValues);
884 assert_eq!("derivedisplayorder".parse::<AppSettings>().unwrap(),
885 AppSettings::DeriveDisplayOrder);
886 assert_eq!("globalversion".parse::<AppSettings>().unwrap(),
887 AppSettings::GlobalVersion);
888 assert_eq!("hidden".parse::<AppSettings>().unwrap(),
889 AppSettings::Hidden);
890 assert_eq!("hidepossiblevaluesinhelp".parse::<AppSettings>().unwrap(),
891 AppSettings::HidePossibleValuesInHelp);
892 assert_eq!("lowindexmultiplePositional".parse::<AppSettings>().unwrap(),
893 AppSettings::LowIndexMultiplePositional);
894 assert_eq!("nobinaryname".parse::<AppSettings>().unwrap(),
895 AppSettings::NoBinaryName);
896 assert_eq!("nextlinehelp".parse::<AppSettings>().unwrap(),
897 AppSettings::NextLineHelp);
898 assert_eq!("subcommandsnegatereqs".parse::<AppSettings>().unwrap(),
899 AppSettings::SubcommandsNegateReqs);
900 assert_eq!("subcommandrequired".parse::<AppSettings>().unwrap(),
901 AppSettings::SubcommandRequired);
902 assert_eq!("subcommandrequiredelsehelp".parse::<AppSettings>().unwrap(),
903 AppSettings::SubcommandRequiredElseHelp);
904 assert_eq!("strictutf8".parse::<AppSettings>().unwrap(),
905 AppSettings::StrictUtf8);
906 assert_eq!("trailingvararg".parse::<AppSettings>().unwrap(),
907 AppSettings::TrailingVarArg);
908 assert_eq!("unifiedhelpmessage".parse::<AppSettings>().unwrap(),
909 AppSettings::UnifiedHelpMessage);
910 assert_eq!("versionlesssubcommands".parse::<AppSettings>().unwrap(),
911 AppSettings::VersionlessSubcommands);
912 assert_eq!("waitonerror".parse::<AppSettings>().unwrap(),
913 AppSettings::WaitOnError);
914 assert!("hahahaha".parse::<AppSettings>().is_err());
915 }
916 }