1use crate::CargoResult;
2use crate::core::Dependency;
3use crate::core::compiler::{BuildConfig, CompileKind, MessageFormat, RustcTargetData};
4use crate::core::resolver::{CliFeatures, ForceAllTargets, HasDevUnits};
5use crate::core::{Edition, Package, TargetKind, Workspace, profiles::Profiles};
6use crate::ops::registry::RegistryOrIndex;
7use crate::ops::{self, CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
8use crate::util::important_paths::find_root_manifest_for_wd;
9use crate::util::interning::InternedString;
10use crate::util::is_rustup;
11use crate::util::restricted_names;
12use crate::util::toml::is_embedded;
13use crate::util::{
14 print_available_benches, print_available_binaries, print_available_examples,
15 print_available_packages, print_available_tests,
16};
17use anyhow::bail;
18use cargo_util::paths;
19use cargo_util_schemas::manifest::ProfileName;
20use cargo_util_schemas::manifest::RegistryName;
21use cargo_util_schemas::manifest::StringOrVec;
22use cargo_util_terminal as shell;
23use clap::builder::UnknownArgumentValueParser;
24use clap_complete::ArgValueCandidates;
25use home::cargo_home_with_cwd;
26use indexmap::IndexSet;
27use itertools::Itertools;
28use semver::Version;
29use std::collections::{BTreeMap, HashMap, HashSet};
30use std::ffi::{OsStr, OsString};
31use std::path::Path;
32use std::path::PathBuf;
33
34pub use crate::core::compiler::UserIntent;
35pub use crate::{CliError, CliResult, GlobalContext};
36pub use clap::{Arg, ArgAction, ArgMatches, value_parser};
37
38pub use clap::Command;
39
40use super::IntoUrl;
41use super::context::JobsConfig;
42
43pub mod heading {
44 pub const PACKAGE_SELECTION: &str = "Package Selection";
45 pub const TARGET_SELECTION: &str = "Target Selection";
46 pub const FEATURE_SELECTION: &str = "Feature Selection";
47 pub const COMPILATION_OPTIONS: &str = "Compilation Options";
48 pub const MANIFEST_OPTIONS: &str = "Manifest Options";
49}
50
51pub trait CommandExt: Sized {
52 fn _arg(self, arg: Arg) -> Self;
53
54 fn arg_package_spec(
57 self,
58 package: &'static str,
59 all: &'static str,
60 exclude: &'static str,
61 ) -> Self {
62 self.arg_package_spec_no_all(
63 package,
64 all,
65 exclude,
66 ArgValueCandidates::new(get_ws_member_candidates),
67 )
68 ._arg(
69 flag("all", "Alias for --workspace (deprecated)")
70 .help_heading(heading::PACKAGE_SELECTION),
71 )
72 }
73
74 fn arg_package_spec_no_all(
78 self,
79 package: &'static str,
80 all: &'static str,
81 exclude: &'static str,
82 package_completion: ArgValueCandidates,
83 ) -> Self {
84 let unsupported_short_arg = {
85 let value_parser = UnknownArgumentValueParser::suggest_arg("--exclude");
86 Arg::new("unsupported-short-exclude-flag")
87 .help("")
88 .short('x')
89 .value_parser(value_parser)
90 .action(ArgAction::SetTrue)
91 .hide(true)
92 };
93 self.arg_package_spec_simple(package, package_completion)
94 ._arg(flag("workspace", all).help_heading(heading::PACKAGE_SELECTION))
95 ._arg(
96 multi_opt("exclude", "SPEC", exclude)
97 .help_heading(heading::PACKAGE_SELECTION)
98 .add(clap_complete::ArgValueCandidates::new(
99 get_ws_member_candidates,
100 )),
101 )
102 ._arg(unsupported_short_arg)
103 }
104
105 fn arg_package_spec_simple(
106 self,
107 package: &'static str,
108 package_completion: ArgValueCandidates,
109 ) -> Self {
110 self._arg(
111 optional_multi_opt("package", "SPEC", package)
112 .short('p')
113 .help_heading(heading::PACKAGE_SELECTION)
114 .add(package_completion),
115 )
116 }
117
118 fn arg_package(self, package: &'static str) -> Self {
119 self._arg(
120 optional_opt("package", package)
121 .short('p')
122 .value_name("SPEC")
123 .help_heading(heading::PACKAGE_SELECTION)
124 .add(clap_complete::ArgValueCandidates::new(|| {
125 get_ws_member_candidates()
126 })),
127 )
128 }
129
130 fn arg_parallel(self) -> Self {
131 self.arg_jobs()._arg(
132 flag(
133 "keep-going",
134 "Do not abort the build as soon as there is an error",
135 )
136 .help_heading(heading::COMPILATION_OPTIONS),
137 )
138 }
139
140 fn arg_jobs(self) -> Self {
141 self._arg(
142 opt("jobs", "Number of parallel jobs, defaults to # of CPUs.")
143 .short('j')
144 .value_name("N")
145 .allow_hyphen_values(true)
146 .help_heading(heading::COMPILATION_OPTIONS),
147 )
148 }
149
150 fn arg_unsupported_keep_going(self) -> Self {
151 let msg = "use `--no-fail-fast` to run as many tests as possible regardless of failure";
152 let value_parser = UnknownArgumentValueParser::suggest(msg);
153 self._arg(flag("keep-going", "").value_parser(value_parser).hide(true))
154 }
155
156 fn arg_redundant_default_mode(
157 self,
158 default_mode: &'static str,
159 command: &'static str,
160 supported_mode: &'static str,
161 ) -> Self {
162 let msg = format!(
163 "`--{default_mode}` is the default for `cargo {command}`; instead `--{supported_mode}` is supported"
164 );
165 let value_parser = UnknownArgumentValueParser::suggest(msg);
166 self._arg(
167 flag(default_mode, "")
168 .conflicts_with("profile")
169 .value_parser(value_parser)
170 .hide(true),
171 )
172 }
173
174 fn arg_targets_all(
175 self,
176 lib: &'static str,
177 bin: &'static str,
178 bins: &'static str,
179 example: &'static str,
180 examples: &'static str,
181 test: &'static str,
182 tests: &'static str,
183 bench: &'static str,
184 benches: &'static str,
185 all: &'static str,
186 ) -> Self {
187 self.arg_targets_lib_bin_example(lib, bin, bins, example, examples)
188 ._arg(flag("tests", tests).help_heading(heading::TARGET_SELECTION))
189 ._arg(
190 optional_multi_opt("test", "NAME", test)
191 .help_heading(heading::TARGET_SELECTION)
192 .add(clap_complete::ArgValueCandidates::new(|| {
193 get_crate_candidates(TargetKind::Test).unwrap_or_default()
194 })),
195 )
196 ._arg(flag("benches", benches).help_heading(heading::TARGET_SELECTION))
197 ._arg(
198 optional_multi_opt("bench", "NAME", bench)
199 .help_heading(heading::TARGET_SELECTION)
200 .add(clap_complete::ArgValueCandidates::new(|| {
201 get_crate_candidates(TargetKind::Bench).unwrap_or_default()
202 })),
203 )
204 ._arg(flag("all-targets", all).help_heading(heading::TARGET_SELECTION))
205 }
206
207 fn arg_targets_lib_bin_example(
208 self,
209 lib: &'static str,
210 bin: &'static str,
211 bins: &'static str,
212 example: &'static str,
213 examples: &'static str,
214 ) -> Self {
215 self._arg(flag("lib", lib).help_heading(heading::TARGET_SELECTION))
216 ._arg(flag("bins", bins).help_heading(heading::TARGET_SELECTION))
217 ._arg(
218 optional_multi_opt("bin", "NAME", bin)
219 .help_heading(heading::TARGET_SELECTION)
220 .add(clap_complete::ArgValueCandidates::new(|| {
221 get_crate_candidates(TargetKind::Bin).unwrap_or_default()
222 })),
223 )
224 ._arg(flag("examples", examples).help_heading(heading::TARGET_SELECTION))
225 ._arg(
226 optional_multi_opt("example", "NAME", example)
227 .help_heading(heading::TARGET_SELECTION)
228 .add(clap_complete::ArgValueCandidates::new(|| {
229 get_crate_candidates(TargetKind::ExampleBin).unwrap_or_default()
230 })),
231 )
232 }
233
234 fn arg_targets_bins_examples(
235 self,
236 bin: &'static str,
237 bins: &'static str,
238 example: &'static str,
239 examples: &'static str,
240 ) -> Self {
241 self._arg(
242 optional_multi_opt("bin", "NAME", bin)
243 .help_heading(heading::TARGET_SELECTION)
244 .add(clap_complete::ArgValueCandidates::new(|| {
245 get_crate_candidates(TargetKind::Bin).unwrap_or_default()
246 })),
247 )
248 ._arg(flag("bins", bins).help_heading(heading::TARGET_SELECTION))
249 ._arg(
250 optional_multi_opt("example", "NAME", example)
251 .help_heading(heading::TARGET_SELECTION)
252 .add(clap_complete::ArgValueCandidates::new(|| {
253 get_crate_candidates(TargetKind::ExampleBin).unwrap_or_default()
254 })),
255 )
256 ._arg(flag("examples", examples).help_heading(heading::TARGET_SELECTION))
257 }
258
259 fn arg_targets_bin_example(self, bin: &'static str, example: &'static str) -> Self {
260 self._arg(
261 optional_multi_opt("bin", "NAME", bin)
262 .help_heading(heading::TARGET_SELECTION)
263 .add(clap_complete::ArgValueCandidates::new(|| {
264 get_crate_candidates(TargetKind::Bin).unwrap_or_default()
265 })),
266 )
267 ._arg(
268 optional_multi_opt("example", "NAME", example)
269 .help_heading(heading::TARGET_SELECTION)
270 .add(clap_complete::ArgValueCandidates::new(|| {
271 get_crate_candidates(TargetKind::ExampleBin).unwrap_or_default()
272 })),
273 )
274 }
275
276 fn arg_features(self) -> Self {
277 self._arg(
278 multi_opt(
279 "features",
280 "FEATURES",
281 "Space or comma separated list of features to activate",
282 )
283 .short('F')
284 .help_heading(heading::FEATURE_SELECTION)
285 .add(clap_complete::ArgValueCandidates::new(|| {
286 get_feature_candidates().unwrap_or_default()
287 })),
288 )
289 ._arg(
290 flag("all-features", "Activate all available features")
291 .help_heading(heading::FEATURE_SELECTION),
292 )
293 ._arg(
294 flag(
295 "no-default-features",
296 "Do not activate the `default` feature",
297 )
298 .help_heading(heading::FEATURE_SELECTION),
299 )
300 }
301
302 fn arg_release(self, release: &'static str) -> Self {
303 self._arg(
304 flag("release", release)
305 .short('r')
306 .conflicts_with("profile")
307 .help_heading(heading::COMPILATION_OPTIONS),
308 )
309 }
310
311 fn arg_profile(self, profile: &'static str) -> Self {
312 self._arg(
313 opt("profile", profile)
314 .value_name("PROFILE-NAME")
315 .help_heading(heading::COMPILATION_OPTIONS)
316 .add(clap_complete::ArgValueCandidates::new(|| {
317 let candidates = get_profile_candidates();
318 candidates
319 })),
320 )
321 }
322
323 fn arg_doc(self, doc: &'static str) -> Self {
324 self._arg(flag("doc", doc))
325 }
326
327 fn arg_target_triple(self, target: &'static str) -> Self {
328 self.arg_target_triple_with_candidates(target, ArgValueCandidates::new(get_target_triples))
329 }
330
331 fn arg_target_triple_with_candidates(
332 self,
333 target: &'static str,
334 target_completion: ArgValueCandidates,
335 ) -> Self {
336 let unsupported_short_arg = {
337 let value_parser = UnknownArgumentValueParser::suggest_arg("--target");
338 Arg::new("unsupported-short-target-flag")
339 .help("")
340 .short('t')
341 .value_parser(value_parser)
342 .action(ArgAction::SetTrue)
343 .hide(true)
344 };
345 self._arg(
346 optional_multi_opt("target", "TRIPLE", target)
347 .help_heading(heading::COMPILATION_OPTIONS)
348 .add(target_completion),
349 )
350 ._arg(unsupported_short_arg)
351 }
352
353 fn arg_target_dir(self) -> Self {
354 self._arg(
355 opt("target-dir", "Directory for all generated artifacts")
356 .value_name("DIRECTORY")
357 .help_heading(heading::COMPILATION_OPTIONS),
358 )
359 }
360
361 fn arg_manifest_path(self) -> Self {
362 let unsupported_path_arg = {
364 let value_parser = UnknownArgumentValueParser::suggest_arg("--manifest-path");
365 flag("unsupported-path-flag", "")
366 .long("path")
367 .value_parser(value_parser)
368 .hide(true)
369 };
370 self.arg_manifest_path_without_unsupported_path_tip()
371 ._arg(unsupported_path_arg)
372 }
373
374 fn arg_manifest_path_without_unsupported_path_tip(self) -> Self {
376 self._arg(
377 opt("manifest-path", "Path to Cargo.toml")
378 .value_name("PATH")
379 .help_heading(heading::MANIFEST_OPTIONS)
380 .add(clap_complete::engine::ArgValueCompleter::new(
381 clap_complete::engine::PathCompleter::any().filter(|path: &Path| {
382 if path.file_name() == Some(OsStr::new("Cargo.toml")) {
383 return true;
384 }
385 if is_embedded(path) {
386 return true;
387 }
388 false
389 }),
390 )),
391 )
392 }
393
394 fn arg_message_format(self) -> Self {
395 self._arg(
396 multi_opt("message-format", "FMT", "Error format")
397 .value_parser([
398 "human",
399 "short",
400 "json",
401 "json-diagnostic-short",
402 "json-diagnostic-rendered-ansi",
403 "json-render-diagnostics",
404 ])
405 .value_delimiter(',')
406 .ignore_case(true),
407 )
408 }
409
410 fn arg_unit_graph(self) -> Self {
411 self._arg(
412 flag("unit-graph", "Output build graph in JSON (unstable)")
413 .help_heading(heading::COMPILATION_OPTIONS),
414 )
415 }
416
417 fn arg_new_opts(self) -> Self {
418 self._arg(
419 opt(
420 "vcs",
421 "Initialize a new repository for the given version \
422 control system, overriding \
423 a global configuration.",
424 )
425 .value_name("VCS")
426 .value_parser(["git", "hg", "pijul", "fossil", "none"]),
427 )
428 ._arg(flag("bin", "Use a binary (application) template [default]"))
429 ._arg(flag("lib", "Use a library template"))
430 ._arg(
431 opt("edition", "Edition to set for the crate generated")
432 .value_parser(Edition::CLI_VALUES)
433 .value_name("YEAR"),
434 )
435 ._arg(
436 opt(
437 "name",
438 "Set the resulting package name, defaults to the directory name",
439 )
440 .value_name("NAME"),
441 )
442 }
443
444 fn arg_registry(self, help: &'static str) -> Self {
445 self._arg(opt("registry", help).value_name("REGISTRY").add(
446 clap_complete::ArgValueCandidates::new(|| {
447 let candidates = get_registry_candidates();
448 candidates.unwrap_or_default()
449 }),
450 ))
451 }
452
453 fn arg_index(self, help: &'static str) -> Self {
454 self._arg(
456 opt("index", help)
457 .value_name("INDEX")
458 .conflicts_with("registry"),
459 )
460 }
461
462 fn arg_dry_run(self, dry_run: &'static str) -> Self {
463 self._arg(flag("dry-run", dry_run).short('n'))
464 }
465
466 fn arg_ignore_rust_version(self) -> Self {
467 self.arg_ignore_rust_version_with_help("Ignore `rust-version` specification in packages")
468 }
469
470 fn arg_ignore_rust_version_with_help(self, help: &'static str) -> Self {
471 self._arg(flag("ignore-rust-version", help).help_heading(heading::MANIFEST_OPTIONS))
472 }
473
474 fn arg_future_incompat_report(self) -> Self {
475 self._arg(flag(
476 "future-incompat-report",
477 "Outputs a future incompatibility report at the end of the build",
478 ))
479 }
480
481 fn arg_silent_suggestion(self) -> Self {
487 let value_parser = UnknownArgumentValueParser::suggest_arg("--quiet");
488 self._arg(
489 flag("silent", "")
490 .short('s')
491 .value_parser(value_parser)
492 .hide(true),
493 )
494 }
495
496 fn arg_timings(self) -> Self {
497 self._arg(
498 flag(
499 "timings",
500 "Output a build timing report at the end of the build",
501 )
502 .help_heading(heading::COMPILATION_OPTIONS),
503 )
504 }
505
506 fn arg_artifact_dir(self) -> Self {
507 let unsupported_short_arg = {
508 let value_parser = UnknownArgumentValueParser::suggest_arg("--artifact-dir");
509 Arg::new("unsupported-short-artifact-dir-flag")
510 .help("")
511 .short('O')
512 .value_parser(value_parser)
513 .action(ArgAction::SetTrue)
514 .hide(true)
515 };
516
517 self._arg(
518 opt(
519 "artifact-dir",
520 "Copy final artifacts to this directory (unstable)",
521 )
522 .value_name("PATH")
523 .help_heading(heading::COMPILATION_OPTIONS),
524 )
525 ._arg(unsupported_short_arg)
526 ._arg({
527 let value_parser = UnknownArgumentValueParser::suggest_arg("--artifact-dir");
528 Arg::new("unsupported-out-dir-flag")
529 .help("")
530 .long("out-dir")
531 .value_name("PATH")
532 .value_parser(value_parser)
533 .action(ArgAction::SetTrue)
534 .hide(true)
535 })
536 }
537
538 fn arg_compile_time_deps(self) -> Self {
539 self._arg(flag("compile-time-deps", "").hide(true))
540 }
541}
542
543impl CommandExt for Command {
544 fn _arg(self, arg: Arg) -> Self {
545 self.arg(arg)
546 }
547}
548
549pub fn flag(name: &'static str, help: &'static str) -> Arg {
550 Arg::new(name)
551 .long(name)
552 .help(help)
553 .action(ArgAction::SetTrue)
554}
555
556pub fn opt(name: &'static str, help: &'static str) -> Arg {
557 Arg::new(name).long(name).help(help).action(ArgAction::Set)
558}
559
560pub fn optional_opt(name: &'static str, help: &'static str) -> Arg {
561 opt(name, help).num_args(0..=1)
562}
563
564pub fn optional_multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Arg {
565 opt(name, help)
566 .value_name(value_name)
567 .num_args(0..=1)
568 .action(ArgAction::Append)
569}
570
571pub fn multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Arg {
572 opt(name, help)
573 .value_name(value_name)
574 .action(ArgAction::Append)
575}
576
577pub fn subcommand(name: &'static str) -> Command {
578 Command::new(name)
579}
580
581pub enum ProfileChecking {
583 LegacyRustc,
586 LegacyTestOnly,
589 Custom,
591}
592
593pub trait ArgMatchesExt {
594 fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
595 let arg = match self._value_of(name) {
596 None => None,
597 Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
598 clap::Error::raw(
599 clap::error::ErrorKind::ValueValidation,
600 format!("invalid value: could not parse `{}` as a number", arg),
601 )
602 })?),
603 };
604 Ok(arg)
605 }
606
607 fn value_of_i32(&self, name: &str) -> CargoResult<Option<i32>> {
608 let arg = match self._value_of(name) {
609 None => None,
610 Some(arg) => Some(arg.parse::<i32>().map_err(|_| {
611 clap::Error::raw(
612 clap::error::ErrorKind::ValueValidation,
613 format!("invalid value: could not parse `{}` as a number", arg),
614 )
615 })?),
616 };
617 Ok(arg)
618 }
619
620 fn value_of_path(&self, name: &str, gctx: &GlobalContext) -> Option<PathBuf> {
622 self._value_of(name).map(|path| gctx.cwd().join(path))
623 }
624
625 fn root_manifest(&self, gctx: &GlobalContext) -> CargoResult<PathBuf> {
626 root_manifest(self._value_of("manifest-path").map(Path::new), gctx)
627 }
628
629 #[tracing::instrument(skip_all)]
630 fn workspace<'a>(&self, gctx: &'a GlobalContext) -> CargoResult<Workspace<'a>> {
631 let root = self.root_manifest(gctx)?;
632 let mut ws = Workspace::new(&root, gctx)?;
633 ws.set_resolve_honors_rust_version(self.honor_rust_version());
634 if gctx.cli_unstable().avoid_dev_deps {
635 ws.set_require_optional_deps(false);
636 }
637 Ok(ws)
638 }
639
640 fn jobs(&self) -> CargoResult<Option<JobsConfig>> {
641 let arg = match self._value_of("jobs") {
642 None => None,
643 Some(arg) => match arg.parse::<i32>() {
644 Ok(j) => Some(JobsConfig::Integer(j)),
645 Err(_) => Some(JobsConfig::String(arg.to_string())),
646 },
647 };
648
649 Ok(arg)
650 }
651
652 fn verbose(&self) -> u32 {
653 self._count("verbose")
654 }
655
656 fn dry_run(&self) -> bool {
657 self.flag("dry-run")
658 }
659
660 fn keep_going(&self) -> bool {
661 self.maybe_flag("keep-going")
662 }
663
664 fn honor_rust_version(&self) -> Option<bool> {
665 self.flag("ignore-rust-version").then_some(false)
666 }
667
668 fn targets(&self) -> CargoResult<Vec<String>> {
669 if self.is_present_with_zero_values("target") {
670 let cmd = if is_rustup() {
671 "rustup target list"
672 } else {
673 "rustc --print target-list"
674 };
675 bail!(
676 "\"--target\" takes a target architecture as an argument.
677
678Run `{cmd}` to see possible targets."
679 );
680 }
681 Ok(self._values_of("target"))
682 }
683
684 fn get_profile_name(
685 &self,
686 default: &str,
687 profile_checking: ProfileChecking,
688 ) -> CargoResult<InternedString> {
689 let specified_profile = self._value_of("profile");
690
691 match (specified_profile, profile_checking) {
694 (Some(name @ ("dev" | "test" | "bench" | "check")), ProfileChecking::LegacyRustc)
696 | (Some(name @ "test"), ProfileChecking::LegacyTestOnly) => {
698 return Ok(name.into());
699 }
700 _ => {}
701 }
702
703 let name = match (
704 self.maybe_flag("release"),
705 self.maybe_flag("debug"),
706 specified_profile,
707 ) {
708 (false, false, None) => default,
709 (true, _, None) => "release",
710 (_, true, None) => "dev",
711 (_, _, Some("doc")) => {
717 bail!("profile `doc` is reserved and not allowed to be explicitly specified")
718 }
719 (_, _, Some(name)) => {
720 ProfileName::new(name)?;
721 name
722 }
723 };
724
725 Ok(name.into())
726 }
727
728 fn packages_from_flags(&self) -> CargoResult<Packages> {
729 Packages::from_flags(
730 self.flag("workspace") || self.flag("all"),
732 self._values_of("exclude"),
733 self._values_of("package"),
734 )
735 }
736
737 fn compile_options(
738 &self,
739 gctx: &GlobalContext,
740 intent: UserIntent,
741 workspace: Option<&Workspace<'_>>,
742 profile_checking: ProfileChecking,
743 ) -> CargoResult<CompileOptions> {
744 let spec = self.packages_from_flags()?;
745 let mut message_format = None;
746 let default_json = MessageFormat::Json {
747 short: false,
748 ansi: false,
749 render_diagnostics: false,
750 };
751 let two_kinds_of_msg_format_err = "cannot specify two kinds of `message-format` arguments";
752 for fmt in self._values_of("message-format") {
753 for fmt in fmt.split(',') {
754 let fmt = fmt.to_ascii_lowercase();
755 match fmt.as_str() {
756 "json" => {
757 if message_format.is_some() {
758 bail!(two_kinds_of_msg_format_err);
759 }
760 message_format = Some(default_json);
761 }
762 "human" => {
763 if message_format.is_some() {
764 bail!(two_kinds_of_msg_format_err);
765 }
766 message_format = Some(MessageFormat::Human);
767 }
768 "short" => {
769 if message_format.is_some() {
770 bail!(two_kinds_of_msg_format_err);
771 }
772 message_format = Some(MessageFormat::Short);
773 }
774 "json-render-diagnostics" => {
775 if message_format.is_none() {
776 message_format = Some(default_json);
777 }
778 match &mut message_format {
779 Some(MessageFormat::Json {
780 render_diagnostics, ..
781 }) => *render_diagnostics = true,
782 _ => bail!(two_kinds_of_msg_format_err),
783 }
784 }
785 "json-diagnostic-short" => {
786 if message_format.is_none() {
787 message_format = Some(default_json);
788 }
789 match &mut message_format {
790 Some(MessageFormat::Json { short, .. }) => *short = true,
791 _ => bail!(two_kinds_of_msg_format_err),
792 }
793 }
794 "json-diagnostic-rendered-ansi" => {
795 if message_format.is_none() {
796 message_format = Some(default_json);
797 }
798 match &mut message_format {
799 Some(MessageFormat::Json { ansi, .. }) => *ansi = true,
800 _ => bail!(two_kinds_of_msg_format_err),
801 }
802 }
803 s => bail!("invalid message format specifier: `{}`", s),
804 }
805 }
806 }
807
808 let mut build_config = BuildConfig::new(
809 gctx,
810 self.jobs()?,
811 self.keep_going(),
812 &self.targets()?,
813 intent,
814 )?;
815 build_config.message_format = message_format.unwrap_or(MessageFormat::Human);
816 build_config.requested_profile = self.get_profile_name("dev", profile_checking)?;
817 build_config.unit_graph = self.flag("unit-graph");
818 build_config.future_incompat_report = self.flag("future-incompat-report");
819 build_config.compile_time_deps_only = self.flag("compile-time-deps");
820 build_config.timing_report = self.flag("timings");
821
822 if build_config.unit_graph {
823 gctx.cli_unstable()
824 .fail_if_stable_opt("--unit-graph", 8002)?;
825 }
826 if build_config.compile_time_deps_only {
827 gctx.cli_unstable()
828 .fail_if_stable_opt("--compile-time-deps", 14434)?;
829 }
830
831 let opts = CompileOptions {
832 build_config,
833 cli_features: self.cli_features()?,
834 spec,
835 filter: CompileFilter::from_raw_arguments(
836 self.flag("lib"),
837 self._values_of("bin"),
838 self.flag("bins"),
839 self._values_of("test"),
840 self.flag("tests"),
841 self._values_of("example"),
842 self.flag("examples"),
843 self._values_of("bench"),
844 self.flag("benches"),
845 self.flag("all-targets"),
846 ),
847 target_rustdoc_args: None,
848 target_rustc_args: None,
849 target_rustc_crate_types: None,
850 rustdoc_document_private_items: false,
851 honor_rust_version: self.honor_rust_version(),
852 };
853
854 if let Some(ws) = workspace {
855 self.check_optional_opts(ws, &opts)?;
856 } else if self.is_present_with_zero_values("package") {
857 anyhow::bail!(
860 "\"--package <SPEC>\" requires a SPEC format value, \
861 which can be any package ID specifier in the dependency graph.\n\
862 Run `cargo help pkgid` for more information about SPEC format."
863 )
864 }
865
866 Ok(opts)
867 }
868
869 fn cli_features(&self) -> CargoResult<CliFeatures> {
870 CliFeatures::from_command_line(
871 &self._values_of("features"),
872 self.flag("all-features"),
873 !self.flag("no-default-features"),
874 )
875 }
876
877 fn compile_options_for_single_package(
878 &self,
879 gctx: &GlobalContext,
880 intent: UserIntent,
881 workspace: Option<&Workspace<'_>>,
882 profile_checking: ProfileChecking,
883 ) -> CargoResult<CompileOptions> {
884 let mut compile_opts = self.compile_options(gctx, intent, workspace, profile_checking)?;
885 let spec = self._values_of("package");
886 if spec.iter().any(restricted_names::is_glob_pattern) {
887 anyhow::bail!("glob patterns on package selection are not supported.")
888 }
889 compile_opts.spec = Packages::Packages(spec);
890 Ok(compile_opts)
891 }
892
893 fn new_options(&self, gctx: &GlobalContext) -> CargoResult<NewOptions> {
894 let vcs = self._value_of("vcs").map(|vcs| match vcs {
895 "git" => VersionControl::Git,
896 "hg" => VersionControl::Hg,
897 "pijul" => VersionControl::Pijul,
898 "fossil" => VersionControl::Fossil,
899 "none" => VersionControl::NoVcs,
900 vcs => panic!("Impossible vcs: {:?}", vcs),
901 });
902 NewOptions::new(
903 vcs,
904 self.flag("bin"),
905 self.flag("lib"),
906 self.value_of_path("path", gctx).unwrap(),
907 self._value_of("name").map(|s| s.to_string()),
908 self._value_of("edition").map(|s| s.to_string()),
909 self.registry(gctx)?,
910 )
911 }
912
913 fn registry_or_index(&self, gctx: &GlobalContext) -> CargoResult<Option<RegistryOrIndex>> {
914 let registry = self._value_of("registry");
915 let index = self._value_of("index");
916 let result = match (registry, index) {
917 (None, None) => gctx.default_registry()?.map(RegistryOrIndex::Registry),
918 (None, Some(i)) => Some(RegistryOrIndex::Index(i.into_url()?)),
919 (Some(r), None) => {
920 RegistryName::new(r)?;
921 Some(RegistryOrIndex::Registry(r.to_string()))
922 }
923 (Some(_), Some(_)) => {
924 unreachable!("both `--index` and `--registry` should not be set at the same time")
926 }
927 };
928 Ok(result)
929 }
930
931 fn registry(&self, gctx: &GlobalContext) -> CargoResult<Option<String>> {
932 match self._value_of("registry").map(|s| s.to_string()) {
933 None => gctx.default_registry(),
934 Some(registry) => {
935 RegistryName::new(®istry)?;
936 Ok(Some(registry))
937 }
938 }
939 }
940
941 fn check_optional_opts(
942 &self,
943 workspace: &Workspace<'_>,
944 compile_opts: &CompileOptions,
945 ) -> CargoResult<()> {
946 if self.is_present_with_zero_values("package") {
947 print_available_packages(workspace)?
948 }
949
950 if self.is_present_with_zero_values("example") {
951 print_available_examples(workspace, compile_opts)?;
952 }
953
954 if self.is_present_with_zero_values("bin") {
955 print_available_binaries(workspace, compile_opts)?;
956 }
957
958 if self.is_present_with_zero_values("bench") {
959 print_available_benches(workspace, compile_opts)?;
960 }
961
962 if self.is_present_with_zero_values("test") {
963 print_available_tests(workspace, compile_opts)?;
964 }
965
966 Ok(())
967 }
968
969 fn is_present_with_zero_values(&self, name: &str) -> bool {
970 self._contains(name) && self._value_of(name).is_none()
971 }
972
973 fn flag(&self, name: &str) -> bool;
974
975 fn maybe_flag(&self, name: &str) -> bool;
976
977 fn _value_of(&self, name: &str) -> Option<&str>;
978
979 fn _values_of(&self, name: &str) -> Vec<String>;
980
981 fn _value_of_os(&self, name: &str) -> Option<&OsStr>;
982
983 fn _values_of_os(&self, name: &str) -> Vec<OsString>;
984
985 fn _count(&self, name: &str) -> u32;
986
987 fn _contains(&self, name: &str) -> bool;
988}
989
990impl<'a> ArgMatchesExt for ArgMatches {
991 fn flag(&self, name: &str) -> bool {
992 ignore_unknown(self.try_get_one::<bool>(name))
993 .copied()
994 .unwrap_or(false)
995 }
996
997 fn maybe_flag(&self, name: &str) -> bool {
1001 self.try_get_one::<bool>(name)
1002 .ok()
1003 .flatten()
1004 .copied()
1005 .unwrap_or_default()
1006 }
1007
1008 fn _value_of(&self, name: &str) -> Option<&str> {
1009 ignore_unknown(self.try_get_one::<String>(name)).map(String::as_str)
1010 }
1011
1012 fn _value_of_os(&self, name: &str) -> Option<&OsStr> {
1013 ignore_unknown(self.try_get_one::<OsString>(name)).map(OsString::as_os_str)
1014 }
1015
1016 fn _values_of(&self, name: &str) -> Vec<String> {
1017 ignore_unknown(self.try_get_many::<String>(name))
1018 .unwrap_or_default()
1019 .cloned()
1020 .collect()
1021 }
1022
1023 fn _values_of_os(&self, name: &str) -> Vec<OsString> {
1024 ignore_unknown(self.try_get_many::<OsString>(name))
1025 .unwrap_or_default()
1026 .cloned()
1027 .collect()
1028 }
1029
1030 fn _count(&self, name: &str) -> u32 {
1031 *ignore_unknown(self.try_get_one::<u8>(name)).expect("defaulted by clap") as u32
1032 }
1033
1034 fn _contains(&self, name: &str) -> bool {
1035 ignore_unknown(self.try_contains_id(name))
1036 }
1037}
1038
1039pub fn values(args: &ArgMatches, name: &str) -> Vec<String> {
1040 args._values_of(name)
1041}
1042
1043pub fn values_os(args: &ArgMatches, name: &str) -> Vec<OsString> {
1044 args._values_of_os(name)
1045}
1046
1047pub fn root_manifest(manifest_path: Option<&Path>, gctx: &GlobalContext) -> CargoResult<PathBuf> {
1048 if let Some(manifest_path) = manifest_path {
1049 let path = gctx.cwd().join(manifest_path);
1050 let path = paths::normalize_path(&path);
1053 if !path.exists() {
1054 anyhow::bail!("manifest path `{}` does not exist", manifest_path.display())
1055 } else if path.is_dir() {
1056 let child_path = path.join("Cargo.toml");
1057 let suggested_path = if child_path.exists() {
1058 format!("\nhelp: {} exists", child_path.display())
1059 } else {
1060 "".to_string()
1061 };
1062 anyhow::bail!(
1063 "manifest path `{}` is a directory but expected a file{suggested_path}",
1064 manifest_path.display()
1065 )
1066 } else if !path.ends_with("Cargo.toml") && !crate::util::toml::is_embedded(&path) {
1067 if gctx.cli_unstable().script {
1068 anyhow::bail!(
1069 "the manifest-path must be a path to a Cargo.toml or script file: `{}`",
1070 path.display()
1071 )
1072 } else {
1073 anyhow::bail!(
1074 "the manifest-path must be a path to a Cargo.toml file: `{}`",
1075 path.display()
1076 )
1077 }
1078 }
1079 if crate::util::toml::is_embedded(&path) && !gctx.cli_unstable().script {
1080 anyhow::bail!("embedded manifest `{}` requires `-Zscript`", path.display())
1081 }
1082 Ok(path)
1083 } else {
1084 find_root_manifest_for_wd(gctx.cwd())
1085 }
1086}
1087
1088pub fn get_registry_candidates() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1089 let gctx = new_gctx_for_completions()?;
1090
1091 if let Ok(Some(registries)) =
1092 gctx.get::<Option<HashMap<String, HashMap<String, String>>>>("registries")
1093 {
1094 Ok(registries
1095 .keys()
1096 .map(|name| clap_complete::CompletionCandidate::new(name.to_owned()))
1097 .collect())
1098 } else {
1099 Ok(vec![])
1100 }
1101}
1102
1103fn get_profile_candidates() -> Vec<clap_complete::CompletionCandidate> {
1104 match get_workspace_profile_candidates() {
1105 Ok(candidates) if !candidates.is_empty() => candidates,
1106 _ => default_profile_candidates(),
1108 }
1109}
1110
1111fn get_workspace_profile_candidates() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1112 let gctx = new_gctx_for_completions()?;
1113 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1114 let profiles = Profiles::new(&ws, "dev".into())?;
1115
1116 let mut candidates = Vec::new();
1117 for name in profiles.profile_names() {
1118 let Ok(profile_instance) = Profiles::new(&ws, name) else {
1119 continue;
1120 };
1121 let base_profile = profile_instance.base_profile();
1122
1123 let mut description = String::from(if base_profile.opt_level.as_str() == "0" {
1124 "unoptimized"
1125 } else {
1126 "optimized"
1127 });
1128
1129 if base_profile.debuginfo.is_turned_on() {
1130 description.push_str(" + debuginfo");
1131 }
1132
1133 candidates
1134 .push(clap_complete::CompletionCandidate::new(&name).help(Some(description.into())));
1135 }
1136
1137 Ok(candidates)
1138}
1139
1140fn default_profile_candidates() -> Vec<clap_complete::CompletionCandidate> {
1141 vec![
1142 clap_complete::CompletionCandidate::new("dev").help(Some("unoptimized + debuginfo".into())),
1143 clap_complete::CompletionCandidate::new("release").help(Some("optimized".into())),
1144 clap_complete::CompletionCandidate::new("test")
1145 .help(Some("unoptimized + debuginfo".into())),
1146 clap_complete::CompletionCandidate::new("bench").help(Some("optimized".into())),
1147 ]
1148}
1149
1150fn get_feature_candidates() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1151 let gctx = new_gctx_for_completions()?;
1152
1153 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1154 let mut feature_candidates = Vec::new();
1155
1156 for package in ws.members() {
1158 let package_name = package.name();
1159
1160 for feature_name in package.summary().features().keys() {
1162 let order = if ws.current_opt().map(|p| p.name()) == Some(package_name) {
1163 0
1164 } else {
1165 1
1166 };
1167 feature_candidates.push(
1168 clap_complete::CompletionCandidate::new(feature_name)
1169 .display_order(Some(order))
1170 .help(Some(format!("from {}", package_name).into())),
1171 );
1172 }
1173 }
1174
1175 Ok(feature_candidates)
1176}
1177
1178fn get_crate_candidates(kind: TargetKind) -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1179 let gctx = new_gctx_for_completions()?;
1180
1181 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1182
1183 let targets = ws
1184 .members()
1185 .flat_map(|pkg| pkg.targets().into_iter().cloned().map(|t| (pkg.name(), t)))
1186 .filter(|(_, target)| *target.kind() == kind)
1187 .map(|(pkg_name, target)| {
1188 let order = if ws.current_opt().map(|p| p.name()) == Some(pkg_name) {
1189 0
1190 } else {
1191 1
1192 };
1193 clap_complete::CompletionCandidate::new(target.name())
1194 .display_order(Some(order))
1195 .help(Some(format!("from {}", pkg_name).into()))
1196 })
1197 .collect::<Vec<_>>();
1198
1199 Ok(targets)
1200}
1201
1202fn get_target_triples() -> Vec<clap_complete::CompletionCandidate> {
1203 let mut candidates = Vec::new();
1204
1205 if let Ok(targets) = get_target_triples_from_rustup() {
1206 candidates = targets;
1207 }
1208
1209 if candidates.is_empty() {
1210 if let Ok(targets) = get_target_triples_from_rustc() {
1211 candidates = targets;
1212 }
1213 }
1214
1215 candidates.insert(
1217 0,
1218 clap_complete::CompletionCandidate::new("host-tuple").help(Some(
1219 concat!("alias for: ", env!("RUST_HOST_TARGET")).into(),
1220 )),
1221 );
1222
1223 candidates
1224}
1225
1226pub fn get_target_triples_with_all() -> Vec<clap_complete::CompletionCandidate> {
1227 let mut candidates = vec![
1228 clap_complete::CompletionCandidate::new("all").help(Some("Include all targets".into())),
1229 ];
1230 candidates.extend(get_target_triples());
1231 candidates
1232}
1233
1234fn get_target_triples_from_rustup() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1235 let output = std::process::Command::new("rustup")
1236 .arg("target")
1237 .arg("list")
1238 .output()?;
1239
1240 if !output.status.success() {
1241 return Ok(vec![]);
1242 }
1243
1244 let stdout = String::from_utf8(output.stdout)?;
1245
1246 Ok(stdout
1247 .lines()
1248 .map(|line| {
1249 let target = line.split_once(' ');
1250 match target {
1251 None => clap_complete::CompletionCandidate::new(line.to_owned()).hide(true),
1252 Some((target, _installed)) => clap_complete::CompletionCandidate::new(target),
1253 }
1254 })
1255 .collect())
1256}
1257
1258fn get_target_triples_from_rustc() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1259 let gctx = new_gctx_for_completions()?;
1260
1261 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx);
1262
1263 let rustc = gctx.load_global_rustc(ws.as_ref().ok())?;
1264
1265 let (stdout, _stderr) =
1266 rustc.cached_output(rustc.process().arg("--print").arg("target-list"), 0)?;
1267
1268 Ok(stdout
1269 .lines()
1270 .map(|line| clap_complete::CompletionCandidate::new(line.to_owned()))
1271 .collect())
1272}
1273
1274pub fn get_ws_member_candidates() -> Vec<clap_complete::CompletionCandidate> {
1275 get_ws_member_packages()
1276 .unwrap_or_default()
1277 .into_iter()
1278 .map(|pkg| {
1279 clap_complete::CompletionCandidate::new(pkg.name().as_str()).help(
1280 pkg.manifest()
1281 .metadata()
1282 .description
1283 .to_owned()
1284 .map(From::from),
1285 )
1286 })
1287 .collect::<Vec<_>>()
1288}
1289
1290fn get_ws_member_packages() -> CargoResult<Vec<Package>> {
1291 let gctx = new_gctx_for_completions()?;
1292 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1293 let packages = ws.members().map(Clone::clone).collect::<Vec<_>>();
1294 Ok(packages)
1295}
1296
1297pub fn get_pkg_id_spec_candidates() -> Vec<clap_complete::CompletionCandidate> {
1298 let mut candidates = vec![];
1299
1300 let package_map = HashMap::<&str, Vec<Package>>::new();
1301 let package_map =
1302 get_packages()
1303 .unwrap_or_default()
1304 .into_iter()
1305 .fold(package_map, |mut map, package| {
1306 map.entry(package.name().as_str())
1307 .or_insert_with(Vec::new)
1308 .push(package);
1309 map
1310 });
1311
1312 let unique_name_candidates = package_map
1313 .iter()
1314 .filter(|(_name, packages)| packages.len() == 1)
1315 .map(|(name, packages)| {
1316 clap_complete::CompletionCandidate::new(name.to_string()).help(
1317 packages[0]
1318 .manifest()
1319 .metadata()
1320 .description
1321 .to_owned()
1322 .map(From::from),
1323 )
1324 })
1325 .collect::<Vec<_>>();
1326
1327 let duplicate_name_pairs = package_map
1328 .iter()
1329 .filter(|(_name, packages)| packages.len() > 1)
1330 .collect::<Vec<_>>();
1331
1332 let mut duplicate_name_candidates = vec![];
1333 for (name, packages) in duplicate_name_pairs {
1334 let mut version_count: HashMap<&Version, usize> = HashMap::new();
1335
1336 for package in packages {
1337 *version_count.entry(package.version()).or_insert(0) += 1;
1338 }
1339
1340 for package in packages {
1341 if let Some(&count) = version_count.get(package.version()) {
1342 if count == 1 {
1343 duplicate_name_candidates.push(
1344 clap_complete::CompletionCandidate::new(format!(
1345 "{}@{}",
1346 name,
1347 package.version()
1348 ))
1349 .help(
1350 package
1351 .manifest()
1352 .metadata()
1353 .description
1354 .to_owned()
1355 .map(From::from),
1356 ),
1357 );
1358 } else {
1359 duplicate_name_candidates.push(
1360 clap_complete::CompletionCandidate::new(format!(
1361 "{}",
1362 package.package_id().to_spec()
1363 ))
1364 .help(
1365 package
1366 .manifest()
1367 .metadata()
1368 .description
1369 .to_owned()
1370 .map(From::from),
1371 ),
1372 )
1373 }
1374 }
1375 }
1376 }
1377
1378 candidates.extend(unique_name_candidates);
1379 candidates.extend(duplicate_name_candidates);
1380
1381 candidates
1382}
1383
1384pub fn get_pkg_name_candidates() -> Vec<clap_complete::CompletionCandidate> {
1385 let packages: BTreeMap<_, _> = get_packages()
1386 .unwrap_or_default()
1387 .into_iter()
1388 .map(|package| {
1389 (
1390 package.name(),
1391 package.manifest().metadata().description.clone(),
1392 )
1393 })
1394 .collect();
1395
1396 packages
1397 .into_iter()
1398 .map(|(name, description)| {
1399 clap_complete::CompletionCandidate::new(name.as_str()).help(description.map(From::from))
1400 })
1401 .collect()
1402}
1403
1404fn get_packages() -> CargoResult<Vec<Package>> {
1405 let gctx = new_gctx_for_completions()?;
1406
1407 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1408
1409 let requested_kinds = CompileKind::from_requested_targets(ws.gctx(), &[])?;
1410 let mut target_data = RustcTargetData::new(&ws, &requested_kinds)?;
1411 let cli_features = CliFeatures::new_all(true);
1413 let has_dev_units = HasDevUnits::Yes;
1414 let force_all_targets = ForceAllTargets::No;
1415 let dry_run = true;
1416
1417 let ws_resolve = ops::resolve_ws_with_opts(
1418 &ws,
1419 &mut target_data,
1420 &requested_kinds,
1421 &cli_features,
1422 &[],
1423 has_dev_units,
1424 force_all_targets,
1425 dry_run,
1426 )?;
1427
1428 let packages = ws_resolve
1429 .pkg_set
1430 .packages()
1431 .map(Clone::clone)
1432 .collect::<Vec<_>>();
1433
1434 Ok(packages)
1435}
1436
1437pub fn get_direct_dependencies_pkg_name_candidates() -> Vec<clap_complete::CompletionCandidate> {
1438 let (current_package_deps, all_package_deps) = match get_dependencies_from_metadata() {
1439 Ok(v) => v,
1440 Err(_) => return Vec::new(),
1441 };
1442
1443 let current_package_deps_package_names = current_package_deps
1444 .into_iter()
1445 .map(|dep| dep.package_name().to_string())
1446 .sorted();
1447 let all_package_deps_package_names = all_package_deps
1448 .into_iter()
1449 .map(|dep| dep.package_name().to_string())
1450 .sorted();
1451
1452 let mut package_names_set = IndexSet::new();
1453 package_names_set.extend(current_package_deps_package_names);
1454 package_names_set.extend(all_package_deps_package_names);
1455
1456 package_names_set
1457 .into_iter()
1458 .map(|name| name.into())
1459 .collect_vec()
1460}
1461
1462fn get_dependencies_from_metadata() -> CargoResult<(Vec<Dependency>, Vec<Dependency>)> {
1463 let cwd = std::env::current_dir()?;
1464 let gctx = GlobalContext::new(shell::Shell::new(), cwd.clone(), cargo_home_with_cwd(&cwd)?);
1465 let ws = Workspace::new(&find_root_manifest_for_wd(&cwd)?, &gctx)?;
1466 let current_package = ws.current().ok();
1467
1468 let current_package_dependencies = ws
1469 .current()
1470 .map(|current| current.dependencies())
1471 .unwrap_or_default()
1472 .to_vec();
1473 let all_other_packages_dependencies = ws
1474 .members()
1475 .filter(|&member| Some(member) != current_package)
1476 .flat_map(|pkg| pkg.dependencies().into_iter().cloned())
1477 .collect::<HashSet<_>>()
1478 .into_iter()
1479 .collect::<Vec<_>>();
1480
1481 Ok((
1482 current_package_dependencies,
1483 all_other_packages_dependencies,
1484 ))
1485}
1486
1487pub fn new_gctx_for_completions() -> CargoResult<GlobalContext> {
1488 let cwd = std::env::current_dir()?;
1489 let mut gctx = GlobalContext::new(shell::Shell::new(), cwd.clone(), cargo_home_with_cwd(&cwd)?);
1490
1491 let verbose = 0;
1492 let quiet = true;
1493 let color = None;
1494 let frozen = false;
1495 let locked = true;
1496 let offline = false;
1497 let target_dir = None;
1498 let unstable_flags = &[];
1499 let cli_config = &[];
1500
1501 gctx.configure(
1502 verbose,
1503 quiet,
1504 color,
1505 frozen,
1506 locked,
1507 offline,
1508 &target_dir,
1509 unstable_flags,
1510 cli_config,
1511 )?;
1512
1513 Ok(gctx)
1514}
1515
1516#[track_caller]
1517pub fn ignore_unknown<T: Default>(r: Result<T, clap::parser::MatchesError>) -> T {
1518 match r {
1519 Ok(t) => t,
1520 Err(clap::parser::MatchesError::UnknownArgument { .. }) => Default::default(),
1521 Err(e) => {
1522 panic!("Mismatch between definition and access: {}", e);
1523 }
1524 }
1525}
1526
1527#[derive(PartialEq, Eq, PartialOrd, Ord)]
1528pub enum CommandInfo {
1529 BuiltIn { about: Option<String> },
1530 External { path: PathBuf },
1531 Alias { target: StringOrVec },
1532}