Skip to content

Commit 4a4229f

Browse files
committed
feat(subcommands): subcommands can optionally negate parent requirements
Closes #123
1 parent ab4ec60 commit 4a4229f

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/app.rs

+22-1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ pub struct App<'a, 'v, 'ab, 'u, 'h, 'ar> {
109109
needs_short_help: bool,
110110
needs_short_version: bool,
111111
needs_subcmd_help: bool,
112+
subcmds_neg_reqs: bool,
112113
required: HashSet<&'ar str>,
113114
short_list: HashSet<char>,
114115
long_list: HashSet<&'ar str>,
@@ -156,6 +157,7 @@ impl<'a, 'v, 'ab, 'u, 'h, 'ar> App<'a, 'v, 'ab, 'u, 'h, 'ar>{
156157
blacklist: HashSet::new(),
157158
bin_name: None,
158159
groups: HashMap::new(),
160+
subcmds_neg_reqs: false
159161
}
160162
}
161163

@@ -209,6 +211,25 @@ impl<'a, 'v, 'ab, 'u, 'h, 'ar> App<'a, 'v, 'ab, 'u, 'h, 'ar>{
209211
self
210212
}
211213

214+
/// Allows subcommands to override all requirements of the parent (this command). For example
215+
/// if you had a subcommand or even top level application which had a required arguments that
216+
/// is only required if no subcommand is used.
217+
///
218+
/// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
219+
///
220+
/// # Example
221+
///
222+
/// ```no_run
223+
/// # use clap::App;
224+
/// # let app = App::new("myprog")
225+
/// .subcommands_negate_reqs(true)
226+
/// # .get_matches();
227+
/// ```
228+
pub fn subcommands_negate_reqs(mut self, n: bool) -> App<'a, 'v, 'ab, 'u, 'h, 'ar> {
229+
self.subcmds_neg_reqs = n;
230+
self
231+
}
232+
212233
/// Sets a string of the version number to be displayed when displaying version or help
213234
/// information.
214235
///
@@ -1602,7 +1623,7 @@ impl<'a, 'v, 'ab, 'u, 'h, 'ar> App<'a, 'v, 'ab, 'u, 'h, 'ar>{
16021623
self.validate_blacklist(matches);
16031624
self.validate_num_args(matches);
16041625

1605-
if !self.required.is_empty() {
1626+
if !self.required.is_empty() && !self.subcmds_neg_reqs {
16061627
if self.validate_required(&matches) {
16071628
self.report_error(format!("The following required arguments were not \
16081629
supplied:{}",

0 commit comments

Comments
 (0)