Struct clap::builder::ValueRange

source ·
pub struct ValueRange { /* private fields */ }
Expand description

Values per occurrence for an argument

Implementations§

Nor argument values, or a flag

A single argument value, the most common case for options

Create a range

Panics

If the end is less than the start

Examples
let range = ValueRange::new(5);
let range = ValueRange::new(5..10);
let range = ValueRange::new(5..=10);
let range = ValueRange::new(5..);
let range = ValueRange::new(..10);
let range = ValueRange::new(..=10);

While this will panic:

let range = ValueRange::new(10..5);  // Panics!

Fewest number of values the argument accepts

Examples found in repository?
src/builder/arg.rs (line 3852)
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
    pub(crate) fn get_min_vals(&self) -> usize {
        self.get_num_args().expect(INTERNAL_ERROR_MSG).min_values()
    }

    /// Get the delimiter between multiple values
    #[inline]
    pub fn get_value_delimiter(&self) -> Option<char> {
        self.val_delim
    }

    /// Get the index of this argument, if any
    #[inline]
    pub fn get_index(&self) -> Option<usize> {
        self.index
    }

    /// Get the value hint of this argument
    pub fn get_value_hint(&self) -> ValueHint {
        self.value_hint.unwrap_or_else(|| {
            if self.is_takes_value_set() {
                let type_id = self.get_value_parser().type_id();
                if type_id == crate::parser::AnyValueId::of::<std::path::PathBuf>() {
                    ValueHint::AnyPath
                } else {
                    ValueHint::default()
                }
            } else {
                ValueHint::default()
            }
        })
    }

    /// Get the environment variable name specified for this argument, if any
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::ffi::OsStr;
    /// # use clap::Arg;
    /// let arg = Arg::new("foo").env("ENVIRONMENT");
    /// assert_eq!(arg.get_env(), Some(OsStr::new("ENVIRONMENT")));
    /// ```
    #[cfg(feature = "env")]
    pub fn get_env(&self) -> Option<&std::ffi::OsStr> {
        self.env.as_ref().map(|x| x.0.as_os_str())
    }

    /// Get the default values specified for this argument, if any
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Arg;
    /// let arg = Arg::new("foo").default_value("default value");
    /// assert_eq!(arg.get_default_values(), &["default value"]);
    /// ```
    pub fn get_default_values(&self) -> &[OsStr] {
        &self.default_vals
    }

    /// Checks whether this argument is a positional or not.
    ///
    /// # Examples
    ///
    /// ```
    /// # use clap::Arg;
    /// let arg = Arg::new("foo");
    /// assert_eq!(arg.is_positional(), true);
    ///
    /// let arg = Arg::new("foo").long("foo");
    /// assert_eq!(arg.is_positional(), false);
    /// ```
    pub fn is_positional(&self) -> bool {
        self.get_long().is_none() && self.get_short().is_none()
    }

    /// Reports whether [`Arg::required`] is set
    pub fn is_required_set(&self) -> bool {
        self.is_set(ArgSettings::Required)
    }

    pub(crate) fn is_multiple_values_set(&self) -> bool {
        self.get_num_args().unwrap_or_default().is_multiple()
    }

    pub(crate) fn is_takes_value_set(&self) -> bool {
        self.get_action().takes_values()
    }

    /// Report whether [`Arg::allow_hyphen_values`] is set
    pub fn is_allow_hyphen_values_set(&self) -> bool {
        self.is_set(ArgSettings::AllowHyphenValues)
    }

    /// Report whether [`Arg::allow_negative_numbers`] is set
    pub fn is_allow_negative_numbers_set(&self) -> bool {
        self.is_set(ArgSettings::AllowNegativeNumbers)
    }

    /// Behavior when parsing the argument
    pub fn get_action(&self) -> &super::ArgAction {
        const DEFAULT: super::ArgAction = super::ArgAction::Set;
        self.action.as_ref().unwrap_or(&DEFAULT)
    }

    /// Configured parser for argument values
    ///
    /// # Example
    ///
    /// ```rust
    /// let cmd = clap::Command::new("raw")
    ///     .arg(
    ///         clap::Arg::new("port")
    ///             .value_parser(clap::value_parser!(usize))
    ///     );
    /// let value_parser = cmd.get_arguments()
    ///     .find(|a| a.get_id() == "port").unwrap()
    ///     .get_value_parser();
    /// println!("{:?}", value_parser);
    /// ```
    pub fn get_value_parser(&self) -> &super::ValueParser {
        if let Some(value_parser) = self.value_parser.as_ref() {
            value_parser
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::string();
            &DEFAULT
        }
    }

    /// Report whether [`Arg::global`] is set
    pub fn is_global_set(&self) -> bool {
        self.is_set(ArgSettings::Global)
    }

    /// Report whether [`Arg::next_line_help`] is set
    pub fn is_next_line_help_set(&self) -> bool {
        self.is_set(ArgSettings::NextLineHelp)
    }

    /// Report whether [`Arg::hide`] is set
    pub fn is_hide_set(&self) -> bool {
        self.is_set(ArgSettings::Hidden)
    }

    /// Report whether [`Arg::hide_default_value`] is set
    pub fn is_hide_default_value_set(&self) -> bool {
        self.is_set(ArgSettings::HideDefaultValue)
    }

    /// Report whether [`Arg::hide_possible_values`] is set
    pub fn is_hide_possible_values_set(&self) -> bool {
        self.is_set(ArgSettings::HidePossibleValues)
    }

    /// Report whether [`Arg::hide_env`] is set
    #[cfg(feature = "env")]
    pub fn is_hide_env_set(&self) -> bool {
        self.is_set(ArgSettings::HideEnv)
    }

    /// Report whether [`Arg::hide_env_values`] is set
    #[cfg(feature = "env")]
    pub fn is_hide_env_values_set(&self) -> bool {
        self.is_set(ArgSettings::HideEnvValues)
    }

    /// Report whether [`Arg::hide_short_help`] is set
    pub fn is_hide_short_help_set(&self) -> bool {
        self.is_set(ArgSettings::HiddenShortHelp)
    }

    /// Report whether [`Arg::hide_long_help`] is set
    pub fn is_hide_long_help_set(&self) -> bool {
        self.is_set(ArgSettings::HiddenLongHelp)
    }

    /// Report whether [`Arg::require_equals`] is set
    pub fn is_require_equals_set(&self) -> bool {
        self.is_set(ArgSettings::RequireEquals)
    }

    /// Reports whether [`Arg::exclusive`] is set
    pub fn is_exclusive_set(&self) -> bool {
        self.is_set(ArgSettings::Exclusive)
    }

    /// Report whether [`Arg::trailing_var_arg`] is set
    pub fn is_trailing_var_arg_set(&self) -> bool {
        self.is_set(ArgSettings::TrailingVarArg)
    }

    /// Reports whether [`Arg::last`] is set
    pub fn is_last_set(&self) -> bool {
        self.is_set(ArgSettings::Last)
    }

    /// Reports whether [`Arg::ignore_case`] is set
    pub fn is_ignore_case_set(&self) -> bool {
        self.is_set(ArgSettings::IgnoreCase)
    }
}

/// # Internally used only
impl Arg {
    pub(crate) fn _build(&mut self) {
        if self.action.is_none() {
            if self.num_vals == Some(ValueRange::EMPTY) {
                let action = super::ArgAction::SetTrue;
                self.action = Some(action);
            } else {
                let action =
                    if self.is_positional() && self.num_vals.unwrap_or_default().is_unbounded() {
                        // Allow collecting arguments interleaved with flags
                        //
                        // Bounded values are probably a group and the user should explicitly opt-in to
                        // Append
                        super::ArgAction::Append
                    } else {
                        super::ArgAction::Set
                    };
                self.action = Some(action);
            }
        }
        if let Some(action) = self.action.as_ref() {
            if let Some(default_value) = action.default_value() {
                if self.default_vals.is_empty() {
                    self.default_vals = vec![default_value.into()];
                }
            }
            if let Some(default_value) = action.default_missing_value() {
                if self.default_missing_vals.is_empty() {
                    self.default_missing_vals = vec![default_value.into()];
                }
            }
        }

        if self.value_parser.is_none() {
            if let Some(default) = self.action.as_ref().and_then(|a| a.default_value_parser()) {
                self.value_parser = Some(default);
            } else {
                self.value_parser = Some(super::ValueParser::string());
            }
        }

        let val_names_len = self.val_names.len();
        if val_names_len > 1 {
            self.num_vals.get_or_insert(val_names_len.into());
        } else {
            let nargs = if self.get_action().takes_values() {
                ValueRange::SINGLE
            } else {
                ValueRange::EMPTY
            };
            self.num_vals.get_or_insert(nargs);
        }
    }

    // Used for positionals when printing
    pub(crate) fn name_no_brackets(&self) -> String {
        debug!("Arg::name_no_brackets:{}", self.get_id());
        let delim = " ";
        if !self.val_names.is_empty() {
            debug!("Arg::name_no_brackets: val_names={:#?}", self.val_names);

            if self.val_names.len() > 1 {
                self.val_names
                    .iter()
                    .map(|n| format!("<{}>", n))
                    .collect::<Vec<_>>()
                    .join(delim)
            } else {
                self.val_names
                    .first()
                    .expect(INTERNAL_ERROR_MSG)
                    .as_str()
                    .to_owned()
            }
        } else {
            debug!("Arg::name_no_brackets: just name");
            self.get_id().as_str().to_owned()
        }
    }

    pub(crate) fn stylized(&self, required: Option<bool>) -> StyledStr {
        let mut styled = StyledStr::new();
        // Write the name such --long or -l
        if let Some(l) = self.get_long() {
            styled.literal("--");
            styled.literal(l);
        } else if let Some(s) = self.get_short() {
            styled.literal("-");
            styled.literal(s);
        }
        styled.extend(self.stylize_arg_suffix(required).into_iter());
        styled
    }

    pub(crate) fn stylize_arg_suffix(&self, required: Option<bool>) -> StyledStr {
        let mut styled = StyledStr::new();

        let mut need_closing_bracket = false;
        if self.is_takes_value_set() && !self.is_positional() {
            let is_optional_val = self.get_min_vals() == 0;
            if self.is_require_equals_set() {
                if is_optional_val {
                    need_closing_bracket = true;
                    styled.placeholder("[=");
                } else {
                    styled.literal("=");
                }
            } else if is_optional_val {
                need_closing_bracket = true;
                styled.placeholder(" [");
            } else {
                styled.placeholder(" ");
            }
        }
        if self.is_takes_value_set() || self.is_positional() {
            let required = required.unwrap_or_else(|| self.is_required_set());
            let arg_val = self.render_arg_val(required);
            styled.placeholder(arg_val);
        } else if matches!(*self.get_action(), ArgAction::Count) {
            styled.placeholder("...");
        }
        if need_closing_bracket {
            styled.placeholder("]");
        }

        styled
    }

    /// Write the values such as <name1> <name2>
    fn render_arg_val(&self, required: bool) -> String {
        let mut rendered = String::new();

        let num_vals = self.get_num_args().unwrap_or_else(|| 1.into());

        let mut val_names = if self.val_names.is_empty() {
            vec![self.id.as_internal_str().to_owned()]
        } else {
            self.val_names.clone()
        };
        if val_names.len() == 1 {
            let min = num_vals.min_values().max(1);
            let val_name = val_names.pop().unwrap();
            val_names = vec![val_name; min];
        }

        debug_assert!(self.is_takes_value_set());
        for (n, val_name) in val_names.iter().enumerate() {
            let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) {
                format!("[{}]", val_name)
            } else {
                format!("<{}>", val_name)
            };

            if n != 0 {
                rendered.push(' ');
            }
            rendered.push_str(&arg_name);
        }

        let mut extra_values = false;
        extra_values |= val_names.len() < num_vals.max_values();
        if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) {
            extra_values = true;
        }
        if extra_values {
            rendered.push_str("...");
        }

        rendered
    }
More examples
Hide additional examples
src/parser/parser.rs (line 1309)
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
    fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> {
        if self.cmd.is_ignore_errors_set() {
            return Ok(());
        }

        let actual = raw_vals.len();
        let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG);

        if 0 < expected.min_values() && actual == 0 {
            // Issue 665 (https://github.com/clap-rs/clap/issues/665)
            // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
            return Err(ClapError::empty_value(
                self.cmd,
                &super::get_possible_values_cli(arg)
                    .iter()
                    .filter(|pv| !pv.is_hide_set())
                    .map(|n| n.get_name().to_owned())
                    .collect::<Vec<_>>(),
                arg.to_string(),
            ));
        } else if let Some(expected) = expected.num_values() {
            if expected != actual {
                debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
                return Err(ClapError::wrong_number_of_values(
                    self.cmd,
                    arg.to_string(),
                    expected,
                    actual,
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                ));
            }
        } else if actual < expected.min_values() {
            return Err(ClapError::too_few_values(
                self.cmd,
                arg.to_string(),
                expected.min_values(),
                actual,
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        } else if expected.max_values() < actual {
            debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
            return Err(ClapError::too_many_values(
                self.cmd,
                raw_vals
                    .last()
                    .expect(INTERNAL_ERROR_MSG)
                    .to_string_lossy()
                    .into_owned(),
                arg.to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        }

        Ok(())
    }
src/builder/debug_asserts.rs (line 784)
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
fn assert_arg(arg: &Arg) {
    debug!("Arg::_debug_asserts:{}", arg.get_id());

    // Self conflict
    // TODO: this check should be recursive
    assert!(
        !arg.blacklist.iter().any(|x| x == arg.get_id()),
        "Argument '{}' cannot conflict with itself",
        arg.get_id(),
    );

    assert_eq!(
        arg.get_action().takes_values(),
        arg.is_takes_value_set(),
        "Argument `{}`'s selected action {:?} contradicts `takes_value`",
        arg.get_id(),
        arg.get_action()
    );
    if let Some(action_type_id) = arg.get_action().value_type_id() {
        assert_eq!(
            action_type_id,
            arg.get_value_parser().type_id(),
            "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})",
            arg.get_id(),
            arg.get_action(),
            arg.get_value_parser()
        );
    }

    if arg.get_value_hint() != ValueHint::Unknown {
        assert!(
            arg.is_takes_value_set(),
            "Argument '{}' has value hint but takes no value",
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_multiple_values_set(),
                "Argument '{}' uses hint CommandWithArguments and must accept multiple values",
                arg.get_id()
            )
        }
    }

    if arg.index.is_some() {
        assert!(
            arg.is_positional(),
            "Argument '{}' is a positional argument and can't have short or long name versions",
            arg.get_id()
        );
        assert!(
            arg.is_takes_value_set(),
            "Argument '{}` is positional, it must take a value{}",
            arg.get_id(),
            if arg.get_id() == Id::HELP {
                " (`mut_arg` no longer works with implicit `--help`)"
            } else if arg.get_id() == Id::VERSION {
                " (`mut_arg` no longer works with implicit `--version`)"
            } else {
                ""
            }
        );
    }

    let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG);
    // This can be the cause of later asserts, so put this first
    if num_vals != ValueRange::EMPTY {
        // HACK: Don't check for flags to make the derive easier
        let num_val_names = arg.get_value_names().unwrap_or(&[]).len();
        if num_vals.max_values() < num_val_names {
            panic!(
                "Argument {}: Too many value names ({}) compared to `num_args` ({})",
                arg.get_id(),
                num_val_names,
                num_vals
            );
        }
    }

    assert_eq!(
        num_vals.takes_values(),
        arg.is_takes_value_set(),
        "Argument {}: mismatch between `num_args` ({}) and `takes_value`",
        arg.get_id(),
        num_vals,
    );
    assert_eq!(
        num_vals.is_multiple(),
        arg.is_multiple_values_set(),
        "Argument {}: mismatch between `num_args` ({}) and `multiple_values`",
        arg.get_id(),
        num_vals,
    );

    if 1 < num_vals.min_values() {
        assert!(
            !arg.is_require_equals_set(),
            "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals",
            arg.get_id(),
            num_vals
        );
    }

    if num_vals == ValueRange::SINGLE {
        assert!(
            !arg.is_multiple_values_set(),
            "Argument {}: mismatch between `num_args` and `multiple_values`",
            arg.get_id()
        );
    }

    assert_arg_flags(arg);

    assert_defaults(arg, "default_value", arg.default_vals.iter());
    assert_defaults(
        arg,
        "default_missing_value",
        arg.default_missing_vals.iter(),
    );
    assert_defaults(
        arg,
        "default_value_if",
        arg.default_vals_ifs
            .iter()
            .filter_map(|(_, _, default)| default.as_ref()),
    );
}

Most number of values the argument accepts

Examples found in repository?
src/builder/arg.rs (line 4214)
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
    fn render_arg_val(&self, required: bool) -> String {
        let mut rendered = String::new();

        let num_vals = self.get_num_args().unwrap_or_else(|| 1.into());

        let mut val_names = if self.val_names.is_empty() {
            vec![self.id.as_internal_str().to_owned()]
        } else {
            self.val_names.clone()
        };
        if val_names.len() == 1 {
            let min = num_vals.min_values().max(1);
            let val_name = val_names.pop().unwrap();
            val_names = vec![val_name; min];
        }

        debug_assert!(self.is_takes_value_set());
        for (n, val_name) in val_names.iter().enumerate() {
            let arg_name = if self.is_positional() && (num_vals.min_values() == 0 || !required) {
                format!("[{}]", val_name)
            } else {
                format!("<{}>", val_name)
            };

            if n != 0 {
                rendered.push(' ');
            }
            rendered.push_str(&arg_name);
        }

        let mut extra_values = false;
        extra_values |= val_names.len() < num_vals.max_values();
        if self.is_positional() && matches!(*self.get_action(), ArgAction::Append) {
            extra_values = true;
        }
        if extra_values {
            rendered.push_str("...");
        }

        rendered
    }
More examples
Hide additional examples
src/parser/parser.rs (line 1340)
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
    fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> {
        if self.cmd.is_ignore_errors_set() {
            return Ok(());
        }

        let actual = raw_vals.len();
        let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG);

        if 0 < expected.min_values() && actual == 0 {
            // Issue 665 (https://github.com/clap-rs/clap/issues/665)
            // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
            return Err(ClapError::empty_value(
                self.cmd,
                &super::get_possible_values_cli(arg)
                    .iter()
                    .filter(|pv| !pv.is_hide_set())
                    .map(|n| n.get_name().to_owned())
                    .collect::<Vec<_>>(),
                arg.to_string(),
            ));
        } else if let Some(expected) = expected.num_values() {
            if expected != actual {
                debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
                return Err(ClapError::wrong_number_of_values(
                    self.cmd,
                    arg.to_string(),
                    expected,
                    actual,
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                ));
            }
        } else if actual < expected.min_values() {
            return Err(ClapError::too_few_values(
                self.cmd,
                arg.to_string(),
                expected.min_values(),
                actual,
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        } else if expected.max_values() < actual {
            debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
            return Err(ClapError::too_many_values(
                self.cmd,
                raw_vals
                    .last()
                    .expect(INTERNAL_ERROR_MSG)
                    .to_string_lossy()
                    .into_owned(),
                arg.to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        }

        Ok(())
    }
src/builder/debug_asserts.rs (line 759)
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
fn assert_arg(arg: &Arg) {
    debug!("Arg::_debug_asserts:{}", arg.get_id());

    // Self conflict
    // TODO: this check should be recursive
    assert!(
        !arg.blacklist.iter().any(|x| x == arg.get_id()),
        "Argument '{}' cannot conflict with itself",
        arg.get_id(),
    );

    assert_eq!(
        arg.get_action().takes_values(),
        arg.is_takes_value_set(),
        "Argument `{}`'s selected action {:?} contradicts `takes_value`",
        arg.get_id(),
        arg.get_action()
    );
    if let Some(action_type_id) = arg.get_action().value_type_id() {
        assert_eq!(
            action_type_id,
            arg.get_value_parser().type_id(),
            "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})",
            arg.get_id(),
            arg.get_action(),
            arg.get_value_parser()
        );
    }

    if arg.get_value_hint() != ValueHint::Unknown {
        assert!(
            arg.is_takes_value_set(),
            "Argument '{}' has value hint but takes no value",
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_multiple_values_set(),
                "Argument '{}' uses hint CommandWithArguments and must accept multiple values",
                arg.get_id()
            )
        }
    }

    if arg.index.is_some() {
        assert!(
            arg.is_positional(),
            "Argument '{}' is a positional argument and can't have short or long name versions",
            arg.get_id()
        );
        assert!(
            arg.is_takes_value_set(),
            "Argument '{}` is positional, it must take a value{}",
            arg.get_id(),
            if arg.get_id() == Id::HELP {
                " (`mut_arg` no longer works with implicit `--help`)"
            } else if arg.get_id() == Id::VERSION {
                " (`mut_arg` no longer works with implicit `--version`)"
            } else {
                ""
            }
        );
    }

    let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG);
    // This can be the cause of later asserts, so put this first
    if num_vals != ValueRange::EMPTY {
        // HACK: Don't check for flags to make the derive easier
        let num_val_names = arg.get_value_names().unwrap_or(&[]).len();
        if num_vals.max_values() < num_val_names {
            panic!(
                "Argument {}: Too many value names ({}) compared to `num_args` ({})",
                arg.get_id(),
                num_val_names,
                num_vals
            );
        }
    }

    assert_eq!(
        num_vals.takes_values(),
        arg.is_takes_value_set(),
        "Argument {}: mismatch between `num_args` ({}) and `takes_value`",
        arg.get_id(),
        num_vals,
    );
    assert_eq!(
        num_vals.is_multiple(),
        arg.is_multiple_values_set(),
        "Argument {}: mismatch between `num_args` ({}) and `multiple_values`",
        arg.get_id(),
        num_vals,
    );

    if 1 < num_vals.min_values() {
        assert!(
            !arg.is_require_equals_set(),
            "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals",
            arg.get_id(),
            num_vals
        );
    }

    if num_vals == ValueRange::SINGLE {
        assert!(
            !arg.is_multiple_values_set(),
            "Argument {}: mismatch between `num_args` and `multiple_values`",
            arg.get_id()
        );
    }

    assert_arg_flags(arg);

    assert_defaults(arg, "default_value", arg.default_vals.iter());
    assert_defaults(
        arg,
        "default_missing_value",
        arg.default_missing_vals.iter(),
    );
    assert_defaults(
        arg,
        "default_value_if",
        arg.default_vals_ifs
            .iter()
            .filter_map(|(_, _, default)| default.as_ref()),
    );
}

Report whether the argument takes any values (ie is a flag)

Examples
let range = ValueRange::new(5);
assert!(range.takes_values());

let range = ValueRange::new(0);
assert!(!range.takes_values());
Examples found in repository?
src/builder/debug_asserts.rs (line 770)
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
fn assert_arg(arg: &Arg) {
    debug!("Arg::_debug_asserts:{}", arg.get_id());

    // Self conflict
    // TODO: this check should be recursive
    assert!(
        !arg.blacklist.iter().any(|x| x == arg.get_id()),
        "Argument '{}' cannot conflict with itself",
        arg.get_id(),
    );

    assert_eq!(
        arg.get_action().takes_values(),
        arg.is_takes_value_set(),
        "Argument `{}`'s selected action {:?} contradicts `takes_value`",
        arg.get_id(),
        arg.get_action()
    );
    if let Some(action_type_id) = arg.get_action().value_type_id() {
        assert_eq!(
            action_type_id,
            arg.get_value_parser().type_id(),
            "Argument `{}`'s selected action {:?} contradicts `value_parser` ({:?})",
            arg.get_id(),
            arg.get_action(),
            arg.get_value_parser()
        );
    }

    if arg.get_value_hint() != ValueHint::Unknown {
        assert!(
            arg.is_takes_value_set(),
            "Argument '{}' has value hint but takes no value",
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_multiple_values_set(),
                "Argument '{}' uses hint CommandWithArguments and must accept multiple values",
                arg.get_id()
            )
        }
    }

    if arg.index.is_some() {
        assert!(
            arg.is_positional(),
            "Argument '{}' is a positional argument and can't have short or long name versions",
            arg.get_id()
        );
        assert!(
            arg.is_takes_value_set(),
            "Argument '{}` is positional, it must take a value{}",
            arg.get_id(),
            if arg.get_id() == Id::HELP {
                " (`mut_arg` no longer works with implicit `--help`)"
            } else if arg.get_id() == Id::VERSION {
                " (`mut_arg` no longer works with implicit `--version`)"
            } else {
                ""
            }
        );
    }

    let num_vals = arg.get_num_args().expect(INTERNAL_ERROR_MSG);
    // This can be the cause of later asserts, so put this first
    if num_vals != ValueRange::EMPTY {
        // HACK: Don't check for flags to make the derive easier
        let num_val_names = arg.get_value_names().unwrap_or(&[]).len();
        if num_vals.max_values() < num_val_names {
            panic!(
                "Argument {}: Too many value names ({}) compared to `num_args` ({})",
                arg.get_id(),
                num_val_names,
                num_vals
            );
        }
    }

    assert_eq!(
        num_vals.takes_values(),
        arg.is_takes_value_set(),
        "Argument {}: mismatch between `num_args` ({}) and `takes_value`",
        arg.get_id(),
        num_vals,
    );
    assert_eq!(
        num_vals.is_multiple(),
        arg.is_multiple_values_set(),
        "Argument {}: mismatch between `num_args` ({}) and `multiple_values`",
        arg.get_id(),
        num_vals,
    );

    if 1 < num_vals.min_values() {
        assert!(
            !arg.is_require_equals_set(),
            "Argument {}: cannot accept more than 1 arg (num_args={}) with require_equals",
            arg.get_id(),
            num_vals
        );
    }

    if num_vals == ValueRange::SINGLE {
        assert!(
            !arg.is_multiple_values_set(),
            "Argument {}: mismatch between `num_args` and `multiple_values`",
            arg.get_id()
        );
    }

    assert_arg_flags(arg);

    assert_defaults(arg, "default_value", arg.default_vals.iter());
    assert_defaults(
        arg,
        "default_missing_value",
        arg.default_missing_vals.iter(),
    );
    assert_defaults(
        arg,
        "default_value_if",
        arg.default_vals_ifs
            .iter()
            .filter_map(|(_, _, default)| default.as_ref()),
    );
}

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
Convert to the intended resettable type
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
Start index bound. Read more
End index bound. Read more
Returns true if item is contained in the range. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.