1use std::fs;
2use std::path::PathBuf;
3
4use crate::core::compiler::{BuildConfig, MessageFormat};
5use crate::core::Workspace;
6use crate::ops::{CompileFilter, CompileOptions, NewOptions, Packages, VersionControl};
7use crate::sources::CRATES_IO_REGISTRY;
8use crate::util::important_paths::find_root_manifest_for_wd;
9use crate::util::{paths, validate_package_name};
10use crate::CargoResult;
11use clap::{self, SubCommand};
12
13pub use crate::core::compiler::CompileMode;
14pub use crate::{CliError, CliResult, Config};
15pub use clap::{AppSettings, Arg, ArgMatches};
16
17pub type App = clap::App<'static, 'static>;
18
19pub trait AppExt: Sized {
20 fn _arg(self, arg: Arg<'static, 'static>) -> Self;
21
22 fn arg_package_spec(
23 self,
24 package: &'static str,
25 all: &'static str,
26 exclude: &'static str,
27 ) -> Self {
28 self.arg_package_spec_simple(package)
29 ._arg(opt("all", all))
30 ._arg(multi_opt("exclude", "SPEC", exclude))
31 }
32
33 fn arg_package_spec_simple(self, package: &'static str) -> Self {
34 self._arg(multi_opt("package", "SPEC", package).short("p"))
35 }
36
37 fn arg_package(self, package: &'static str) -> Self {
38 self._arg(opt("package", package).short("p").value_name("SPEC"))
39 }
40
41 fn arg_jobs(self) -> Self {
42 self._arg(
43 opt("jobs", "Number of parallel jobs, defaults to # of CPUs")
44 .short("j")
45 .value_name("N"),
46 )
47 }
48
49 fn arg_targets_all(
50 self,
51 lib: &'static str,
52 bin: &'static str,
53 bins: &'static str,
54 example: &'static str,
55 examples: &'static str,
56 test: &'static str,
57 tests: &'static str,
58 bench: &'static str,
59 benches: &'static str,
60 all: &'static str,
61 ) -> Self {
62 self.arg_targets_lib_bin(lib, bin, bins)
63 ._arg(multi_opt("example", "NAME", example))
64 ._arg(opt("examples", examples))
65 ._arg(multi_opt("test", "NAME", test))
66 ._arg(opt("tests", tests))
67 ._arg(multi_opt("bench", "NAME", bench))
68 ._arg(opt("benches", benches))
69 ._arg(opt("all-targets", all))
70 }
71
72 fn arg_targets_lib_bin(self, lib: &'static str, bin: &'static str, bins: &'static str) -> Self {
73 self._arg(opt("lib", lib))
74 ._arg(multi_opt("bin", "NAME", bin))
75 ._arg(opt("bins", bins))
76 }
77
78 fn arg_targets_bins_examples(
79 self,
80 bin: &'static str,
81 bins: &'static str,
82 example: &'static str,
83 examples: &'static str,
84 ) -> Self {
85 self._arg(multi_opt("bin", "NAME", bin))
86 ._arg(opt("bins", bins))
87 ._arg(multi_opt("example", "NAME", example))
88 ._arg(opt("examples", examples))
89 }
90
91 fn arg_targets_bin_example(self, bin: &'static str, example: &'static str) -> Self {
92 self._arg(multi_opt("bin", "NAME", bin))
93 ._arg(multi_opt("example", "NAME", example))
94 }
95
96 fn arg_features(self) -> Self {
97 self._arg(
98 opt("features", "Space-separated list of features to activate").value_name("FEATURES"),
99 )
100 ._arg(opt("all-features", "Activate all available features"))
101 ._arg(opt(
102 "no-default-features",
103 "Do not activate the `default` feature",
104 ))
105 }
106
107 fn arg_release(self, release: &'static str) -> Self {
108 self._arg(opt("release", release))
109 }
110
111 fn arg_doc(self, doc: &'static str) -> Self {
112 self._arg(opt("doc", doc))
113 }
114
115 fn arg_target_triple(self, target: &'static str) -> Self {
116 self._arg(opt("target", target).value_name("TRIPLE"))
117 }
118
119 fn arg_target_dir(self) -> Self {
120 self._arg(
121 opt("target-dir", "Directory for all generated artifacts").value_name("DIRECTORY"),
122 )
123 }
124
125 fn arg_manifest_path(self) -> Self {
126 self._arg(opt("manifest-path", "Path to Cargo.toml").value_name("PATH"))
127 }
128
129 fn arg_message_format(self) -> Self {
130 self._arg(
131 opt("message-format", "Error format")
132 .value_name("FMT")
133 .case_insensitive(true)
134 .possible_values(&["human", "json", "short"])
135 .default_value("human"),
136 )
137 }
138
139 fn arg_build_plan(self) -> Self {
140 self._arg(opt("build-plan", "Output the build plan in JSON"))
141 }
142
143 fn arg_new_opts(self) -> Self {
144 self._arg(
145 opt(
146 "vcs",
147 "\
148 Initialize a new repository for the given version \
149 control system (git, hg, pijul, or fossil) or do not \
150 initialize any version control at all (none), overriding \
151 a global configuration.",
152 )
153 .value_name("VCS")
154 .possible_values(&["git", "hg", "pijul", "fossil", "none"]),
155 )
156 ._arg(opt("bin", "Use a binary (application) template [default]"))
157 ._arg(opt("lib", "Use a library template"))
158 ._arg(
159 opt("edition", "Edition to set for the crate generated")
160 .possible_values(&["2015", "2018"])
161 .value_name("YEAR"),
162 )
163 ._arg(
164 opt(
165 "name",
166 "Set the resulting package name, defaults to the directory name",
167 )
168 .value_name("NAME"),
169 )
170 }
171
172 fn arg_index(self) -> Self {
173 self._arg(opt("index", "Registry index to upload the package to").value_name("INDEX"))
174 ._arg(
175 opt("host", "DEPRECATED, renamed to '--index'")
176 .value_name("HOST")
177 .hidden(true),
178 )
179 }
180
181 fn arg_dry_run(self, dry_run: &'static str) -> Self {
182 self._arg(opt("dry-run", dry_run))
183 }
184}
185
186impl AppExt for App {
187 fn _arg(self, arg: Arg<'static, 'static>) -> Self {
188 self.arg(arg)
189 }
190}
191
192pub fn opt(name: &'static str, help: &'static str) -> Arg<'static, 'static> {
193 Arg::with_name(name).long(name).help(help)
194}
195
196pub fn multi_opt(
197 name: &'static str,
198 value_name: &'static str,
199 help: &'static str,
200) -> Arg<'static, 'static> {
201 opt(name, help)
206 .value_name(value_name)
207 .multiple(true)
208 .number_of_values(1)
209}
210
211pub fn subcommand(name: &'static str) -> App {
212 SubCommand::with_name(name).settings(&[
213 AppSettings::UnifiedHelpMessage,
214 AppSettings::DeriveDisplayOrder,
215 AppSettings::DontCollapseArgsInUsage,
216 ])
217}
218
219pub trait ArgMatchesExt {
220 fn value_of_u32(&self, name: &str) -> CargoResult<Option<u32>> {
221 let arg = match self._value_of(name) {
222 None => None,
223 Some(arg) => Some(arg.parse::<u32>().map_err(|_| {
224 clap::Error::value_validation_auto(format!("could not parse `{}` as a number", arg))
225 })?),
226 };
227 Ok(arg)
228 }
229
230 fn value_of_path(&self, name: &str, config: &Config) -> Option<PathBuf> {
232 self._value_of(name).map(|path| config.cwd().join(path))
233 }
234
235 fn root_manifest(&self, config: &Config) -> CargoResult<PathBuf> {
236 if let Some(path) = self.value_of_path("manifest-path", config) {
237 let path = paths::normalize_path(&path);
240 if !path.ends_with("Cargo.toml") {
241 failure::bail!("the manifest-path must be a path to a Cargo.toml file")
242 }
243 if fs::metadata(&path).is_err() {
244 failure::bail!(
245 "manifest path `{}` does not exist",
246 self._value_of("manifest-path").unwrap()
247 )
248 }
249 return Ok(path);
250 }
251 find_root_manifest_for_wd(config.cwd())
252 }
253
254 fn workspace<'a>(&self, config: &'a Config) -> CargoResult<Workspace<'a>> {
255 let root = self.root_manifest(config)?;
256 let mut ws = Workspace::new(&root, config)?;
257 if config.cli_unstable().avoid_dev_deps {
258 ws.set_require_optional_deps(false);
259 }
260 Ok(ws)
261 }
262
263 fn jobs(&self) -> CargoResult<Option<u32>> {
264 self.value_of_u32("jobs")
265 }
266
267 fn target(&self) -> Option<String> {
268 self._value_of("target").map(|s| s.to_string())
269 }
270
271 fn compile_options<'a>(
272 &self,
273 config: &'a Config,
274 mode: CompileMode,
275 ) -> CargoResult<CompileOptions<'a>> {
276 let spec = Packages::from_flags(
277 self._is_present("all"),
278 self._values_of("exclude"),
279 self._values_of("package"),
280 )?;
281
282 let message_format = match self._value_of("message-format") {
283 None => MessageFormat::Human,
284 Some(f) => {
285 if f.eq_ignore_ascii_case("json") {
286 MessageFormat::Json
287 } else if f.eq_ignore_ascii_case("human") {
288 MessageFormat::Human
289 } else if f.eq_ignore_ascii_case("short") {
290 MessageFormat::Short
291 } else {
292 panic!("Impossible message format: {:?}", f)
293 }
294 }
295 };
296
297 let mut build_config = BuildConfig::new(config, self.jobs()?, &self.target(), mode)?;
298 build_config.message_format = message_format;
299 build_config.release = self._is_present("release");
300 build_config.build_plan = self._is_present("build-plan");
301 if build_config.build_plan && !config.cli_unstable().unstable_options {
302 Err(failure::format_err!(
303 "`--build-plan` flag is unstable, pass `-Z unstable-options` to enable it"
304 ))?;
305 };
306
307 let opts = CompileOptions {
308 config,
309 build_config,
310 features: self._values_of("features"),
311 all_features: self._is_present("all-features"),
312 no_default_features: self._is_present("no-default-features"),
313 spec,
314 filter: CompileFilter::new(
315 self._is_present("lib"),
316 self._values_of("bin"),
317 self._is_present("bins"),
318 self._values_of("test"),
319 self._is_present("tests"),
320 self._values_of("example"),
321 self._is_present("examples"),
322 self._values_of("bench"),
323 self._is_present("benches"),
324 self._is_present("all-targets"),
325 ),
326 target_rustdoc_args: None,
327 target_rustc_args: None,
328 local_rustdoc_args: None,
329 export_dir: None,
330 };
331 Ok(opts)
332 }
333
334 fn compile_options_for_single_package<'a>(
335 &self,
336 config: &'a Config,
337 mode: CompileMode,
338 ) -> CargoResult<CompileOptions<'a>> {
339 let mut compile_opts = self.compile_options(config, mode)?;
340 compile_opts.spec = Packages::Packages(self._values_of("package"));
341 Ok(compile_opts)
342 }
343
344 fn new_options(&self, config: &Config) -> CargoResult<NewOptions> {
345 let vcs = self._value_of("vcs").map(|vcs| match vcs {
346 "git" => VersionControl::Git,
347 "hg" => VersionControl::Hg,
348 "pijul" => VersionControl::Pijul,
349 "fossil" => VersionControl::Fossil,
350 "none" => VersionControl::NoVcs,
351 vcs => panic!("Impossible vcs: {:?}", vcs),
352 });
353 NewOptions::new(
354 vcs,
355 self._is_present("bin"),
356 self._is_present("lib"),
357 self.value_of_path("path", config).unwrap(),
358 self._value_of("name").map(|s| s.to_string()),
359 self._value_of("edition").map(|s| s.to_string()),
360 self.registry(config)?,
361 )
362 }
363
364 fn registry(&self, config: &Config) -> CargoResult<Option<String>> {
365 match self._value_of("registry") {
366 Some(registry) => {
367 if !config.cli_unstable().unstable_options {
368 return Err(failure::format_err!(
369 "registry option is an unstable feature and \
370 requires -Zunstable-options to use."
371 ));
372 }
373 validate_package_name(registry, "registry name", "")?;
374
375 if registry == CRATES_IO_REGISTRY {
376 Ok(None)
382 } else {
383 Ok(Some(registry.to_string()))
384 }
385 }
386 None => config.default_registry(),
387 }
388 }
389
390 fn index(&self, config: &Config) -> CargoResult<Option<String>> {
391 let msg = "The flag '--host' is no longer valid.
397
398Previous versions of Cargo accepted this flag, but it is being
399deprecated. The flag is being renamed to 'index', as the flag
400wants the location of the index. Please use '--index' instead.
401
402This will soon become a hard error, so it's either recommended
403to update to a fixed version or contact the upstream maintainer
404about this warning.";
405
406 let index = match self._value_of("host") {
407 Some(host) => {
408 config.shell().warn(&msg)?;
409 Some(host.to_string())
410 }
411 None => self._value_of("index").map(|s| s.to_string()),
412 };
413 Ok(index)
414 }
415
416 fn _value_of(&self, name: &str) -> Option<&str>;
417
418 fn _values_of(&self, name: &str) -> Vec<String>;
419
420 fn _is_present(&self, name: &str) -> bool;
421}
422
423impl<'a> ArgMatchesExt for ArgMatches<'a> {
424 fn _value_of(&self, name: &str) -> Option<&str> {
425 self.value_of(name)
426 }
427
428 fn _values_of(&self, name: &str) -> Vec<String> {
429 self.values_of(name)
430 .unwrap_or_default()
431 .map(|s| s.to_string())
432 .collect()
433 }
434
435 fn _is_present(&self, name: &str) -> bool {
436 self.is_present(name)
437 }
438}
439
440pub fn values(args: &ArgMatches<'_>, name: &str) -> Vec<String> {
441 args.values_of(name)
442 .unwrap_or_default()
443 .map(|s| s.to_string())
444 .collect()
445}
446
447#[derive(PartialEq, PartialOrd, Eq, Ord)]
448pub enum CommandInfo {
449 BuiltIn { name: String, about: Option<String> },
450 External { name: String, path: PathBuf },
451}
452
453impl CommandInfo {
454 pub fn name(&self) -> String {
455 match self {
456 CommandInfo::BuiltIn { name, .. } => name.to_string(),
457 CommandInfo::External { name, .. } => name.to_string(),
458 }
459 }
460}