pub struct Id(_);
Expand description
This is used for accessing the value in ArgMatches
or defining
relationships between Arg
s and ArgGroup
s with functions like
Arg::conflicts_with
.
Implementations§
source§impl Id
impl Id
sourcepub fn as_str(&self) -> &str
pub fn as_str(&self) -> &str
Get the raw string of the Id
Examples found in repository?
src/util/id.rs (line 89)
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self.as_str(), f)
}
}
impl std::fmt::Debug for Id {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(self.as_str(), f)
}
}
impl AsRef<str> for Id {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl std::borrow::Borrow<str> for Id {
#[inline]
fn borrow(&self) -> &str {
self.as_str()
}
}
impl PartialEq<str> for Id {
#[inline]
fn eq(&self, other: &str) -> bool {
PartialEq::eq(self.as_str(), other)
}
}
impl PartialEq<Id> for str {
#[inline]
fn eq(&self, other: &Id) -> bool {
PartialEq::eq(self, other.as_str())
}
}
impl PartialEq<&'_ str> for Id {
#[inline]
fn eq(&self, other: &&str) -> bool {
PartialEq::eq(self.as_str(), *other)
}
}
impl PartialEq<Id> for &'_ str {
#[inline]
fn eq(&self, other: &Id) -> bool {
PartialEq::eq(*self, other.as_str())
}
}
impl PartialEq<Str> for Id {
#[inline]
fn eq(&self, other: &Str) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
}
impl PartialEq<Id> for Str {
#[inline]
fn eq(&self, other: &Id) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
}
impl PartialEq<std::string::String> for Id {
#[inline]
fn eq(&self, other: &std::string::String) -> bool {
PartialEq::eq(self.as_str(), other.as_str())
}
More examples
src/builder/arg.rs (line 4130)
4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
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()
}
}
src/output/help_template.rs (line 977)
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
fn option_sort_key(arg: &Arg) -> (usize, String) {
// Formatting key like this to ensure that:
// 1. Argument has long flags are printed just after short flags.
// 2. For two args both have short flags like `-c` and `-C`, the
// `-C` arg is printed just after the `-c` arg
// 3. For args without short or long flag, print them at last(sorted
// by arg name).
// Example order: -a, -b, -B, -s, --select-file, --select-folder, -x
let key = if let Some(x) = arg.get_short() {
let mut s = x.to_ascii_lowercase().to_string();
s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
s
} else if let Some(x) = arg.get_long() {
x.to_string()
} else {
let mut s = '{'.to_string();
s.push_str(arg.get_id().as_str());
s
};
(arg.get_display_order(), key)
}
src/parser/parser.rs (line 1267)
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 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 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
fn react(
&self,
ident: Option<Identifier>,
source: ValueSource,
arg: &Arg,
mut raw_vals: Vec<OsString>,
mut trailing_idx: Option<usize>,
matcher: &mut ArgMatcher,
) -> ClapResult<ParseResult> {
ok!(self.resolve_pending(matcher));
debug!(
"Parser::react action={:?}, identifier={:?}, source={:?}",
arg.get_action(),
ident,
source
);
// Process before `default_missing_values` to avoid it counting as values from the command
// line
if source == ValueSource::CommandLine {
ok!(self.verify_num_args(arg, &raw_vals));
}
if raw_vals.is_empty() {
// We assume this case is valid: require equals, but min_vals == 0.
if !arg.default_missing_vals.is_empty() {
debug!("Parser::react: has default_missing_vals");
trailing_idx = None;
raw_vals.extend(
arg.default_missing_vals
.iter()
.map(|s| s.as_os_str().to_owned()),
);
}
}
if let Some(val_delim) = arg.get_value_delimiter() {
if self.cmd.is_dont_delimit_trailing_values_set() && trailing_idx == Some(0) {
// Nothing to do
} else {
let mut split_raw_vals = Vec::with_capacity(raw_vals.len());
for (i, raw_val) in raw_vals.into_iter().enumerate() {
let raw_val = RawOsString::new(raw_val);
if !raw_val.contains(val_delim)
|| (self.cmd.is_dont_delimit_trailing_values_set()
&& trailing_idx == Some(i))
{
split_raw_vals.push(raw_val.into_os_string());
} else {
split_raw_vals
.extend(raw_val.split(val_delim).map(|x| x.to_os_str().into_owned()));
}
}
raw_vals = split_raw_vals
}
}
match arg.get_action() {
ArgAction::Set => {
if source == ValueSource::CommandLine
&& matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
{
// Record flag's index
self.cur_idx.set(self.cur_idx.get() + 1);
debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
}
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
self.cmd,
arg.to_string(),
vec![arg.to_string()],
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
debug!(
"Parser::react not enough values passed in, leaving it to the validator to complain",
);
}
Ok(ParseResult::ValuesDone)
}
ArgAction::Append => {
if source == ValueSource::CommandLine
&& matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
{
// Record flag's index
self.cur_idx.set(self.cur_idx.get() + 1);
debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
debug!(
"Parser::react not enough values passed in, leaving it to the validator to complain",
);
}
Ok(ParseResult::ValuesDone)
}
ArgAction::SetTrue => {
let raw_vals = if raw_vals.is_empty() {
vec![OsString::from("true")]
} else {
raw_vals
};
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
self.cmd,
arg.to_string(),
vec![arg.to_string()],
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
}
ArgAction::SetFalse => {
let raw_vals = if raw_vals.is_empty() {
vec![OsString::from("false")]
} else {
raw_vals
};
if matcher.remove(arg.get_id())
&& !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
{
return Err(ClapError::argument_conflict(
self.cmd,
arg.to_string(),
vec![arg.to_string()],
Usage::new(self.cmd).create_usage_with_title(&[]),
));
}
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
}
ArgAction::Count => {
let raw_vals = if raw_vals.is_empty() {
let existing_value = *matcher
.get_one::<crate::builder::CountType>(arg.get_id().as_str())
.unwrap_or(&0);
let next_value = existing_value.saturating_add(1);
vec![OsString::from(next_value.to_string())]
} else {
raw_vals
};
matcher.remove(arg.get_id());
self.start_custom_arg(matcher, arg, source);
ok!(self.push_arg_values(arg, raw_vals, matcher));
Ok(ParseResult::ValuesDone)
}
ArgAction::Help => {
let use_long = match ident {
Some(Identifier::Long) => true,
Some(Identifier::Short) => false,
Some(Identifier::Index) => true,
None => true,
};
debug!("Help: use_long={}", use_long);
Err(self.help_err(use_long))
}
ArgAction::Version => {
let use_long = match ident {
Some(Identifier::Long) => true,
Some(Identifier::Short) => false,
Some(Identifier::Index) => true,
None => true,
};
debug!("Version: use_long={}", use_long);
Err(self.version_err(use_long))
}
}
}
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(())
}
fn remove_overrides(&self, arg: &Arg, matcher: &mut ArgMatcher) {
debug!("Parser::remove_overrides: id={:?}", arg.id);
for override_id in &arg.overrides {
debug!("Parser::remove_overrides:iter:{:?}: removing", override_id);
matcher.remove(override_id);
}
// Override anything that can override us
let mut transitive = Vec::new();
for arg_id in matcher.arg_ids() {
if let Some(overrider) = self.cmd.find(arg_id) {
if overrider.overrides.contains(arg.get_id()) {
transitive.push(overrider.get_id());
}
}
}
for overrider_id in transitive {
debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id);
matcher.remove(overrider_id);
}
}
#[cfg(feature = "env")]
fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> {
debug!("Parser::add_env");
for arg in self.cmd.get_arguments() {
// Use env only if the arg was absent among command line args,
// early return if this is not the case.
if matcher.contains(&arg.id) {
debug!("Parser::add_env: Skipping existing arg `{}`", arg);
continue;
}
debug!("Parser::add_env: Checking arg `{}`", arg);
if let Some((_, Some(ref val))) = arg.env {
debug!("Parser::add_env: Found an opt with value={:?}", val);
let arg_values = vec![val.to_owned()];
let trailing_idx = None;
let _ = ok!(self.react(
None,
ValueSource::EnvVariable,
arg,
arg_values,
trailing_idx,
matcher,
));
}
}
Ok(())
}
fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
debug!("Parser::add_defaults");
for arg in self.cmd.get_arguments() {
debug!("Parser::add_defaults:iter:{}:", arg.get_id());
ok!(self.add_default_value(arg, matcher));
}
Ok(())
}
fn add_default_value(&self, arg: &Arg, matcher: &mut ArgMatcher) -> ClapResult<()> {
if !arg.default_vals_ifs.is_empty() {
debug!("Parser::add_default_value: has conditional defaults");
if !matcher.contains(arg.get_id()) {
for (id, val, default) in arg.default_vals_ifs.iter() {
let add = if let Some(a) = matcher.get(id) {
match val {
crate::builder::ArgPredicate::Equals(v) => {
a.raw_vals_flatten().any(|value| v == value)
}
crate::builder::ArgPredicate::IsPresent => true,
}
} else {
false
};
if add {
if let Some(default) = default {
let arg_values = vec![default.to_os_string()];
let trailing_idx = None;
let _ = ok!(self.react(
None,
ValueSource::DefaultValue,
arg,
arg_values,
trailing_idx,
matcher,
));
}
return Ok(());
}
}
}
} else {
debug!("Parser::add_default_value: doesn't have conditional defaults");
}
if !arg.default_vals.is_empty() {
debug!(
"Parser::add_default_value:iter:{}: has default vals",
arg.get_id()
);
if matcher.contains(arg.get_id()) {
debug!("Parser::add_default_value:iter:{}: was used", arg.get_id());
// do nothing
} else {
debug!(
"Parser::add_default_value:iter:{}: wasn't used",
arg.get_id()
);
let arg_values: Vec<_> = arg
.default_vals
.iter()
.map(crate::builder::OsStr::to_os_string)
.collect();
let trailing_idx = None;
let _ = ok!(self.react(
None,
ValueSource::DefaultValue,
arg,
arg_values,
trailing_idx,
matcher,
));
}
} else {
debug!(
"Parser::add_default_value:iter:{}: doesn't have default vals",
arg.get_id()
);
// do nothing
}
Ok(())
}
fn start_custom_arg(&self, matcher: &mut ArgMatcher, arg: &Arg, source: ValueSource) {
if source == ValueSource::CommandLine {
// With each new occurrence, remove overrides from prior occurrences
self.remove_overrides(arg, matcher);
}
matcher.start_custom_arg(arg, source);
if source.is_explicit() {
for group in self.cmd.groups_for_arg(arg.get_id()) {
matcher.start_custom_group(group.clone(), source);
matcher.add_val_to(
&group,
AnyValue::new(arg.get_id().clone()),
OsString::from(arg.get_id().as_str()),
);
}
}
}
src/builder/debug_asserts.rs (line 71)
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
pub(crate) fn assert_app(cmd: &Command) {
debug!("Command::_debug_asserts");
let mut short_flags = vec![];
let mut long_flags = vec![];
// Invalid version flag settings
if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
// PropagateVersion is meaningless if there is no version
assert!(
!cmd.is_propagate_version_set(),
"Command {}: No version information via Command::version or Command::long_version to propagate",
cmd.get_name(),
);
// Used `Command::mut_arg("version", ..) but did not provide any version information to display
let version_needed = cmd
.get_arguments()
.filter(|x| matches!(x.get_action(), ArgAction::Version))
.map(|x| x.get_id())
.collect::<Vec<_>>();
assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
,cmd.get_name()
);
}
for sc in cmd.get_subcommands() {
if let Some(s) = sc.get_short_flag().as_ref() {
short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
}
for short_alias in sc.get_all_short_flag_aliases() {
short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
}
if let Some(l) = sc.get_long_flag().as_ref() {
assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
}
for long_alias in sc.get_all_long_flag_aliases() {
long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
}
}
for arg in cmd.get_arguments() {
assert_arg(arg);
assert!(
!cmd.is_multicall_set(),
"Command {}: Arguments like {} cannot be set on a multicall command",
cmd.get_name(),
arg.get_id()
);
if let Some(s) = arg.get_short() {
short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
}
for (short_alias, _) in &arg.short_aliases {
short_flags.push(Flag::Arg(
format!("-{}", short_alias),
arg.get_id().as_str(),
));
}
if let Some(l) = arg.get_long() {
assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
}
for (long_alias, _) in &arg.aliases {
long_flags.push(Flag::Arg(
format!("--{}", long_alias),
arg.get_id().as_str(),
));
}
// Name conflicts
if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
panic!(
"Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
cmd.get_name(),
arg.get_id(),
duplicate_tip(cmd, first, second),
);
}
// Long conflicts
if let Some(l) = arg.get_long() {
if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
panic!(
"Command {}: Long option names must be unique for each argument, \
but '--{}' is in use by both '{}' and '{}'{}",
cmd.get_name(),
l,
first.get_id(),
second.get_id(),
duplicate_tip(cmd, first, second)
)
}
}
// Short conflicts
if let Some(s) = arg.get_short() {
if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
panic!(
"Command {}: Short option names must be unique for each argument, \
but '-{}' is in use by both '{}' and '{}'{}",
cmd.get_name(),
s,
first.get_id(),
second.get_id(),
duplicate_tip(cmd, first, second),
)
}
}
// Index conflicts
if let Some(idx) = arg.index {
if let Some((first, second)) =
cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
{
panic!(
"Command {}: Argument '{}' has the same index as '{}' \
and they are both positional arguments\n\n\t \
Use `Arg::num_args(1..)` to allow one \
positional argument to take multiple values",
cmd.get_name(),
first.get_id(),
second.get_id()
)
}
}
// requires, r_if, r_unless
for req in &arg.requires {
assert!(
cmd.id_exists(&req.1),
"Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
cmd.get_name(),
req.1,
arg.get_id(),
);
}
for req in &arg.r_ifs {
assert!(
!arg.is_required_set(),
"Argument {}: `required` conflicts with `required_if_eq*`",
arg.get_id()
);
assert!(
cmd.id_exists(&req.0),
"Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
cmd.get_name(),
req.0,
arg.get_id()
);
}
for req in &arg.r_ifs_all {
assert!(
!arg.is_required_set(),
"Argument {}: `required` conflicts with `required_if_eq_all`",
arg.get_id()
);
assert!(
cmd.id_exists(&req.0),
"Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
cmd.get_name(),
req.0,
arg.get_id()
);
}
for req in &arg.r_unless {
assert!(
!arg.is_required_set(),
"Argument {}: `required` conflicts with `required_unless*`",
arg.get_id()
);
assert!(
cmd.id_exists(req),
"Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
cmd.get_name(),
req,
arg.get_id(),
);
}
for req in &arg.r_unless_all {
assert!(
!arg.is_required_set(),
"Argument {}: `required` conflicts with `required_unless*`",
arg.get_id()
);
assert!(
cmd.id_exists(req),
"Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
cmd.get_name(),
req,
arg.get_id(),
);
}
// blacklist
for req in &arg.blacklist {
assert!(
cmd.id_exists(req),
"Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
cmd.get_name(),
req,
arg.get_id(),
);
}
// overrides
for req in &arg.overrides {
assert!(
cmd.id_exists(req),
"Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
cmd.get_name(),
req,
arg.get_id(),
);
}
if arg.is_last_set() {
assert!(
arg.get_long().is_none(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
cmd.get_name(),
arg.get_id()
);
assert!(
arg.get_short().is_none(),
"Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
cmd.get_name(),
arg.get_id()
);
}
assert!(
!(arg.is_required_set() && arg.is_global_set()),
"Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
cmd.get_name(),
arg.get_id()
);
if arg.get_value_hint() == ValueHint::CommandWithArguments {
assert!(
arg.is_positional(),
"Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
cmd.get_name(),
arg.get_id()
);
assert!(
arg.is_trailing_var_arg_set() || arg.is_last_set(),
"Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
cmd.get_name(),
arg.get_id()
);
}
}
for group in cmd.get_groups() {
let derive_hint = if cfg!(feature = "derive") {
" (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
} else {
""
};
// Name conflicts
assert!(
cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
"Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
cmd.get_name(),
group.get_id(),
derive_hint
);
// Groups should not have naming conflicts with Args
assert!(
!cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
"Command {}: Argument group name '{}' must not conflict with argument name{}",
cmd.get_name(),
group.get_id(),
derive_hint
);
for arg in &group.args {
// Args listed inside groups should exist
assert!(
cmd.get_arguments().any(|x| x.get_id() == arg),
"Command {}: Argument group '{}' contains non-existent argument '{}'",
cmd.get_name(),
group.get_id(),
arg
);
}
}
// Conflicts between flags and subcommands
long_flags.sort_unstable();
short_flags.sort_unstable();
detect_duplicate_flags(&long_flags, "long");
detect_duplicate_flags(&short_flags, "short");
let mut subs = FlatSet::new();
for sc in cmd.get_subcommands() {
assert!(
subs.insert(sc.get_name()),
"Command {}: command name `{}` is duplicated",
cmd.get_name(),
sc.get_name()
);
for alias in sc.get_all_aliases() {
assert!(
subs.insert(alias),
"Command {}: command `{}` alias `{}` is duplicated",
cmd.get_name(),
sc.get_name(),
alias
);
}
}
_verify_positionals(cmd);
#[cfg(feature = "help")]
if let Some(help_template) = cmd.get_help_template() {
assert!(
!help_template.to_string().contains("{flags}"),
"Command {}: {}",
cmd.get_name(),
"`{flags}` template variable was removed in clap3, they are now included in `{options}`",
);
assert!(
!help_template.to_string().contains("{unified}"),
"Command {}: {}",
cmd.get_name(),
"`{unified}` template variable was removed in clap3, use `{options}` instead"
);
#[cfg(feature = "unstable-v5")]
assert!(
!help_template.to_string().contains("{bin}"),
"Command {}: {}",
cmd.get_name(),
"`{bin}` template variable was removed in clap5, use `{name}` instead"
)
}
cmd._panic_on_missing_help(cmd.is_help_expected_set());
assert_app_flags(cmd);
}
Trait Implementations§
source§impl<I: Into<Id>> IntoResettable<Id> for I
impl<I: Into<Id>> IntoResettable<Id> for I
source§fn into_resettable(self) -> Resettable<Id>
fn into_resettable(self) -> Resettable<Id>
Convert to the intended resettable type
source§impl Ord for Id
impl Ord for Id
source§impl PartialEq<&str> for Id
impl PartialEq<&str> for Id
source§impl PartialEq<String> for Id
impl PartialEq<String> for Id
source§impl PartialOrd<Id> for Id
impl PartialOrd<Id> for Id
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read more