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