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, shell};
6use crate::ops::lockfile::LOCKFILE_NAME;
7use crate::ops::registry::RegistryOrIndex;
8use crate::ops::{self, CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
9use crate::util::important_paths::find_root_manifest_for_wd;
10use crate::util::interning::InternedString;
11use crate::util::is_rustup;
12use crate::util::restricted_names;
13use crate::util::toml::is_embedded;
14use crate::util::{
15 print_available_benches, print_available_binaries, print_available_examples,
16 print_available_packages, print_available_tests,
17};
18use anyhow::bail;
19use cargo_util::paths;
20use cargo_util_schemas::manifest::ProfileName;
21use cargo_util_schemas::manifest::RegistryName;
22use cargo_util_schemas::manifest::StringOrVec;
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_lockfile_path(self) -> Self {
395 self._arg(
396 opt("lockfile-path", "Path to Cargo.lock (unstable)")
397 .value_name("PATH")
398 .help_heading(heading::MANIFEST_OPTIONS)
399 .add(clap_complete::engine::ArgValueCompleter::new(
400 clap_complete::engine::PathCompleter::any().filter(|path: &Path| {
401 let file_name = match path.file_name() {
402 Some(name) => name,
403 None => return false,
404 };
405
406 file_name == OsStr::new("Cargo.lock")
408 }),
409 )),
410 )
411 }
412
413 fn arg_message_format(self) -> Self {
414 self._arg(
415 multi_opt("message-format", "FMT", "Error format")
416 .value_parser([
417 "human",
418 "short",
419 "json",
420 "json-diagnostic-short",
421 "json-diagnostic-rendered-ansi",
422 "json-render-diagnostics",
423 ])
424 .value_delimiter(',')
425 .ignore_case(true),
426 )
427 }
428
429 fn arg_unit_graph(self) -> Self {
430 self._arg(
431 flag("unit-graph", "Output build graph in JSON (unstable)")
432 .help_heading(heading::COMPILATION_OPTIONS),
433 )
434 }
435
436 fn arg_new_opts(self) -> Self {
437 self._arg(
438 opt(
439 "vcs",
440 "Initialize a new repository for the given version \
441 control system, overriding \
442 a global configuration.",
443 )
444 .value_name("VCS")
445 .value_parser(["git", "hg", "pijul", "fossil", "none"]),
446 )
447 ._arg(flag("bin", "Use a binary (application) template [default]"))
448 ._arg(flag("lib", "Use a library template"))
449 ._arg(
450 opt("edition", "Edition to set for the crate generated")
451 .value_parser(Edition::CLI_VALUES)
452 .value_name("YEAR"),
453 )
454 ._arg(
455 opt(
456 "name",
457 "Set the resulting package name, defaults to the directory name",
458 )
459 .value_name("NAME"),
460 )
461 }
462
463 fn arg_registry(self, help: &'static str) -> Self {
464 self._arg(opt("registry", help).value_name("REGISTRY").add(
465 clap_complete::ArgValueCandidates::new(|| {
466 let candidates = get_registry_candidates();
467 candidates.unwrap_or_default()
468 }),
469 ))
470 }
471
472 fn arg_index(self, help: &'static str) -> Self {
473 self._arg(
475 opt("index", help)
476 .value_name("INDEX")
477 .conflicts_with("registry"),
478 )
479 }
480
481 fn arg_dry_run(self, dry_run: &'static str) -> Self {
482 self._arg(flag("dry-run", dry_run).short('n'))
483 }
484
485 fn arg_ignore_rust_version(self) -> Self {
486 self.arg_ignore_rust_version_with_help("Ignore `rust-version` specification in packages")
487 }
488
489 fn arg_ignore_rust_version_with_help(self, help: &'static str) -> Self {
490 self._arg(flag("ignore-rust-version", help).help_heading(heading::MANIFEST_OPTIONS))
491 }
492
493 fn arg_future_incompat_report(self) -> Self {
494 self._arg(flag(
495 "future-incompat-report",
496 "Outputs a future incompatibility report at the end of the build",
497 ))
498 }
499
500 fn arg_silent_suggestion(self) -> Self {
506 let value_parser = UnknownArgumentValueParser::suggest_arg("--quiet");
507 self._arg(
508 flag("silent", "")
509 .short('s')
510 .value_parser(value_parser)
511 .hide(true),
512 )
513 }
514
515 fn arg_timings(self) -> Self {
516 self._arg(
517 flag(
518 "timings",
519 "Output a build timing report at the end of the build",
520 )
521 .help_heading(heading::COMPILATION_OPTIONS),
522 )
523 }
524
525 fn arg_artifact_dir(self) -> Self {
526 let unsupported_short_arg = {
527 let value_parser = UnknownArgumentValueParser::suggest_arg("--artifact-dir");
528 Arg::new("unsupported-short-artifact-dir-flag")
529 .help("")
530 .short('O')
531 .value_parser(value_parser)
532 .action(ArgAction::SetTrue)
533 .hide(true)
534 };
535
536 self._arg(
537 opt(
538 "artifact-dir",
539 "Copy final artifacts to this directory (unstable)",
540 )
541 .value_name("PATH")
542 .help_heading(heading::COMPILATION_OPTIONS),
543 )
544 ._arg(unsupported_short_arg)
545 ._arg(
546 opt(
547 "out-dir",
548 "Copy final artifacts to this directory (deprecated; use --artifact-dir instead)",
549 )
550 .value_name("PATH")
551 .conflicts_with("artifact-dir")
552 .hide(true),
553 )
554 }
555
556 fn arg_compile_time_deps(self) -> Self {
557 self._arg(flag("compile-time-deps", "").hide(true))
558 }
559}
560
561impl CommandExt for Command {
562 fn _arg(self, arg: Arg) -> Self {
563 self.arg(arg)
564 }
565}
566
567pub fn flag(name: &'static str, help: &'static str) -> Arg {
568 Arg::new(name)
569 .long(name)
570 .help(help)
571 .action(ArgAction::SetTrue)
572}
573
574pub fn opt(name: &'static str, help: &'static str) -> Arg {
575 Arg::new(name).long(name).help(help).action(ArgAction::Set)
576}
577
578pub fn optional_opt(name: &'static str, help: &'static str) -> Arg {
579 opt(name, help).num_args(0..=1)
580}
581
582pub fn optional_multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Arg {
583 opt(name, help)
584 .value_name(value_name)
585 .num_args(0..=1)
586 .action(ArgAction::Append)
587}
588
589pub fn multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Arg {
590 opt(name, help)
591 .value_name(value_name)
592 .action(ArgAction::Append)
593}
594
595pub fn subcommand(name: &'static str) -> Command {
596 Command::new(name)
597}
598
599pub enum ProfileChecking {
601 LegacyRustc,
604 LegacyTestOnly,
607 Custom,
609}
610
611pub trait ArgMatchesExt {
612 fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
613 let arg = match self._value_of(name) {
614 None => None,
615 Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
616 clap::Error::raw(
617 clap::error::ErrorKind::ValueValidation,
618 format!("Invalid value: could not parse `{}` as a number", arg),
619 )
620 })?),
621 };
622 Ok(arg)
623 }
624
625 fn value_of_i32(&self, name: &str) -> CargoResult<Option<i32>> {
626 let arg = match self._value_of(name) {
627 None => None,
628 Some(arg) => Some(arg.parse::<i32>().map_err(|_| {
629 clap::Error::raw(
630 clap::error::ErrorKind::ValueValidation,
631 format!("Invalid value: could not parse `{}` as a number", arg),
632 )
633 })?),
634 };
635 Ok(arg)
636 }
637
638 fn value_of_path(&self, name: &str, gctx: &GlobalContext) -> Option<PathBuf> {
640 self._value_of(name).map(|path| gctx.cwd().join(path))
641 }
642
643 fn root_manifest(&self, gctx: &GlobalContext) -> CargoResult<PathBuf> {
644 root_manifest(self._value_of("manifest-path").map(Path::new), gctx)
645 }
646
647 fn lockfile_path(&self, gctx: &GlobalContext) -> CargoResult<Option<PathBuf>> {
648 lockfile_path(self._value_of("lockfile-path").map(Path::new), gctx)
649 }
650
651 #[tracing::instrument(skip_all)]
652 fn workspace<'a>(&self, gctx: &'a GlobalContext) -> CargoResult<Workspace<'a>> {
653 let root = self.root_manifest(gctx)?;
654 let lockfile_path = self.lockfile_path(gctx)?;
655 let mut ws = Workspace::new(&root, gctx)?;
656 ws.set_resolve_honors_rust_version(self.honor_rust_version());
657 if gctx.cli_unstable().avoid_dev_deps {
658 ws.set_require_optional_deps(false);
659 }
660 ws.set_requested_lockfile_path(lockfile_path);
661 Ok(ws)
662 }
663
664 fn jobs(&self) -> CargoResult<Option<JobsConfig>> {
665 let arg = match self._value_of("jobs") {
666 None => None,
667 Some(arg) => match arg.parse::<i32>() {
668 Ok(j) => Some(JobsConfig::Integer(j)),
669 Err(_) => Some(JobsConfig::String(arg.to_string())),
670 },
671 };
672
673 Ok(arg)
674 }
675
676 fn verbose(&self) -> u32 {
677 self._count("verbose")
678 }
679
680 fn dry_run(&self) -> bool {
681 self.flag("dry-run")
682 }
683
684 fn keep_going(&self) -> bool {
685 self.maybe_flag("keep-going")
686 }
687
688 fn honor_rust_version(&self) -> Option<bool> {
689 self.flag("ignore-rust-version").then_some(false)
690 }
691
692 fn targets(&self) -> CargoResult<Vec<String>> {
693 if self.is_present_with_zero_values("target") {
694 let cmd = if is_rustup() {
695 "rustup target list"
696 } else {
697 "rustc --print target-list"
698 };
699 bail!(
700 "\"--target\" takes a target architecture as an argument.
701
702Run `{cmd}` to see possible targets."
703 );
704 }
705 Ok(self._values_of("target"))
706 }
707
708 fn get_profile_name(
709 &self,
710 default: &str,
711 profile_checking: ProfileChecking,
712 ) -> CargoResult<InternedString> {
713 let specified_profile = self._value_of("profile");
714
715 match (specified_profile, profile_checking) {
718 (Some(name @ ("dev" | "test" | "bench" | "check")), ProfileChecking::LegacyRustc)
720 | (Some(name @ "test"), ProfileChecking::LegacyTestOnly) => {
722 return Ok(name.into());
723 }
724 _ => {}
725 }
726
727 let name = match (
728 self.maybe_flag("release"),
729 self.maybe_flag("debug"),
730 specified_profile,
731 ) {
732 (false, false, None) => default,
733 (true, _, None) => "release",
734 (_, true, None) => "dev",
735 (_, _, Some("doc")) => {
741 bail!("profile `doc` is reserved and not allowed to be explicitly specified")
742 }
743 (_, _, Some(name)) => {
744 ProfileName::new(name)?;
745 name
746 }
747 };
748
749 Ok(name.into())
750 }
751
752 fn packages_from_flags(&self) -> CargoResult<Packages> {
753 Packages::from_flags(
754 self.flag("workspace") || self.flag("all"),
756 self._values_of("exclude"),
757 self._values_of("package"),
758 )
759 }
760
761 fn compile_options(
762 &self,
763 gctx: &GlobalContext,
764 intent: UserIntent,
765 workspace: Option<&Workspace<'_>>,
766 profile_checking: ProfileChecking,
767 ) -> CargoResult<CompileOptions> {
768 let spec = self.packages_from_flags()?;
769 let mut message_format = None;
770 let default_json = MessageFormat::Json {
771 short: false,
772 ansi: false,
773 render_diagnostics: false,
774 };
775 let two_kinds_of_msg_format_err = "cannot specify two kinds of `message-format` arguments";
776 for fmt in self._values_of("message-format") {
777 for fmt in fmt.split(',') {
778 let fmt = fmt.to_ascii_lowercase();
779 match fmt.as_str() {
780 "json" => {
781 if message_format.is_some() {
782 bail!(two_kinds_of_msg_format_err);
783 }
784 message_format = Some(default_json);
785 }
786 "human" => {
787 if message_format.is_some() {
788 bail!(two_kinds_of_msg_format_err);
789 }
790 message_format = Some(MessageFormat::Human);
791 }
792 "short" => {
793 if message_format.is_some() {
794 bail!(two_kinds_of_msg_format_err);
795 }
796 message_format = Some(MessageFormat::Short);
797 }
798 "json-render-diagnostics" => {
799 if message_format.is_none() {
800 message_format = Some(default_json);
801 }
802 match &mut message_format {
803 Some(MessageFormat::Json {
804 render_diagnostics, ..
805 }) => *render_diagnostics = true,
806 _ => bail!(two_kinds_of_msg_format_err),
807 }
808 }
809 "json-diagnostic-short" => {
810 if message_format.is_none() {
811 message_format = Some(default_json);
812 }
813 match &mut message_format {
814 Some(MessageFormat::Json { short, .. }) => *short = true,
815 _ => bail!(two_kinds_of_msg_format_err),
816 }
817 }
818 "json-diagnostic-rendered-ansi" => {
819 if message_format.is_none() {
820 message_format = Some(default_json);
821 }
822 match &mut message_format {
823 Some(MessageFormat::Json { ansi, .. }) => *ansi = true,
824 _ => bail!(two_kinds_of_msg_format_err),
825 }
826 }
827 s => bail!("invalid message format specifier: `{}`", s),
828 }
829 }
830 }
831
832 let mut build_config = BuildConfig::new(
833 gctx,
834 self.jobs()?,
835 self.keep_going(),
836 &self.targets()?,
837 intent,
838 )?;
839 build_config.message_format = message_format.unwrap_or(MessageFormat::Human);
840 build_config.requested_profile = self.get_profile_name("dev", profile_checking)?;
841 build_config.unit_graph = self.flag("unit-graph");
842 build_config.future_incompat_report = self.flag("future-incompat-report");
843 build_config.compile_time_deps_only = self.flag("compile-time-deps");
844 build_config.timing_report = self.flag("timings");
845
846 if build_config.unit_graph {
847 gctx.cli_unstable()
848 .fail_if_stable_opt("--unit-graph", 8002)?;
849 }
850 if build_config.compile_time_deps_only {
851 gctx.cli_unstable()
852 .fail_if_stable_opt("--compile-time-deps", 14434)?;
853 }
854
855 let opts = CompileOptions {
856 build_config,
857 cli_features: self.cli_features()?,
858 spec,
859 filter: CompileFilter::from_raw_arguments(
860 self.flag("lib"),
861 self._values_of("bin"),
862 self.flag("bins"),
863 self._values_of("test"),
864 self.flag("tests"),
865 self._values_of("example"),
866 self.flag("examples"),
867 self._values_of("bench"),
868 self.flag("benches"),
869 self.flag("all-targets"),
870 ),
871 target_rustdoc_args: None,
872 target_rustc_args: None,
873 target_rustc_crate_types: None,
874 rustdoc_document_private_items: false,
875 honor_rust_version: self.honor_rust_version(),
876 };
877
878 if let Some(ws) = workspace {
879 self.check_optional_opts(ws, &opts)?;
880 } else if self.is_present_with_zero_values("package") {
881 anyhow::bail!(
884 "\"--package <SPEC>\" requires a SPEC format value, \
885 which can be any package ID specifier in the dependency graph.\n\
886 Run `cargo help pkgid` for more information about SPEC format."
887 )
888 }
889
890 Ok(opts)
891 }
892
893 fn cli_features(&self) -> CargoResult<CliFeatures> {
894 CliFeatures::from_command_line(
895 &self._values_of("features"),
896 self.flag("all-features"),
897 !self.flag("no-default-features"),
898 )
899 }
900
901 fn compile_options_for_single_package(
902 &self,
903 gctx: &GlobalContext,
904 intent: UserIntent,
905 workspace: Option<&Workspace<'_>>,
906 profile_checking: ProfileChecking,
907 ) -> CargoResult<CompileOptions> {
908 let mut compile_opts = self.compile_options(gctx, intent, workspace, profile_checking)?;
909 let spec = self._values_of("package");
910 if spec.iter().any(restricted_names::is_glob_pattern) {
911 anyhow::bail!("Glob patterns on package selection are not supported.")
912 }
913 compile_opts.spec = Packages::Packages(spec);
914 Ok(compile_opts)
915 }
916
917 fn new_options(&self, gctx: &GlobalContext) -> CargoResult<NewOptions> {
918 let vcs = self._value_of("vcs").map(|vcs| match vcs {
919 "git" => VersionControl::Git,
920 "hg" => VersionControl::Hg,
921 "pijul" => VersionControl::Pijul,
922 "fossil" => VersionControl::Fossil,
923 "none" => VersionControl::NoVcs,
924 vcs => panic!("Impossible vcs: {:?}", vcs),
925 });
926 NewOptions::new(
927 vcs,
928 self.flag("bin"),
929 self.flag("lib"),
930 self.value_of_path("path", gctx).unwrap(),
931 self._value_of("name").map(|s| s.to_string()),
932 self._value_of("edition").map(|s| s.to_string()),
933 self.registry(gctx)?,
934 )
935 }
936
937 fn registry_or_index(&self, gctx: &GlobalContext) -> CargoResult<Option<RegistryOrIndex>> {
938 let registry = self._value_of("registry");
939 let index = self._value_of("index");
940 let result = match (registry, index) {
941 (None, None) => gctx.default_registry()?.map(RegistryOrIndex::Registry),
942 (None, Some(i)) => Some(RegistryOrIndex::Index(i.into_url()?)),
943 (Some(r), None) => {
944 RegistryName::new(r)?;
945 Some(RegistryOrIndex::Registry(r.to_string()))
946 }
947 (Some(_), Some(_)) => {
948 unreachable!("both `--index` and `--registry` should not be set at the same time")
950 }
951 };
952 Ok(result)
953 }
954
955 fn registry(&self, gctx: &GlobalContext) -> CargoResult<Option<String>> {
956 match self._value_of("registry").map(|s| s.to_string()) {
957 None => gctx.default_registry(),
958 Some(registry) => {
959 RegistryName::new(®istry)?;
960 Ok(Some(registry))
961 }
962 }
963 }
964
965 fn check_optional_opts(
966 &self,
967 workspace: &Workspace<'_>,
968 compile_opts: &CompileOptions,
969 ) -> CargoResult<()> {
970 if self.is_present_with_zero_values("package") {
971 print_available_packages(workspace)?
972 }
973
974 if self.is_present_with_zero_values("example") {
975 print_available_examples(workspace, compile_opts)?;
976 }
977
978 if self.is_present_with_zero_values("bin") {
979 print_available_binaries(workspace, compile_opts)?;
980 }
981
982 if self.is_present_with_zero_values("bench") {
983 print_available_benches(workspace, compile_opts)?;
984 }
985
986 if self.is_present_with_zero_values("test") {
987 print_available_tests(workspace, compile_opts)?;
988 }
989
990 Ok(())
991 }
992
993 fn is_present_with_zero_values(&self, name: &str) -> bool {
994 self._contains(name) && self._value_of(name).is_none()
995 }
996
997 fn flag(&self, name: &str) -> bool;
998
999 fn maybe_flag(&self, name: &str) -> bool;
1000
1001 fn _value_of(&self, name: &str) -> Option<&str>;
1002
1003 fn _values_of(&self, name: &str) -> Vec<String>;
1004
1005 fn _value_of_os(&self, name: &str) -> Option<&OsStr>;
1006
1007 fn _values_of_os(&self, name: &str) -> Vec<OsString>;
1008
1009 fn _count(&self, name: &str) -> u32;
1010
1011 fn _contains(&self, name: &str) -> bool;
1012}
1013
1014impl<'a> ArgMatchesExt for ArgMatches {
1015 fn flag(&self, name: &str) -> bool {
1016 ignore_unknown(self.try_get_one::<bool>(name))
1017 .copied()
1018 .unwrap_or(false)
1019 }
1020
1021 fn maybe_flag(&self, name: &str) -> bool {
1025 self.try_get_one::<bool>(name)
1026 .ok()
1027 .flatten()
1028 .copied()
1029 .unwrap_or_default()
1030 }
1031
1032 fn _value_of(&self, name: &str) -> Option<&str> {
1033 ignore_unknown(self.try_get_one::<String>(name)).map(String::as_str)
1034 }
1035
1036 fn _value_of_os(&self, name: &str) -> Option<&OsStr> {
1037 ignore_unknown(self.try_get_one::<OsString>(name)).map(OsString::as_os_str)
1038 }
1039
1040 fn _values_of(&self, name: &str) -> Vec<String> {
1041 ignore_unknown(self.try_get_many::<String>(name))
1042 .unwrap_or_default()
1043 .cloned()
1044 .collect()
1045 }
1046
1047 fn _values_of_os(&self, name: &str) -> Vec<OsString> {
1048 ignore_unknown(self.try_get_many::<OsString>(name))
1049 .unwrap_or_default()
1050 .cloned()
1051 .collect()
1052 }
1053
1054 fn _count(&self, name: &str) -> u32 {
1055 *ignore_unknown(self.try_get_one::<u8>(name)).expect("defaulted by clap") as u32
1056 }
1057
1058 fn _contains(&self, name: &str) -> bool {
1059 ignore_unknown(self.try_contains_id(name))
1060 }
1061}
1062
1063pub fn values(args: &ArgMatches, name: &str) -> Vec<String> {
1064 args._values_of(name)
1065}
1066
1067pub fn values_os(args: &ArgMatches, name: &str) -> Vec<OsString> {
1068 args._values_of_os(name)
1069}
1070
1071pub fn root_manifest(manifest_path: Option<&Path>, gctx: &GlobalContext) -> CargoResult<PathBuf> {
1072 if let Some(manifest_path) = manifest_path {
1073 let path = gctx.cwd().join(manifest_path);
1074 let path = paths::normalize_path(&path);
1077 if !path.ends_with("Cargo.toml") && !crate::util::toml::is_embedded(&path) {
1078 anyhow::bail!(
1079 "the manifest-path must be a path to a Cargo.toml file: `{}`",
1080 path.display()
1081 )
1082 }
1083 if !path.exists() {
1084 anyhow::bail!("manifest path `{}` does not exist", manifest_path.display())
1085 }
1086 if path.is_dir() {
1087 anyhow::bail!(
1088 "manifest path `{}` is a directory but expected a file",
1089 manifest_path.display()
1090 )
1091 }
1092 if crate::util::toml::is_embedded(&path) && !gctx.cli_unstable().script {
1093 anyhow::bail!("embedded manifest `{}` requires `-Zscript`", path.display())
1094 }
1095 Ok(path)
1096 } else {
1097 find_root_manifest_for_wd(gctx.cwd())
1098 }
1099}
1100
1101pub fn lockfile_path(
1102 lockfile_path: Option<&Path>,
1103 gctx: &GlobalContext,
1104) -> CargoResult<Option<PathBuf>> {
1105 let Some(lockfile_path) = lockfile_path else {
1106 return Ok(None);
1107 };
1108
1109 gctx.cli_unstable()
1110 .fail_if_stable_opt("--lockfile-path", 14421)?;
1111
1112 let path = gctx.cwd().join(lockfile_path);
1113
1114 if !path.ends_with(LOCKFILE_NAME) {
1115 bail!(
1116 "the lockfile-path must be a path to a {LOCKFILE_NAME} file (please rename your lock file to {LOCKFILE_NAME})"
1117 )
1118 }
1119 if path.is_dir() {
1120 bail!(
1121 "lockfile path `{}` is a directory but expected a file",
1122 lockfile_path.display()
1123 )
1124 }
1125
1126 return Ok(Some(path));
1127}
1128
1129pub fn get_registry_candidates() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1130 let gctx = new_gctx_for_completions()?;
1131
1132 if let Ok(Some(registries)) =
1133 gctx.get::<Option<HashMap<String, HashMap<String, String>>>>("registries")
1134 {
1135 Ok(registries
1136 .keys()
1137 .map(|name| clap_complete::CompletionCandidate::new(name.to_owned()))
1138 .collect())
1139 } else {
1140 Ok(vec![])
1141 }
1142}
1143
1144fn get_profile_candidates() -> Vec<clap_complete::CompletionCandidate> {
1145 match get_workspace_profile_candidates() {
1146 Ok(candidates) if !candidates.is_empty() => candidates,
1147 _ => default_profile_candidates(),
1149 }
1150}
1151
1152fn get_workspace_profile_candidates() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1153 let gctx = new_gctx_for_completions()?;
1154 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1155 let profiles = Profiles::new(&ws, "dev".into())?;
1156
1157 let mut candidates = Vec::new();
1158 for name in profiles.profile_names() {
1159 let Ok(profile_instance) = Profiles::new(&ws, name) else {
1160 continue;
1161 };
1162 let base_profile = profile_instance.base_profile();
1163
1164 let mut description = String::from(if base_profile.opt_level.as_str() == "0" {
1165 "unoptimized"
1166 } else {
1167 "optimized"
1168 });
1169
1170 if base_profile.debuginfo.is_turned_on() {
1171 description.push_str(" + debuginfo");
1172 }
1173
1174 candidates
1175 .push(clap_complete::CompletionCandidate::new(&name).help(Some(description.into())));
1176 }
1177
1178 Ok(candidates)
1179}
1180
1181fn default_profile_candidates() -> Vec<clap_complete::CompletionCandidate> {
1182 vec![
1183 clap_complete::CompletionCandidate::new("dev").help(Some("unoptimized + debuginfo".into())),
1184 clap_complete::CompletionCandidate::new("release").help(Some("optimized".into())),
1185 clap_complete::CompletionCandidate::new("test")
1186 .help(Some("unoptimized + debuginfo".into())),
1187 clap_complete::CompletionCandidate::new("bench").help(Some("optimized".into())),
1188 ]
1189}
1190
1191fn get_feature_candidates() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1192 let gctx = new_gctx_for_completions()?;
1193
1194 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1195 let mut feature_candidates = Vec::new();
1196
1197 for package in ws.members() {
1199 let package_name = package.name();
1200
1201 for feature_name in package.summary().features().keys() {
1203 let order = if ws.current_opt().map(|p| p.name()) == Some(package_name) {
1204 0
1205 } else {
1206 1
1207 };
1208 feature_candidates.push(
1209 clap_complete::CompletionCandidate::new(feature_name)
1210 .display_order(Some(order))
1211 .help(Some(format!("from {}", package_name).into())),
1212 );
1213 }
1214 }
1215
1216 Ok(feature_candidates)
1217}
1218
1219fn get_crate_candidates(kind: TargetKind) -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1220 let gctx = new_gctx_for_completions()?;
1221
1222 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1223
1224 let targets = ws
1225 .members()
1226 .flat_map(|pkg| pkg.targets().into_iter().cloned().map(|t| (pkg.name(), t)))
1227 .filter(|(_, target)| *target.kind() == kind)
1228 .map(|(pkg_name, target)| {
1229 let order = if ws.current_opt().map(|p| p.name()) == Some(pkg_name) {
1230 0
1231 } else {
1232 1
1233 };
1234 clap_complete::CompletionCandidate::new(target.name())
1235 .display_order(Some(order))
1236 .help(Some(format!("from {}", pkg_name).into()))
1237 })
1238 .collect::<Vec<_>>();
1239
1240 Ok(targets)
1241}
1242
1243fn get_target_triples() -> Vec<clap_complete::CompletionCandidate> {
1244 let mut candidates = Vec::new();
1245
1246 if let Ok(targets) = get_target_triples_from_rustup() {
1247 candidates = targets;
1248 }
1249
1250 if candidates.is_empty() {
1251 if let Ok(targets) = get_target_triples_from_rustc() {
1252 candidates = targets;
1253 }
1254 }
1255
1256 candidates.insert(
1258 0,
1259 clap_complete::CompletionCandidate::new("host-tuple").help(Some(
1260 concat!("alias for: ", env!("RUST_HOST_TARGET")).into(),
1261 )),
1262 );
1263
1264 candidates
1265}
1266
1267pub fn get_target_triples_with_all() -> Vec<clap_complete::CompletionCandidate> {
1268 let mut candidates = vec![
1269 clap_complete::CompletionCandidate::new("all").help(Some("Include all targets".into())),
1270 ];
1271 candidates.extend(get_target_triples());
1272 candidates
1273}
1274
1275fn get_target_triples_from_rustup() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1276 let output = std::process::Command::new("rustup")
1277 .arg("target")
1278 .arg("list")
1279 .output()?;
1280
1281 if !output.status.success() {
1282 return Ok(vec![]);
1283 }
1284
1285 let stdout = String::from_utf8(output.stdout)?;
1286
1287 Ok(stdout
1288 .lines()
1289 .map(|line| {
1290 let target = line.split_once(' ');
1291 match target {
1292 None => clap_complete::CompletionCandidate::new(line.to_owned()).hide(true),
1293 Some((target, _installed)) => clap_complete::CompletionCandidate::new(target),
1294 }
1295 })
1296 .collect())
1297}
1298
1299fn get_target_triples_from_rustc() -> CargoResult<Vec<clap_complete::CompletionCandidate>> {
1300 let gctx = new_gctx_for_completions()?;
1301
1302 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx);
1303
1304 let rustc = gctx.load_global_rustc(ws.as_ref().ok())?;
1305
1306 let (stdout, _stderr) =
1307 rustc.cached_output(rustc.process().arg("--print").arg("target-list"), 0)?;
1308
1309 Ok(stdout
1310 .lines()
1311 .map(|line| clap_complete::CompletionCandidate::new(line.to_owned()))
1312 .collect())
1313}
1314
1315pub fn get_ws_member_candidates() -> Vec<clap_complete::CompletionCandidate> {
1316 get_ws_member_packages()
1317 .unwrap_or_default()
1318 .into_iter()
1319 .map(|pkg| {
1320 clap_complete::CompletionCandidate::new(pkg.name().as_str()).help(
1321 pkg.manifest()
1322 .metadata()
1323 .description
1324 .to_owned()
1325 .map(From::from),
1326 )
1327 })
1328 .collect::<Vec<_>>()
1329}
1330
1331fn get_ws_member_packages() -> CargoResult<Vec<Package>> {
1332 let gctx = new_gctx_for_completions()?;
1333 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1334 let packages = ws.members().map(Clone::clone).collect::<Vec<_>>();
1335 Ok(packages)
1336}
1337
1338pub fn get_pkg_id_spec_candidates() -> Vec<clap_complete::CompletionCandidate> {
1339 let mut candidates = vec![];
1340
1341 let package_map = HashMap::<&str, Vec<Package>>::new();
1342 let package_map =
1343 get_packages()
1344 .unwrap_or_default()
1345 .into_iter()
1346 .fold(package_map, |mut map, package| {
1347 map.entry(package.name().as_str())
1348 .or_insert_with(Vec::new)
1349 .push(package);
1350 map
1351 });
1352
1353 let unique_name_candidates = package_map
1354 .iter()
1355 .filter(|(_name, packages)| packages.len() == 1)
1356 .map(|(name, packages)| {
1357 clap_complete::CompletionCandidate::new(name.to_string()).help(
1358 packages[0]
1359 .manifest()
1360 .metadata()
1361 .description
1362 .to_owned()
1363 .map(From::from),
1364 )
1365 })
1366 .collect::<Vec<_>>();
1367
1368 let duplicate_name_pairs = package_map
1369 .iter()
1370 .filter(|(_name, packages)| packages.len() > 1)
1371 .collect::<Vec<_>>();
1372
1373 let mut duplicate_name_candidates = vec![];
1374 for (name, packages) in duplicate_name_pairs {
1375 let mut version_count: HashMap<&Version, usize> = HashMap::new();
1376
1377 for package in packages {
1378 *version_count.entry(package.version()).or_insert(0) += 1;
1379 }
1380
1381 for package in packages {
1382 if let Some(&count) = version_count.get(package.version()) {
1383 if count == 1 {
1384 duplicate_name_candidates.push(
1385 clap_complete::CompletionCandidate::new(format!(
1386 "{}@{}",
1387 name,
1388 package.version()
1389 ))
1390 .help(
1391 package
1392 .manifest()
1393 .metadata()
1394 .description
1395 .to_owned()
1396 .map(From::from),
1397 ),
1398 );
1399 } else {
1400 duplicate_name_candidates.push(
1401 clap_complete::CompletionCandidate::new(format!(
1402 "{}",
1403 package.package_id().to_spec()
1404 ))
1405 .help(
1406 package
1407 .manifest()
1408 .metadata()
1409 .description
1410 .to_owned()
1411 .map(From::from),
1412 ),
1413 )
1414 }
1415 }
1416 }
1417 }
1418
1419 candidates.extend(unique_name_candidates);
1420 candidates.extend(duplicate_name_candidates);
1421
1422 candidates
1423}
1424
1425pub fn get_pkg_name_candidates() -> Vec<clap_complete::CompletionCandidate> {
1426 let packages: BTreeMap<_, _> = get_packages()
1427 .unwrap_or_default()
1428 .into_iter()
1429 .map(|package| {
1430 (
1431 package.name(),
1432 package.manifest().metadata().description.clone(),
1433 )
1434 })
1435 .collect();
1436
1437 packages
1438 .into_iter()
1439 .map(|(name, description)| {
1440 clap_complete::CompletionCandidate::new(name.as_str()).help(description.map(From::from))
1441 })
1442 .collect()
1443}
1444
1445fn get_packages() -> CargoResult<Vec<Package>> {
1446 let gctx = new_gctx_for_completions()?;
1447
1448 let ws = Workspace::new(&find_root_manifest_for_wd(gctx.cwd())?, &gctx)?;
1449
1450 let requested_kinds = CompileKind::from_requested_targets(ws.gctx(), &[])?;
1451 let mut target_data = RustcTargetData::new(&ws, &requested_kinds)?;
1452 let cli_features = CliFeatures::new_all(true);
1454 let has_dev_units = HasDevUnits::Yes;
1455 let force_all_targets = ForceAllTargets::No;
1456 let dry_run = true;
1457
1458 let ws_resolve = ops::resolve_ws_with_opts(
1459 &ws,
1460 &mut target_data,
1461 &requested_kinds,
1462 &cli_features,
1463 &[],
1464 has_dev_units,
1465 force_all_targets,
1466 dry_run,
1467 )?;
1468
1469 let packages = ws_resolve
1470 .pkg_set
1471 .packages()
1472 .map(Clone::clone)
1473 .collect::<Vec<_>>();
1474
1475 Ok(packages)
1476}
1477
1478pub fn get_direct_dependencies_pkg_name_candidates() -> Vec<clap_complete::CompletionCandidate> {
1479 let (current_package_deps, all_package_deps) = match get_dependencies_from_metadata() {
1480 Ok(v) => v,
1481 Err(_) => return Vec::new(),
1482 };
1483
1484 let current_package_deps_package_names = current_package_deps
1485 .into_iter()
1486 .map(|dep| dep.package_name().to_string())
1487 .sorted();
1488 let all_package_deps_package_names = all_package_deps
1489 .into_iter()
1490 .map(|dep| dep.package_name().to_string())
1491 .sorted();
1492
1493 let mut package_names_set = IndexSet::new();
1494 package_names_set.extend(current_package_deps_package_names);
1495 package_names_set.extend(all_package_deps_package_names);
1496
1497 package_names_set
1498 .into_iter()
1499 .map(|name| name.into())
1500 .collect_vec()
1501}
1502
1503fn get_dependencies_from_metadata() -> CargoResult<(Vec<Dependency>, Vec<Dependency>)> {
1504 let cwd = std::env::current_dir()?;
1505 let gctx = GlobalContext::new(shell::Shell::new(), cwd.clone(), cargo_home_with_cwd(&cwd)?);
1506 let ws = Workspace::new(&find_root_manifest_for_wd(&cwd)?, &gctx)?;
1507 let current_package = ws.current().ok();
1508
1509 let current_package_dependencies = ws
1510 .current()
1511 .map(|current| current.dependencies())
1512 .unwrap_or_default()
1513 .to_vec();
1514 let all_other_packages_dependencies = ws
1515 .members()
1516 .filter(|&member| Some(member) != current_package)
1517 .flat_map(|pkg| pkg.dependencies().into_iter().cloned())
1518 .collect::<HashSet<_>>()
1519 .into_iter()
1520 .collect::<Vec<_>>();
1521
1522 Ok((
1523 current_package_dependencies,
1524 all_other_packages_dependencies,
1525 ))
1526}
1527
1528pub fn new_gctx_for_completions() -> CargoResult<GlobalContext> {
1529 let cwd = std::env::current_dir()?;
1530 let mut gctx = GlobalContext::new(shell::Shell::new(), cwd.clone(), cargo_home_with_cwd(&cwd)?);
1531
1532 let verbose = 0;
1533 let quiet = true;
1534 let color = None;
1535 let frozen = false;
1536 let locked = true;
1537 let offline = false;
1538 let target_dir = None;
1539 let unstable_flags = &[];
1540 let cli_config = &[];
1541
1542 gctx.configure(
1543 verbose,
1544 quiet,
1545 color,
1546 frozen,
1547 locked,
1548 offline,
1549 &target_dir,
1550 unstable_flags,
1551 cli_config,
1552 )?;
1553
1554 Ok(gctx)
1555}
1556
1557#[track_caller]
1558pub fn ignore_unknown<T: Default>(r: Result<T, clap::parser::MatchesError>) -> T {
1559 match r {
1560 Ok(t) => t,
1561 Err(clap::parser::MatchesError::UnknownArgument { .. }) => Default::default(),
1562 Err(e) => {
1563 panic!("Mismatch between definition and access: {}", e);
1564 }
1565 }
1566}
1567
1568#[derive(PartialEq, Eq, PartialOrd, Ord)]
1569pub enum CommandInfo {
1570 BuiltIn { about: Option<String> },
1571 External { path: PathBuf },
1572 Alias { target: StringOrVec },
1573}