1use self::super::ops::{PackageFilterElement, ConfigOperation};
16use semver::{VersionReq as SemverReq, Version as Semver};
17use clap::{AppSettings, SubCommand, App, Arg};
18use std::num::{ParseIntError, NonZero};
19use std::ffi::{OsString, OsStr};
20use std::path::{PathBuf, Path};
21use std::fmt::Arguments;
22use whoami::username_os;
23use std::process::exit;
24use std::str::FromStr;
25use std::borrow::Cow;
26use std::{env, fs};
27use home;
28
29
30#[derive(Debug, Clone, Hash, PartialEq, Eq)]
32pub struct Options {
33 pub to_update: Vec<(String, Option<Semver>, Cow<'static, str>)>,
35 pub all: bool,
37 pub update: bool,
39 pub install: bool,
41 pub force: bool,
43 pub downdate: bool,
45 pub update_git: bool,
47 pub quiet: bool,
49 pub locked: bool,
52 pub filter: Vec<PackageFilterElement>,
54 pub cargo_dir: (PathBuf, PathBuf),
57 pub temp_dir: PathBuf,
59 pub cargo_install_args: Vec<OsString>,
61 pub install_cargo: Option<OsString>,
63 pub jobs: Option<NonZero<usize>>,
65 pub recursive_jobs: Option<NonZero<usize>>,
67 pub concurrent_cargos: Option<NonZero<usize>>,
69}
70
71#[derive(Debug, Clone, Hash, PartialEq, Eq)]
73pub struct ConfigOptions {
74 pub cargo_dir: PathBuf,
76 pub package: String,
78 pub ops: Vec<ConfigOperation>,
80}
81
82
83impl Options {
84 pub fn parse() -> Options {
86 let nproc = std::thread::available_parallelism().unwrap_or(NonZero::new(1).unwrap());
87 let matches = App::new("cargo")
88 .bin_name("cargo")
89 .version(crate_version!())
90 .settings(&[AppSettings::ColoredHelp, AppSettings::ArgRequiredElseHelp, AppSettings::GlobalVersion, AppSettings::SubcommandRequired])
91 .subcommand(SubCommand::with_name("install-update")
92 .version(crate_version!())
93 .author("https://github.com/nabijaczleweli/cargo-update")
94 .about("A cargo subcommand for checking and applying updates to installed executables")
95 .args(&[Arg::from_usage("-c --cargo-dir=[CARGO_DIR] 'The cargo home directory. Default: $CARGO_HOME or $HOME/.cargo'")
96 .visible_alias("root")
97 .allow_invalid_utf8(true)
98 .validator(|s| existing_dir_validator("Cargo", &s)),
99 Arg::from_usage("-t --temp-dir=[TEMP_DIR] 'The temporary directory. Default: $TEMP/cargo-update'")
100 .validator(|s| existing_dir_validator("Temporary", &s)),
101 Arg::from_usage("-a --all 'Update all packages'"),
102 Arg::from_usage("-l --list 'Don't update packages, only list and check if they need an update (all packages by default)'"),
103 Arg::from_usage("-f --force 'Update all packages regardless if they need updating'"),
104 Arg::from_usage("-d --downdate 'Downdate packages to match latest unyanked registry version'"),
105 Arg::from_usage("-i --allow-no-update 'Allow for fresh-installing packages'"),
106 Arg::from_usage("-g --git 'Also update git packages'"),
107 Arg::from_usage("-q --quiet 'No output printed to stdout'"),
108 Arg::from_usage("--locked 'Enforce packages' embedded Cargo.lock'"),
109 Arg::from_usage("-s --filter=[PACKAGE_FILTER]... 'Specify a filter a package must match to be considered'")
110 .number_of_values(1)
111 .validator(|s| PackageFilterElement::parse(&s).map(|_| ())),
112 Arg::from_usage("-r --install-cargo=[EXECUTABLE] 'Specify an alternative cargo to run for installations'")
113 .number_of_values(1)
114 .allow_invalid_utf8(true),
115 Arg::from_usage(&format!("-j --jobs=[JOBS] 'Limit number of parallel jobs or \"default\" for {}'", nproc))
116 .number_of_values(1)
117 .validator(|s| jobs_parse(s, "default", nproc)),
118 Arg::from_usage(&format!("-J --recursive-jobs=[JOBS] 'Build up to JOBS crates at once on up to JOBS CPUs. {} if empty.'",
119 nproc))
120 .number_of_values(1)
121 .forbid_empty_values(false)
122 .default_missing_value("")
123 .validator(|s| jobs_parse(s, "", nproc)),
124 Arg::with_name("cargo_install_opts")
125 .long("__cargo_install_opts")
126 .env("CARGO_INSTALL_OPTS")
127 .allow_invalid_utf8(true)
128 .empty_values(false)
129 .multiple(true)
130 .value_delimiter(' ')
131 .hidden(true),
132 Arg::from_usage("[PACKAGE]... 'Packages to update'")
133 .empty_values(false)
134 .min_values(1)
135 .validator(|s| package_parse(s).map(|_| ()))]))
136 .get_matches();
137 let matches = matches.subcommand_matches("install-update").unwrap();
138
139 let all = matches.is_present("all");
140 let update = !matches.is_present("list");
141 let jobs_arg = matches.value_of("jobs").map(|j| jobs_parse(j, "default", nproc).unwrap());
142 let recursive_jobs = matches.value_of("recursive-jobs").map(|rj| jobs_parse(rj, "", nproc).unwrap());
143 Options {
144 to_update: match (all || !update, matches.values_of("PACKAGE")) {
145 (_, Some(pkgs)) => {
146 let mut packages: Vec<_> = pkgs.map(package_parse)
147 .map(Result::unwrap)
148 .map(|(package, version, registry)| {
149 (package.to_string(),
150 version,
151 registry.map(str::to_string).map(Cow::from).unwrap_or("https://github.com/rust-lang/crates.io-index".into()))
152 })
153 .collect();
154 packages.sort_by(|l, r| l.0.cmp(&r.0));
155 packages.dedup_by(|l, r| l.0 == r.0);
156 packages
157 }
158 (true, None) => vec![],
159 (false, None) => clerror(format_args!("Need at least one PACKAGE without --all")),
160 },
161 all: all,
162 update: update,
163 install: matches.is_present("allow-no-update"),
164 force: matches.is_present("force"),
165 downdate: matches.is_present("downdate"),
166 update_git: matches.is_present("git"),
167 quiet: matches.is_present("quiet"),
168 locked: matches.is_present("locked"),
169 filter: matches.values_of("filter").map(|pfs| pfs.flat_map(PackageFilterElement::parse).collect()).unwrap_or_default(),
170 cargo_dir: cargo_dir(matches.value_of_os("cargo-dir")),
171 temp_dir: {
172 if let Some(tmpdir) = matches.value_of("temp-dir") {
173 fs::canonicalize(tmpdir).unwrap()
174 } else {
175 env::temp_dir()
176 }
177 .join(Path::new("cargo-update").with_extension(username_os()))
178 },
179 cargo_install_args: matches.values_of_os("cargo_install_opts").into_iter().flat_map(|cio| cio.map(OsStr::to_os_string)).collect(),
180 install_cargo: matches.value_of_os("install-cargo").map(OsStr::to_os_string),
181 jobs: if recursive_jobs.is_some() {
182 None
183 } else {
184 jobs_arg
185 },
186 recursive_jobs: recursive_jobs,
187 concurrent_cargos: match (jobs_arg, recursive_jobs) {
188 (Some(j), Some(rj)) => Some(NonZero::new((rj.get() + (j.get() - 1)) / j).unwrap_or(NonZero::new(1).unwrap())),
189 _ => None,
190 },
191 }
192 }
193}
194
195impl ConfigOptions {
196 pub fn parse() -> ConfigOptions {
198 let matches = App::new("cargo")
199 .bin_name("cargo")
200 .version(crate_version!())
201 .settings(&[AppSettings::ColoredHelp, AppSettings::ArgRequiredElseHelp, AppSettings::GlobalVersion, AppSettings::SubcommandRequired])
202 .subcommand(SubCommand::with_name("install-update-config")
203 .version(crate_version!())
204 .author("https://github.com/nabijaczleweli/cargo-update")
205 .about("A cargo subcommand for checking and applying updates to installed executables -- configuration")
206 .args(&[Arg::from_usage("-c --cargo-dir=[CARGO_DIR] 'The cargo home directory. Default: $CARGO_HOME or $HOME/.cargo'")
207 .validator(|s| existing_dir_validator("Cargo", &s)),
208 Arg::from_usage("-t --toolchain=[TOOLCHAIN] 'Toolchain to use or empty for default'"),
209 Arg::from_usage("-f --feature=[FEATURE]... 'Feature to enable'").number_of_values(1),
210 Arg::from_usage("-n --no-feature=[DISABLED_FEATURE]... 'Feature to disable'").number_of_values(1),
211 Arg::from_usage("-d --default-features=[DEFAULT_FEATURES] 'Whether to allow default features'")
212 .possible_values(&["1", "yes", "true", "0", "no", "false"])
213 .hide_possible_values(true),
214 Arg::from_usage("--debug 'Compile the package in debug (\"dev\") mode'").conflicts_with("release").conflicts_with("build-profile"),
215 Arg::from_usage("--release 'Compile the package in release mode'").conflicts_with("debug").conflicts_with("build-profile"),
216 Arg::from_usage("--build-profile=[PROFILE] 'Compile the package in the given profile'")
217 .conflicts_with("debug")
218 .conflicts_with("release"),
219 Arg::from_usage("--install-prereleases 'Install prerelease versions'").conflicts_with("no-install-prereleases"),
220 Arg::from_usage("--no-install-prereleases 'Filter out prerelease versions'").conflicts_with("install-prereleases"),
221 Arg::from_usage("--enforce-lock 'Require Cargo.lock to be up to date'").conflicts_with("no-enforce-lock"),
222 Arg::from_usage("--no-enforce-lock 'Don't enforce Cargo.lock'").conflicts_with("enforce-lock"),
223 Arg::from_usage("--respect-binaries 'Only install already installed binaries'").conflicts_with("no-respect-binaries"),
224 Arg::from_usage("--no-respect-binaries 'Install all binaries'").conflicts_with("respect-binaries"),
225 Arg::from_usage("-v --version=[VERSION_REQ] 'Require a cargo-compatible version range'")
226 .validator(|s| SemverReq::from_str(&s).map(|_| ()).map_err(|e| e.to_string()))
227 .conflicts_with("any-version"),
228 Arg::from_usage("-a --any-version 'Allow any version'").conflicts_with("version"),
229 Arg::from_usage("-e --environment=[VARIABLE=VALUE]... 'Environment variable to set'")
230 .number_of_values(1)
231 .validator(|s| if s.contains('=') {
232 Ok(())
233 } else {
234 Err("Missing VALUE")
235 }),
236 Arg::from_usage("-E --clear-environment=[VARIABLE]... 'Environment variable to clear'")
237 .number_of_values(1)
238 .validator(|s| if s.contains('=') {
239 Err("VARIABLE can't contain a =")
240 } else {
241 Ok(())
242 }),
243 Arg::from_usage("--inherit-environment=[VARIABLE]... 'Environment variable to use from the environment'")
244 .number_of_values(1)
245 .validator(|s| if s.contains('=') {
246 Err("VARIABLE can't contain a =")
247 } else {
248 Ok(())
249 }),
250 Arg::from_usage("-r --reset 'Roll back the configuration to the defaults.'"),
251 Arg::from_usage("<PACKAGE> 'Package to configure'").empty_values(false)]))
252 .get_matches();
253 let matches = matches.subcommand_matches("install-update-config").unwrap();
254
255 ConfigOptions {
256 cargo_dir: cargo_dir(matches.value_of_os("cargo-dir")).1,
257 package: matches.value_of("PACKAGE").unwrap().to_string(),
258 ops: matches.value_of("toolchain")
259 .map(|t| if t.is_empty() {
260 ConfigOperation::RemoveToolchain
261 } else {
262 ConfigOperation::SetToolchain(t.to_string())
263 })
264 .into_iter()
265 .chain(matches.values_of("feature").into_iter().flatten().map(str::to_string).map(ConfigOperation::AddFeature))
266 .chain(matches.values_of("no-feature").into_iter().flatten().map(str::to_string).map(ConfigOperation::RemoveFeature))
267 .chain(matches.value_of("default-features").map(|d| ["1", "yes", "true"].contains(&d)).map(ConfigOperation::DefaultFeatures).into_iter())
268 .chain(match (matches.is_present("debug"), matches.is_present("release"), matches.value_of("build-profile")) {
269 (true, _, _) => Some(ConfigOperation::SetBuildProfile("dev".into())),
270 (_, true, _) => Some(ConfigOperation::SetBuildProfile("release".into())),
271 (_, _, Some(prof)) => Some(ConfigOperation::SetBuildProfile(prof.to_string().into())),
272 _ => None,
273 })
274 .chain(match (matches.is_present("install-prereleases"), matches.is_present("no-install-prereleases")) {
275 (true, _) => Some(ConfigOperation::SetInstallPrereleases(true)),
276 (_, true) => Some(ConfigOperation::SetInstallPrereleases(false)),
277 _ => None,
278 })
279 .chain(match (matches.is_present("enforce-lock"), matches.is_present("no-enforce-lock")) {
280 (true, _) => Some(ConfigOperation::SetEnforceLock(true)),
281 (_, true) => Some(ConfigOperation::SetEnforceLock(false)),
282 _ => None,
283 })
284 .chain(match (matches.is_present("respect-binaries"), matches.is_present("no-respect-binaries")) {
285 (true, _) => Some(ConfigOperation::SetRespectBinaries(true)),
286 (_, true) => Some(ConfigOperation::SetRespectBinaries(false)),
287 _ => None,
288 })
289 .chain(match (matches.is_present("any-version"), matches.value_of("version")) {
290 (true, _) => Some(ConfigOperation::RemoveTargetVersion),
291 (false, Some(vr)) => Some(ConfigOperation::SetTargetVersion(SemverReq::from_str(vr).unwrap())),
292 _ => None,
293 })
294 .chain(matches.values_of("environment")
295 .into_iter()
296 .flatten()
297 .map(|s| s.split_once('=').unwrap())
298 .map(|(k, v)| ConfigOperation::SetEnvironment(k.to_string(), v.to_string())))
299 .chain(matches.values_of("clear-environment").into_iter().flatten().map(str::to_string).map(ConfigOperation::ClearEnvironment))
300 .chain(matches.values_of("inherit-environment").into_iter().flatten().map(str::to_string).map(ConfigOperation::InheritEnvironment))
301 .chain(matches.index_of("reset").map(|_| ConfigOperation::ResetConfig))
302 .collect(),
303 }
304 }
305}
306
307fn cargo_dir(opt_cargo_dir: Option<&OsStr>) -> (PathBuf, PathBuf) {
308 if let Some(dir) = opt_cargo_dir {
309 match fs::canonicalize(&dir) {
310 Ok(cdir) => (dir.into(), cdir),
311 Err(_) => clerror(format_args!("--cargo-dir={:?} doesn't exist", dir)),
312 }
313 } else {
314 match env::var_os("CARGO_INSTALL_ROOT")
315 .map(PathBuf::from)
316 .or_else(|| home::cargo_home().ok())
317 .and_then(|ch| fs::canonicalize(&ch).map(|can| (ch, can)).ok()) {
318 Some(cd) => cd,
319 None => {
320 clerror(format_args!("$CARGO_INSTALL_ROOT, $CARGO_HOME, and home directory invalid, please specify the cargo home directory with the -c \
321 option"))
322 }
323 }
324 }
325}
326
327fn existing_dir_validator(label: &str, s: &str) -> Result<(), String> {
328 fs::canonicalize(s).map(|_| ()).map_err(|_| format!("{} directory \"{}\" not found", label, s))
329}
330
331fn package_parse(mut s: &str) -> Result<(&str, Option<Semver>, Option<&str>), String> {
332 let mut registry_url = None;
333 if s.starts_with('(') {
334 if let Some(idx) = s.find("):") {
335 registry_url = Some(&s[1..idx]);
336 s = &s[idx + 2..];
337 }
338 }
339
340 if let Some(idx) = s.find(':') {
341 Ok((&s[0..idx],
342 Some(Semver::parse(&s[idx + 1..]).map_err(|e| format!("Version {} provided for package {} invalid: {}", &s[idx + 1..], &s[0..idx], e))?),
343 registry_url))
344 } else {
345 Ok((s, None, registry_url))
346 }
347}
348
349fn jobs_parse(s: &str, special: &str, default: NonZero<usize>) -> Result<NonZero<usize>, ParseIntError> {
350 if s != special {
351 NonZero::<usize>::from_str(s)
352 } else {
353 Ok(default)
354 }
355}
356
357
358fn clerror(f: Arguments) -> ! {
359 eprintln!("{}", f);
360 exit(1)
361}