1use crate::CargoResult;
2use crate::compiler::{BuildConfig, CompileKind, MessageFormat, RustcTargetData};
3use crate::context::VersionControl;
4use crate::ops::registry::RegistryOrIndex;
5use crate::ops::{self, CompileFilter, CompileOptions, NewOptions, Packages};
6use crate::resolver::{CliFeatures, ForceAllTargets, HasDevUnits};
7use crate::util::important_paths::find_root_manifest_for_wd;
8use crate::util::interning::InternedString;
9use crate::util::is_rustup;
10use crate::util::{
11 print_available_benches, print_available_binaries, print_available_examples,
12 print_available_packages, print_available_tests,
13};
14use crate::workspace::Dependency;
15use crate::workspace::parser::is_embedded;
16use crate::workspace::{Edition, Package, TargetKind, Workspace, profiles::Profiles};
17use anyhow::bail;
18use cargo_util::collections::{HashMap, HashSet};
19use cargo_util::collections::{IndexMap, IndexSet};
20use cargo_util::paths;
21use cargo_util_schemas::manifest::ProfileName;
22use cargo_util_schemas::manifest::RegistryName;
23use cargo_util_terminal::report::Level;
24use clap::builder::PossibleValuesParser;
25use clap::builder::UnknownArgumentValueParser;
26use clap_complete::ArgValueCandidates;
27use itertools::Itertools;
28use semver::Version;
29use std::collections::BTreeMap;
30use std::ffi::{OsStr, OsString};
31use std::path::Path;
32use std::path::PathBuf;
33
34pub use crate::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 crate::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_targets_all(
157 self,
158 lib: &'static str,
159 bin: &'static str,
160 bins: &'static str,
161 example: &'static str,
162 examples: &'static str,
163 test: &'static str,
164 tests: &'static str,
165 bench: &'static str,
166 benches: &'static str,
167 all: &'static str,
168 ) -> Self {
169 self.arg_targets_lib_bin_example(lib, bin, bins, example, examples)
170 ._arg(flag("tests", tests).help_heading(heading::TARGET_SELECTION))
171 ._arg(
172 optional_multi_opt("test", "NAME", test)
173 .help_heading(heading::TARGET_SELECTION)
174 .add(clap_complete::ArgValueCandidates::new(|| {
175 get_crate_candidates(TargetKind::Test).unwrap_or_default()
176 })),
177 )
178 ._arg(flag("benches", benches).help_heading(heading::TARGET_SELECTION))
179 ._arg(
180 optional_multi_opt("bench", "NAME", bench)
181 .help_heading(heading::TARGET_SELECTION)
182 .add(clap_complete::ArgValueCandidates::new(|| {
183 get_crate_candidates(TargetKind::Bench).unwrap_or_default()
184 })),
185 )
186 ._arg(flag("all-targets", all).help_heading(heading::TARGET_SELECTION))
187 }
188
189 fn arg_targets_lib_bin_example(
190 self,
191 lib: &'static str,
192 bin: &'static str,
193 bins: &'static str,
194 example: &'static str,
195 examples: &'static str,
196 ) -> Self {
197 self._arg(flag("lib", lib).help_heading(heading::TARGET_SELECTION))
198 ._arg(flag("bins", bins).help_heading(heading::TARGET_SELECTION))
199 ._arg(
200 optional_multi_opt("bin", "NAME", bin)
201 .help_heading(heading::TARGET_SELECTION)
202 .add(clap_complete::ArgValueCandidates::new(|| {
203 get_crate_candidates(TargetKind::Bin).unwrap_or_default()
204 })),
205 )
206 ._arg(flag("examples", examples).help_heading(heading::TARGET_SELECTION))
207 ._arg(
208 optional_multi_opt("example", "NAME", example)
209 .help_heading(heading::TARGET_SELECTION)
210 .add(clap_complete::ArgValueCandidates::new(|| {
211 get_crate_candidates(TargetKind::ExampleBin).unwrap_or_default()
212 })),
213 )
214 }
215
216 fn arg_targets_bins_examples(
217 self,
218 bin: &'static str,
219 bins: &'static str,
220 example: &'static str,
221 examples: &'static str,
222 ) -> Self {
223 self._arg(
224 optional_multi_opt("bin", "NAME", bin)
225 .help_heading(heading::TARGET_SELECTION)
226 .add(clap_complete::ArgValueCandidates::new(|| {
227 get_crate_candidates(TargetKind::Bin).unwrap_or_default()
228 })),
229 )
230 ._arg(flag("bins", bins).help_heading(heading::TARGET_SELECTION))
231 ._arg(
232 optional_multi_opt("example", "NAME", example)
233 .help_heading(heading::TARGET_SELECTION)
234 .add(clap_complete::ArgValueCandidates::new(|| {
235 get_crate_candidates(TargetKind::ExampleBin).unwrap_or_default()
236 })),
237 )
238 ._arg(flag("examples", examples).help_heading(heading::TARGET_SELECTION))
239 }
240
241 fn arg_targets_bin_example(self, bin: &'static str, example: &'static str) -> Self {
242 self._arg(
243 optional_multi_opt("bin", "NAME", bin)
244 .help_heading(heading::TARGET_SELECTION)
245 .add(clap_complete::ArgValueCandidates::new(|| {
246 get_crate_candidates(TargetKind::Bin).unwrap_or_default()
247 })),
248 )
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 }
257
258 fn arg_features(self) -> Self {
259 self._arg(
260 multi_opt(
261 "features",
262 "FEATURES",
263 "Space or comma separated list of features to activate",
264 )
265 .short('F')
266 .help_heading(heading::FEATURE_SELECTION)
267 .add(clap_complete::ArgValueCandidates::new(|| {
268 get_feature_candidates().unwrap_or_default()
269 })),
270 )
271 ._arg(
272 flag("all-features", "Activate all available features")
273 .help_heading(heading::FEATURE_SELECTION),
274 )
275 ._arg(
276 flag(
277 "no-default-features",
278 "Do not activate the `default` feature",
279 )
280 .help_heading(heading::FEATURE_SELECTION),
281 )
282 }
283
284 fn arg_release(self, release: &'static str) -> Self {
285 self._arg(
286 flag("release", release)
287 .short('r')
288 .conflicts_with("profile")
289 .help_heading(heading::COMPILATION_OPTIONS),
290 )
291 }
292
293 fn arg_debug(self, command: &'static str) -> Self {
294 let msg =
295 format!("to enable the debug profile for `cargo {command}`, pass `--profile debug`");
296 let value_parser = UnknownArgumentValueParser::suggest(msg);
297 self._arg(
298 flag("debug", "")
299 .conflicts_with("profile")
300 .value_parser(value_parser)
301 .hide(true),
302 )
303 }
304
305 fn arg_profile(self, profile: &'static str) -> Self {
306 self._arg(
307 opt("profile", profile)
308 .value_name("PROFILE-NAME")
309 .help_heading(heading::COMPILATION_OPTIONS)
310 .add(clap_complete::ArgValueCandidates::new(|| {
311 let candidates = get_profile_candidates();
312 candidates
313 })),
314 )
315 }
316
317 fn arg_doc(self, doc: &'static str) -> Self {
318 self._arg(flag("doc", doc))
319 }
320
321 fn arg_target_tuple(self, target: &'static str) -> Self {
322 self.arg_target_tuple_with_candidates(target, ArgValueCandidates::new(get_target_tuples))
323 }
324
325 fn arg_target_tuple_with_candidates(
326 self,
327 target: &'static str,
328 target_completion: ArgValueCandidates,
329 ) -> Self {
330 let unsupported_short_arg = {
331 let value_parser = UnknownArgumentValueParser::suggest_arg("--target");
332 Arg::new("unsupported-short-target-flag")
333 .help("")
334 .short('t')
335 .value_parser(value_parser)
336 .action(ArgAction::SetTrue)
337 .hide(true)
338 };
339 self._arg(
340 optional_multi_opt("target", "TUPLE", target)
341 .help_heading(heading::COMPILATION_OPTIONS)
342 .add(target_completion),
343 )
344 ._arg(unsupported_short_arg)
345 }
346
347 fn arg_target_dir(self) -> Self {
348 self._arg(
349 opt("target-dir", "Directory for all generated artifacts")
350 .value_name("DIRECTORY")
351 .help_heading(heading::COMPILATION_OPTIONS),
352 )
353 }
354
355 fn arg_manifest_path(self) -> Self {
356 let unsupported_path_arg = {
358 let value_parser = UnknownArgumentValueParser::suggest_arg("--manifest-path");
359 flag("unsupported-path-flag", "")
360 .long("path")
361 .value_parser(value_parser)
362 .hide(true)
363 };
364 self.arg_manifest_path_without_unsupported_path_tip()
365 ._arg(unsupported_path_arg)
366 }
367
368 fn arg_manifest_path_without_unsupported_path_tip(self) -> Self {
370 self._arg(
371 opt("manifest-path", "Path to Cargo.toml")
372 .short('m')
373 .value_name("PATH")
374 .help_heading(heading::MANIFEST_OPTIONS)
375 .add(clap_complete::engine::ArgValueCompleter::new(
376 clap_complete::engine::PathCompleter::any().filter(|path: &Path| {
377 if path.file_name() == Some(OsStr::new("Cargo.toml")) {
378 return true;
379 }
380 if is_embedded(path) {
381 return true;
382 }
383 false
384 }),
385 )),
386 )
387 }
388
389 fn arg_message_format(self) -> Self {
390 self._arg(
391 multi_opt("message-format", "FMT", "Error format")
392 .value_parser([
393 "human",
394 "short",
395 "json",
396 "json-diagnostic-short",
397 "json-diagnostic-rendered-ansi",
398 "json-render-diagnostics",
399 ])
400 .value_delimiter(',')
401 .ignore_case(true),
402 )
403 }
404
405 fn arg_unit_graph(self) -> Self {
406 self._arg(
407 flag("unit-graph", "Output build graph in JSON (unstable)")
408 .help_heading(heading::COMPILATION_OPTIONS),
409 )
410 }
411
412 fn arg_new_opts(self) -> Self {
413 self._arg(
414 opt(
415 "vcs",
416 "Initialize a new repository for the given version \
417 control system, overriding \
418 a global configuration.",
419 )
420 .value_name("VCS")
421 .value_parser(PossibleValuesParser::new(
422 VersionControl::VALUES.iter().map(|v| v.as_str()),
423 )),
424 )
425 ._arg(flag("bin", "Use a binary (application) template [default]"))
426 ._arg(flag("lib", "Use a library template"))
427 ._arg(
428 opt("edition", "Edition to set for the crate generated")
429 .value_parser(Edition::CLI_VALUES)
430 .value_name("YEAR"),
431 )
432 ._arg(
433 opt(
434 "name",
435 "Set the resulting package name, defaults to the directory name",
436 )
437 .value_name("NAME"),
438 )
439 }
440
441 fn arg_registry(self, help: &'static str) -> Self {
442 self._arg(opt("registry", help).value_name("REGISTRY").add(
443 clap_complete::ArgValueCandidates::new(|| {
444 let candidates = get_registry_candidates();
445 candidates.unwrap_or_default()
446 }),
447 ))
448 }
449
450 fn arg_index(self, help: &'static str) -> Self {
451 self._arg(
453 opt("index", help)
454 .value_name("INDEX")
455 .conflicts_with("registry"),
456 )
457 }
458
459 fn arg_dry_run(self, dry_run: &'static str) -> Self {
460 self._arg(flag("dry-run", dry_run).short('n'))
461 }
462
463 fn arg_ignore_rust_version(self) -> Self {
464 self.arg_ignore_rust_version_with_help("Ignore `rust-version` specification in packages")
465 }
466
467 fn arg_ignore_rust_version_with_help(self, help: &'static str) -> Self {
468 self._arg(flag("ignore-rust-version", help).help_heading(heading::MANIFEST_OPTIONS))
469 }
470
471 fn arg_future_incompat_report(self) -> Self {
472 self._arg(flag(
473 "future-incompat-report",
474 "Outputs a future incompatibility report at the end of the build",
475 ))
476 }
477
478 fn arg_silent_suggestion(self) -> Self {
484 let value_parser = UnknownArgumentValueParser::suggest_arg("--quiet");
485 self._arg(
486 flag("silent", "")
487 .short('s')
488 .value_parser(value_parser)
489 .hide(true),
490 )
491 }
492
493 fn arg_timings(self) -> Self {
494 self._arg(
495 flag(
496 "timings",
497 "Output a build timing report at the end of the build",
498 )
499 .help_heading(heading::COMPILATION_OPTIONS),
500 )
501 }
502
503 fn arg_artifact_dir(self) -> Self {
504 let unsupported_short_arg = {
505 let value_parser = UnknownArgumentValueParser::suggest_arg("--artifact-dir");
506 Arg::new("unsupported-short-artifact-dir-flag")
507 .help("")
508 .short('O')
509 .value_parser(value_parser)
510 .action(ArgAction::SetTrue)
511 .hide(true)
512 };
513
514 self._arg(
515 opt(
516 "artifact-dir",
517 "Copy final artifacts to this directory (unstable)",
518 )
519 .value_name("PATH")
520 .help_heading(heading::COMPILATION_OPTIONS),
521 )
522 ._arg(unsupported_short_arg)
523 ._arg({
524 let value_parser = UnknownArgumentValueParser::suggest_arg("--artifact-dir");
525 Arg::new("unsupported-out-dir-flag")
526 .help("")
527 .long("out-dir")
528 .value_name("PATH")
529 .value_parser(value_parser)
530 .action(ArgAction::SetTrue)
531 .hide(true)
532 })
533 }
534
535 fn arg_compile_time_deps(self) -> Self {
536 self._arg(flag("compile-time-deps", "").hide(true))
537 }
538}
539
540impl CommandExt for Command {
541 fn _arg(self, arg: Arg) -> Self {
542 self.arg(arg)
543 }
544}
545
546pub fn flag(name: &'static str, help: &'static str) -> Arg {
547 Arg::new(name)
548 .long(name)
549 .help(help)
550 .action(ArgAction::SetTrue)
551}
552
553pub fn opt(name: &'static str, help: &'static str) -> Arg {
554 Arg::new(name).long(name).help(help).action(ArgAction::Set)
555}
556
557pub fn optional_opt(name: &'static str, help: &'static str) -> Arg {
558 opt(name, help).num_args(0..=1)
559}
560
561pub fn optional_multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Arg {
562 opt(name, help)
563 .value_name(value_name)
564 .num_args(0..=1)
565 .action(ArgAction::Append)
566}
567
568pub fn multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Arg {
569 opt(name, help)
570 .value_name(value_name)
571 .action(ArgAction::Append)
572}
573
574pub fn subcommand(name: &'static str) -> Command {
575 Command::new(name)
576}
577
578pub enum ProfileChecking {
580 LegacyRustc,
583 LegacyTestOnly,
586 Custom,
588}
589
590pub trait ArgMatchesExt {
591 fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
592 let arg = match self._value_of(name) {
593 None => None,
594 Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
595 clap::Error::raw(
596 clap::error::ErrorKind::ValueValidation,
597 format!("invalid value: could not parse `{}` as a number", arg),
598 )
599 })?),
600 };
601 Ok(arg)
602 }
603
604 fn value_of_i32(&self, name: &str) -> CargoResult<Option<i32>> {
605 let arg = match self._value_of(name) {
606 None => None,
607 Some(arg) => Some(arg.parse::<i32>().map_err(|_| {
608 clap::Error::raw(
609 clap::error::ErrorKind::ValueValidation,
610 format!("invalid value: could not parse `{}` as a number", arg),
611 )
612 })?),
613 };
614 Ok(arg)
615 }
616
617 fn value_of_path(&self, name: &str, gctx: &GlobalContext) -> Option<PathBuf> {
619 self._value_of(name).map(|path| gctx.cwd().join(path))
620 }
621
622 fn root_manifest(&self, gctx: &GlobalContext) -> CargoResult<PathBuf> {
623 root_manifest(self._value_of("manifest-path").map(Path::new), gctx)
624 }
625
626 #[tracing::instrument(skip_all)]
627 fn workspace<'a>(&self, gctx: &'a GlobalContext) -> CargoResult<Workspace<'a>> {
628 let root = self.root_manifest(gctx)?;
629 let mut ws = Workspace::new(&root, gctx)?;
630 ws.set_resolve_honors_rust_version(self.honor_rust_version());
631 if gctx.cli_unstable().avoid_dev_deps {
632 ws.set_require_optional_deps(false);
633 }
634 Ok(ws)
635 }
636
637 fn jobs(&self) -> CargoResult<Option<JobsConfig>> {
638 let arg = match self._value_of("jobs") {
639 None => None,
640 Some(arg) => match arg.parse::<i32>() {
641 Ok(j) => Some(JobsConfig::Integer(j)),
642 Err(_) => Some(JobsConfig::String(arg.to_string())),
643 },
644 };
645
646 Ok(arg)
647 }
648
649 fn verbose(&self) -> u32 {
650 self._count("verbose")
651 }
652
653 fn dry_run(&self) -> bool {
654 self.flag("dry-run")
655 }
656
657 fn keep_going(&self) -> bool {
658 self.maybe_flag("keep-going")
659 }
660
661 fn honor_rust_version(&self) -> Option<bool> {
662 self.flag("ignore-rust-version").then_some(false)
663 }
664
665 fn targets(&self) -> CargoResult<Vec<String>> {
666 if self.is_present_with_zero_values("target") {
667 let cmd = if is_rustup() {
668 "rustup target list"
669 } else {
670 "rustc --print target-list"
671 };
672 bail!(
673 "\"--target\" takes a target architecture as an argument.
674
675Run `{cmd}` to see possible targets."
676 );
677 }
678 Ok(self._values_of("target"))
679 }
680
681 fn get_profile_name(
682 &self,
683 default: &str,
684 profile_checking: ProfileChecking,
685 ) -> CargoResult<InternedString> {
686 let specified_profile = self._value_of("profile");
687
688 match (specified_profile, profile_checking) {
691 (Some(name @ ("dev" | "test" | "bench" | "check")), ProfileChecking::LegacyRustc)
693 | (Some(name @ "test"), ProfileChecking::LegacyTestOnly) => {
695 return Ok(name.into());
696 }
697 _ => {}
698 }
699
700 let name = match (
701 self.maybe_flag("release"),
702 self.maybe_flag("debug"),
703 specified_profile,
704 ) {
705 (false, false, None) => default,
706 (true, _, None) => "release",
707 (_, true, None) => "debug",
708 (_, _, Some("doc")) => {
714 bail!("profile `doc` is reserved and not allowed to be explicitly specified")
715 }
716 (_, _, Some(name)) => {
717 ProfileName::new(name)?;
718 name
719 }
720 };
721
722 Ok(name.into())
723 }
724
725 fn packages_from_flags(&self) -> CargoResult<Packages> {
726 Packages::from_flags(
727 self.flag("workspace") || self.flag("all"),
729 self._values_of("exclude"),
730 self._values_of("package"),
731 )
732 }
733
734 fn compile_options(
735 &self,
736 gctx: &GlobalContext,
737 intent: UserIntent,
738 workspace: Option<&Workspace<'_>>,
739 profile_checking: ProfileChecking,
740 ) -> CargoResult<CompileOptions> {
741 let spec = self.packages_from_flags()?;
742 let mut message_format = None;
743 let default_json = MessageFormat::Json {
744 short: false,
745 ansi: false,
746 render_diagnostics: false,
747 };
748 let two_kinds_of_msg_format_err = "cannot specify two kinds of `message-format` arguments";
749 for fmt in self._values_of("message-format") {
750 for fmt in fmt.split(',') {
751 let fmt = fmt.to_ascii_lowercase();
752 match fmt.as_str() {
753 "json" => {
754 if message_format.is_some() {
755 bail!(two_kinds_of_msg_format_err);
756 }
757 message_format = Some(default_json);
758 }
759 "human" => {
760 if message_format.is_some() {
761 bail!(two_kinds_of_msg_format_err);
762 }
763 message_format = Some(MessageFormat::Human);
764 }
765 "short" => {
766 if message_format.is_some() {
767 bail!(two_kinds_of_msg_format_err);
768 }
769 message_format = Some(MessageFormat::Short);
770 }
771 "json-render-diagnostics" => {
772 if message_format.is_none() {
773 message_format = Some(default_json);
774 }
775 match &mut message_format {
776 Some(MessageFormat::Json {
777 render_diagnostics, ..
778 }) => *render_diagnostics = true,
779 _ => bail!(two_kinds_of_msg_format_err),
780 }
781 }
782 "json-diagnostic-short" => {
783 if message_format.is_none() {
784 message_format = Some(default_json);
785 }
786 match &mut message_format {
787 Some(MessageFormat::Json { short, .. }) => *short = true,
788 _ => bail!(two_kinds_of_msg_format_err),
789 }
790 }
791 "json-diagnostic-rendered-ansi" => {
792 if message_format.is_none() {
793 message_format = Some(default_json);
794 }
795 match &mut message_format {
796 Some(MessageFormat::Json { ansi, .. }) => *ansi = true,
797 _ => bail!(two_kinds_of_msg_format_err),
798 }
799 }
800 s => bail!("invalid message format specifier: `{}`", s),
801 }
802 }
803 }
804
805 let mut build_config = BuildConfig::new(
806 gctx,
807 self.jobs()?,
808 self.keep_going(),
809 &self.targets()?,
810 intent,
811 )?;
812 build_config.message_format = message_format.unwrap_or(MessageFormat::Human);
813 let default_profile = gctx
814 .build_config()?
815 .profile
816 .as_ref()
817 .map(|p| p.as_ref())
818 .unwrap_or_else(|| "dev");
819 build_config.requested_profile =
820 self.get_profile_name(default_profile, profile_checking)?;
821 build_config.unit_graph = self.flag("unit-graph");
822 build_config.future_incompat_report = self.flag("future-incompat-report");
823 build_config.compile_time_deps_only = self.flag("compile-time-deps");
824 build_config.timing_report = self.flag("timings");
825
826 if build_config.unit_graph {
827 gctx.cli_unstable()
828 .fail_if_stable_opt("--unit-graph", 8002)?;
829 }
830 if build_config.compile_time_deps_only {
831 gctx.cli_unstable()
832 .fail_if_stable_opt("--compile-time-deps", 14434)?;
833 }
834
835 let opts = CompileOptions {
836 build_config,
837 cli_features: self.cli_features()?,
838 spec,
839 filter: CompileFilter::from_raw_arguments(
840 self.flag("lib"),
841 self._values_of("bin"),
842 self.flag("bins"),
843 self._values_of("test"),
844 self.flag("tests"),
845 self._values_of("example"),
846 self.flag("examples"),
847 self._values_of("bench"),
848 self.flag("benches"),
849 self.flag("all-targets"),
850 ),
851 target_rustdoc_args: None,
852 target_rustc_args: None,
853 target_rustc_crate_types: None,
854 rustdoc_document_private_items: false,
855 honor_rust_version: self.honor_rust_version(),
856 };
857
858 if let Some(ws) = workspace {
859 self.check_optional_opts(ws, &opts)?;
860 } else if self.is_present_with_zero_values("package") {
861 anyhow::bail!(
864 "\"--package <SPEC>\" requires a SPEC format value, \
865 which can be any package ID specifier in the dependency graph.\n\
866 Run `cargo help pkgid` for more information about SPEC format."
867 )
868 }
869
870 Ok(opts)
871 }
872
873 fn cli_features(&self) -> CargoResult<CliFeatures> {
874 CliFeatures::from_command_line(
875 &self._values_of("features"),
876 self.flag("all-features"),
877 !self.flag("no-default-features"),
878 )
879 }
880
881 fn compile_options_for_single_package(
882 &self,
883 gctx: &GlobalContext,
884 intent: UserIntent,
885 workspace: Option<&Workspace<'_>>,
886 profile_checking: ProfileChecking,
887 ) -> CargoResult<CompileOptions> {
888 let mut compile_opts = self.compile_options(gctx, intent, workspace, profile_checking)?;
889 let spec = self._values_of("package");
890 if spec.iter().any(cargo_util::is_glob_pattern) {
891 anyhow::bail!("glob patterns on package selection are not supported.")
892 }
893 compile_opts.spec = Packages::Packages(spec);
894 Ok(compile_opts)
895 }
896
897 fn new_options(&self, gctx: &GlobalContext) -> CargoResult<NewOptions> {
898 let vcs = self._value_of("vcs").map(|vcs| {
899 vcs.parse::<VersionControl>()
900 .expect("clap ensures only valid values are present")
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::workspace::parser::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::workspace::parser::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: IndexMap<&str, (usize, Vec<&str>)> = IndexMap::default();
1155
1156 for package in ws.members() {
1158 let package_name = package.name();
1159 let order = if ws.current_opt().map(|p| p.name()) == Some(package_name) {
1160 0
1161 } else {
1162 1
1163 };
1164
1165 for feature_name in package.summary().features().keys() {
1167 let (min_order, packages) = feature_candidates
1168 .entry(feature_name.as_str())
1169 .or_insert((order, Vec::new()));
1170 *min_order = (*min_order).min(order);
1171 packages.push(package_name.as_str());
1172 }
1173 }
1174
1175 Ok(feature_candidates
1176 .into_iter()
1177 .map(|(feature_name, (order, packages))| {
1178 clap_complete::CompletionCandidate::new(feature_name)
1179 .display_order(Some(order))
1180 .help(Some(format!("from {}", packages.join(", ")).into()))
1181 })
1182 .collect())
1183}
1184
1185fn get_crate_candidates(kind: TargetKind) -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1186 let gctx = new_gctx_for_completions()?;
1187
1188 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1189
1190 let targets = ws
1191 .members()
1192 .flat_map(|pkg| pkg.targets().into_iter().cloned().map(|t| (pkg.name(), t)))
1193 .filter(|(_, target)| *target.kind() == kind)
1194 .map(|(pkg_name, target)| {
1195 let order = if ws.current_opt().map(|p| p.name()) == Some(pkg_name) {
1196 0
1197 } else {
1198 1
1199 };
1200 clap_complete::CompletionCandidate::new(target.name())
1201 .display_order(Some(order))
1202 .help(Some(format!("from {}", pkg_name).into()))
1203 })
1204 .collect::<Vec<_>>();
1205
1206 Ok(targets)
1207}
1208
1209fn get_target_tuples() -> Vec<clap_complete::CompletionCandidate> {
1210 let mut candidates = Vec::new();
1211
1212 if let Ok(targets) = get_target_tuples_from_rustup() {
1213 candidates = targets;
1214 }
1215
1216 if candidates.is_empty() {
1217 if let Ok(targets) = get_target_tuples_from_rustc() {
1218 candidates = targets;
1219 }
1220 }
1221
1222 candidates.insert(
1224 0,
1225 clap_complete::CompletionCandidate::new("host-tuple").help(Some(
1226 concat!("alias for: ", env!("RUST_HOST_TARGET")).into(),
1227 )),
1228 );
1229
1230 candidates
1231}
1232
1233pub fn get_target_tuples_with_all() -> Vec<clap_complete::CompletionCandidate> {
1234 let mut candidates = vec![
1235 clap_complete::CompletionCandidate::new("all").help(Some("Include all targets".into())),
1236 ];
1237 candidates.extend(get_target_tuples());
1238 candidates
1239}
1240
1241fn get_target_tuples_from_rustup() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1242 let output = std::process::Command::new("rustup")
1243 .arg("target")
1244 .arg("list")
1245 .output()?;
1246
1247 if !output.status.success() {
1248 return Ok(vec![]);
1249 }
1250
1251 let stdout = String::from_utf8(output.stdout)?;
1252
1253 Ok(stdout
1254 .lines()
1255 .map(|line| {
1256 let target = line.split_once(' ');
1257 match target {
1258 None => clap_complete::CompletionCandidate::new(line.to_owned()).hide(true),
1259 Some((target, _installed)) => clap_complete::CompletionCandidate::new(target),
1260 }
1261 })
1262 .collect())
1263}
1264
1265fn get_target_tuples_from_rustc() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1266 let gctx = new_gctx_for_completions()?;
1267
1268 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx);
1269
1270 let rustc = gctx.load_global_rustc(ws.as_ref().ok())?;
1271
1272 let (stdout, _stderr) =
1273 rustc.cached_output(rustc.process().arg("--print").arg("target-list"), 0)?;
1274
1275 Ok(stdout
1276 .lines()
1277 .map(|line| clap_complete::CompletionCandidate::new(line.to_owned()))
1278 .collect())
1279}
1280
1281pub fn get_ws_member_candidates() -> Vec<clap_complete::CompletionCandidate> {
1282 get_ws_member_packages()
1283 .unwrap_or_default()
1284 .into_iter()
1285 .map(|pkg| {
1286 clap_complete::CompletionCandidate::new(pkg.name().as_str()).help(
1287 pkg.manifest()
1288 .metadata()
1289 .description
1290 .to_owned()
1291 .map(From::from),
1292 )
1293 })
1294 .collect::<Vec<_>>()
1295}
1296
1297fn get_ws_member_packages() -> CargoResult<Vec<Package>> {
1298 let gctx = new_gctx_for_completions()?;
1299 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1300 let packages = ws.members().map(Clone::clone).collect::<Vec<_>>();
1301 Ok(packages)
1302}
1303
1304pub fn get_pkg_id_spec_candidates() -> Vec<clap_complete::CompletionCandidate> {
1305 let mut candidates = vec![];
1306
1307 let package_map = HashMap::<&str, Vec<Package>>::default();
1308 let package_map =
1309 get_packages()
1310 .unwrap_or_default()
1311 .into_iter()
1312 .fold(package_map, |mut map, package| {
1313 map.entry(package.name().as_str())
1314 .or_insert_with(Vec::new)
1315 .push(package);
1316 map
1317 });
1318
1319 let unique_name_candidates = package_map
1320 .iter()
1321 .filter(|(_name, packages)| packages.len() == 1)
1322 .map(|(name, packages)| {
1323 clap_complete::CompletionCandidate::new(name.to_string()).help(
1324 packages[0]
1325 .manifest()
1326 .metadata()
1327 .description
1328 .to_owned()
1329 .map(From::from),
1330 )
1331 })
1332 .collect::<Vec<_>>();
1333
1334 let duplicate_name_pairs = package_map
1335 .iter()
1336 .filter(|(_name, packages)| packages.len() > 1)
1337 .collect::<Vec<_>>();
1338
1339 let mut duplicate_name_candidates = vec![];
1340 for (name, packages) in duplicate_name_pairs {
1341 let mut version_count: HashMap<&Version, usize> = HashMap::default();
1342
1343 for package in packages {
1344 *version_count.entry(package.version()).or_insert(0) += 1;
1345 }
1346
1347 for package in packages {
1348 if let Some(&count) = version_count.get(package.version()) {
1349 if count == 1 {
1350 duplicate_name_candidates.push(
1351 clap_complete::CompletionCandidate::new(format!(
1352 "{}@{}",
1353 name,
1354 package.version()
1355 ))
1356 .help(
1357 package
1358 .manifest()
1359 .metadata()
1360 .description
1361 .to_owned()
1362 .map(From::from),
1363 ),
1364 );
1365 } else {
1366 duplicate_name_candidates.push(
1367 clap_complete::CompletionCandidate::new(format!(
1368 "{}",
1369 package.package_id().to_spec()
1370 ))
1371 .help(
1372 package
1373 .manifest()
1374 .metadata()
1375 .description
1376 .to_owned()
1377 .map(From::from),
1378 ),
1379 )
1380 }
1381 }
1382 }
1383 }
1384
1385 candidates.extend(unique_name_candidates);
1386 candidates.extend(duplicate_name_candidates);
1387
1388 candidates
1389}
1390
1391pub fn get_pkg_name_candidates() -> Vec<clap_complete::CompletionCandidate> {
1392 let packages: BTreeMap<_, _> = get_packages()
1393 .unwrap_or_default()
1394 .into_iter()
1395 .map(|package| {
1396 (
1397 package.name(),
1398 package.manifest().metadata().description.clone(),
1399 )
1400 })
1401 .collect();
1402
1403 packages
1404 .into_iter()
1405 .map(|(name, description)| {
1406 clap_complete::CompletionCandidate::new(name.as_str()).help(description.map(From::from))
1407 })
1408 .collect()
1409}
1410
1411fn get_packages() -> CargoResult<Vec<Package>> {
1412 let gctx = new_gctx_for_completions()?;
1413
1414 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1415
1416 let requested_kinds = CompileKind::from_requested_targets(ws.gctx(), &[])?;
1417 let mut target_data = RustcTargetData::new(&ws, &requested_kinds)?;
1418 let cli_features = CliFeatures::new_all(true);
1420 let has_dev_units = HasDevUnits::Yes;
1421 let force_all_targets = ForceAllTargets::No;
1422 let dry_run = true;
1423
1424 let ws_resolve = ops::resolve_ws_with_opts(
1425 &ws,
1426 &mut target_data,
1427 &requested_kinds,
1428 &cli_features,
1429 &[],
1430 has_dev_units,
1431 force_all_targets,
1432 dry_run,
1433 )?;
1434
1435 let packages = ws_resolve
1436 .pkg_set
1437 .packages()
1438 .map(Clone::clone)
1439 .collect::<Vec<_>>();
1440
1441 Ok(packages)
1442}
1443
1444pub fn get_direct_dependencies_pkg_name_candidates() -> Vec<clap_complete::CompletionCandidate> {
1445 let (current_package_deps, all_package_deps) = match get_dependencies_from_metadata() {
1446 Ok(v) => v,
1447 Err(_) => return Vec::new(),
1448 };
1449
1450 let current_package_deps_package_names = current_package_deps
1451 .into_iter()
1452 .map(|dep| dep.package_name().to_string())
1453 .sorted();
1454 let all_package_deps_package_names = all_package_deps
1455 .into_iter()
1456 .map(|dep| dep.package_name().to_string())
1457 .sorted();
1458
1459 let mut package_names_set = IndexSet::default();
1460 package_names_set.extend(current_package_deps_package_names);
1461 package_names_set.extend(all_package_deps_package_names);
1462
1463 package_names_set
1464 .into_iter()
1465 .map(|name| name.into())
1466 .collect_vec()
1467}
1468
1469fn get_dependencies_from_metadata() -> CargoResult<(Vec<Dependency>, Vec<Dependency>)> {
1470 let gctx = GlobalContext::default()?;
1471 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1472 let current_package = ws.current().ok();
1473
1474 let current_package_dependencies = ws
1475 .current()
1476 .map(|current| current.dependencies())
1477 .unwrap_or_default()
1478 .to_vec();
1479 let all_other_packages_dependencies = ws
1480 .members()
1481 .filter(|&member| Some(member) != current_package)
1482 .flat_map(|pkg| pkg.dependencies().into_iter().cloned())
1483 .collect::<HashSet<_>>()
1484 .into_iter()
1485 .collect::<Vec<_>>();
1486
1487 Ok((
1488 current_package_dependencies,
1489 all_other_packages_dependencies,
1490 ))
1491}
1492
1493pub fn new_gctx_for_completions() -> CargoResult<GlobalContext> {
1494 let mut gctx = GlobalContext::default()?;
1495
1496 let verbose = 0;
1497 let quiet = true;
1498 let color = None;
1499 let frozen = false;
1500 let locked = true;
1501 let offline = false;
1502 let target_dir = None;
1503 let unstable_flags = &[];
1504 let cli_config = &[];
1505
1506 gctx.configure(
1507 verbose,
1508 quiet,
1509 color,
1510 frozen,
1511 locked,
1512 offline,
1513 &target_dir,
1514 unstable_flags,
1515 cli_config,
1516 )?;
1517
1518 Ok(gctx)
1519}
1520
1521#[track_caller]
1522pub fn ignore_unknown<T: Default>(r: Result<T, clap::parser::MatchesError>) -> T {
1523 match r {
1524 Ok(t) => t,
1525 Err(clap::parser::MatchesError::UnknownArgument { .. }) => Default::default(),
1526 Err(e) => {
1527 panic!("Mismatch between definition and access: {}", e);
1528 }
1529 }
1530}
1531
1532pub fn warn_ignored_zero_values(gctx: &GlobalContext, name: &str) -> CargoResult<()> {
1534 gctx.shell().print_report(
1535 &[Level::WARNING
1536 .secondary_title(format!("`--{name}` without a value is ignored"))
1537 .elements([
1538 Level::NOTE.message(
1539 "this was previously accepted but will become a hard error in the future",
1540 ),
1541 Level::HELP.message(format!("pass a value to `--{name}` or remove it")),
1542 ])],
1543 false,
1544 )
1545}