1use clap::builder::{ValueParser, TypedValueParser, NonEmptyStringValueParser, PossibleValue};
16use clap::error::{Error as ClapError, ErrorKind as ClapErrorKind};
17use self::super::ops::{PackageFilterElement, ConfigOperation};
18use semver::{VersionReq as SemverReq, Version as Semver};
19use chrono::{TimeDelta, DateTime, Utc};
20use clap::{Command, Arg, ArgAction};
21use std::ffi::{OsString, OsStr};
22use std::path::{PathBuf, Path};
23use std::fmt::Arguments;
24use whoami::username_os;
25use std::process::exit;
26use std::str::FromStr;
27use std::num::NonZero;
28use std::borrow::Cow;
29use std::{env, fs};
30use home;
31
32
33#[derive(Debug, Clone, Hash, PartialEq, Eq)]
35pub struct Options {
36 pub to_update: Vec<(String, Option<Semver>, Cow<'static, str>)>,
38 pub all: bool,
40 pub update: bool,
42 pub install: bool,
44 pub force: bool,
46 pub downdate: bool,
48 pub update_git: bool,
50 pub quiet: bool,
52 pub locked: bool,
55 pub released_after: Option<DateTime<Utc>>,
57 pub filter: Vec<PackageFilterElement>,
59 pub cargo_dir: (PathBuf, PathBuf),
62 pub temp_dir: PathBuf,
64 pub cargo_install_args: Vec<OsString>,
66 pub install_cargo: Option<OsString>,
68 pub jobs: Option<NonZero<usize>>,
70 pub recursive_jobs: Option<NonZero<usize>>,
72 pub concurrent_cargos: Option<NonZero<usize>>,
74}
75
76#[derive(Debug, Clone, Hash, PartialEq, Eq)]
78pub struct ConfigOptions {
79 pub cargo_dir: PathBuf,
81 pub package: String,
83 pub ops: Vec<ConfigOperation>,
85}
86
87
88impl Options {
89 pub fn parse() -> Options {
91 let nproc = std::thread::available_parallelism().unwrap_or(NonZero::new(1).unwrap());
92 let mut matches = Command::new("cargo")
93 .bin_name("cargo")
94 .version(crate_version!())
95 .arg_required_else_help(true)
96 .subcommand_required(true)
97 .args_override_self(true)
98 .subcommand(Command::new("install-update")
99 .version(crate_version!())
100 .author("https://github.com/nabijaczleweli/cargo-update")
101 .about("A cargo subcommand for checking and applying updates to installed executables")
102 .args(&[arg!(-c --"cargo-dir" <CARGO_DIR> "The cargo home directory. Default: $CARGO_HOME or $HOME/.cargo")
103 .required(false)
104 .action(ArgAction::Set)
105 .visible_alias("root")
106 .value_parser(ExistingDirParser("Cargo")),
107 arg!(-t --"temp-dir" <TEMP_DIR> "The temporary directory. Default: $TEMP/cargo-update")
108 .required(false)
109 .action(ArgAction::Set)
110 .value_parser(ExistingDirParser("Temporary")),
111 arg!(-a --"all" "Update all packages").action(ArgAction::SetTrue),
112 arg!(-l --"list" "Don't update packages, only list and check if they need an update (all packages by default)")
113 .action(ArgAction::SetTrue),
114 arg!(-f --"force" "Update all packages regardless if they need updating").action(ArgAction::SetTrue),
115 arg!(-d --"downdate" "Downdate packages to match latest unyanked registry version").action(ArgAction::SetTrue),
116 arg!(-i --"allow-no-update" "Allow for fresh-installing packages").action(ArgAction::SetTrue),
117 arg!(-g --"git" "Also update git packages").action(ArgAction::SetTrue),
118 arg!(-q --"quiet" "No output printed to stdout").action(ArgAction::SetTrue),
119 arg!(--"locked" "Enforce packages' embedded Cargo.lock").action(ArgAction::SetTrue),
120 arg!(--"cooldown" <TIME> "Only consider versions released before (now - TIME). Seconds, [smhdwy] suffix.")
121 .required(false)
122 .action(ArgAction::Set)
123 .num_args(1)
124 .value_parser(duration_parse),
125 arg!(-s --"filter" <PACKAGE_FILTER>... "Specify a filter a package must match to be considered")
126 .required(false)
127 .action(ArgAction::Append)
128 .num_args(1)
129 .value_parser(PackageFilterElement::parse),
130 arg!(-r --"install-cargo" <EXECUTABLE> "Specify an alternative cargo to run for installations")
131 .required(false)
132 .action(ArgAction::Set)
133 .num_args(1)
134 .value_parser(ValueParser::os_string()),
135 arg!(-j --"jobs" <JOBS>)
136 .help(format!("Limit number of parallel jobs or \"default\" for {}", nproc))
137 .required(false)
138 .num_args(1)
139 .value_parser(JobsParser("default", nproc)),
140 arg!(-J --"recursive-jobs" [JOBS])
141 .help(format!("Build up to JOBS crates at once on up to JOBS CPUs. {} if empty.", nproc))
142 .required(false)
143 .value_parser(JobsParser("", nproc)),
144 Arg::new("cargo_install_opts")
145 .long("__cargo_install_opts")
146 .env("CARGO_INSTALL_OPTS")
147 .action(ArgAction::Set)
148 .value_parser(ValueParser::os_string())
149 .value_delimiter(' ')
150 .hide(true),
151 arg!(<PACKAGE>... "Packages to update")
152 .action(ArgAction::Append)
153 .required(false)
154 .value_parser(package_parse)]))
155 .get_matches_mut();
156 let (_, mut matches) = matches.remove_subcommand().unwrap();
157
158 let all = matches.remove_one("all").unwrap_or(false);
159 let update = !matches.remove_one("list").unwrap_or(false);
160 let jobs_arg = matches.remove_one("jobs");
161 let recursive_jobs = matches.remove_one("recursive-jobs");
162 Options {
163 to_update: match (all || !update, matches.remove_many::<(String, Option<Semver>, Option<String>)>("PACKAGE")) {
164 (_, Some(pkgs)) => {
165 let mut packages: Vec<_> = pkgs.map(|(package, version, registry)| {
166 (package, version, registry.map(Cow::from).unwrap_or("https://github.com/rust-lang/crates.io-index".into()))
167 })
168 .collect();
169 packages.sort_by(|l, r| l.0.cmp(&r.0));
170 packages.dedup_by(|l, r| l.0 == r.0);
171 packages
172 }
173 (true, None) => vec![],
174 (false, None) => clerror(format_args!("Need at least one PACKAGE without --all")),
175 },
176 all: all,
177 update: update,
178 install: matches.remove_one("allow-no-update").unwrap_or(false),
179 force: matches.remove_one("force").unwrap_or(false),
180 downdate: matches.remove_one("downdate").unwrap_or(false),
181 update_git: matches.remove_one("git").unwrap_or(false),
182 quiet: matches.remove_one("quiet").unwrap_or(false),
183 released_after: matches.get_one::<TimeDelta>("cooldown")
184 .map(|&td| {
185 Utc::now().checked_sub_signed(td).unwrap_or_else(|| {
186 let raw = matches.get_raw("cooldown").unwrap_or_default().last().unwrap();
187 clerror(format_args!("--cooldown {}: (now - {}) out of range", Path::new(raw).display(), td)) })
189 }),
190 locked: matches.remove_one("locked").unwrap_or(false),
191 filter: matches.remove_many("filter").into_iter().flatten().collect(),
192 cargo_dir: cargo_dir(matches.remove_one("cargo-dir")),
193 temp_dir: matches.remove_one("temp-dir").unwrap_or_else(env::temp_dir).join(Path::new("cargo-update").with_extension(username_os())),
194 cargo_install_args: matches.remove_many("cargo_install_opts").into_iter().flatten().filter(|a: &OsString| !a.is_empty()).collect(),
195 install_cargo: matches.remove_one("install-cargo"),
196 jobs: if recursive_jobs.is_some() {
197 None
198 } else {
199 jobs_arg
200 },
201 recursive_jobs: recursive_jobs,
202 concurrent_cargos: match (jobs_arg, recursive_jobs) {
203 (Some(j), Some(rj)) => Some(NonZero::new((rj.get() + (j.get() - 1)) / j).unwrap_or(NonZero::new(1).unwrap())),
204 _ => None,
205 },
206 }
207 }
208}
209
210impl ConfigOptions {
211 pub fn parse() -> ConfigOptions {
213 let mut matches = Command::new("cargo")
214 .bin_name("cargo")
215 .version(crate_version!())
216 .arg_required_else_help(true)
218 .subcommand_required(true)
219 .subcommand(Command::new("install-update-config")
220 .disable_version_flag(true)
221 .version(crate_version!())
222 .author("https://github.com/nabijaczleweli/cargo-update")
223 .about("A cargo subcommand for checking and applying updates to installed executables -- configuration")
224 .args(&[arg!(-c --"cargo-dir" <CARGO_DIR> "The cargo home directory. Default: $CARGO_HOME or $HOME/.cargo").required(false)
225 .value_parser(ExistingDirParser("Cargo")),
226 arg!(-t --"toolchain" <TOOLCHAIN> "Toolchain to use or empty for default")
227 .num_args(1).required(false).value_parser(ValueParser::string()),
228 arg!(-f --"feature" <FEATURE>... "Feature to enable").num_args(1).required(false).value_parser(ValueParser::string()),
229 arg!(-n --"no-feature" <DISABLED_FEATURE>... "Feature to disable").num_args(1).required(false).value_parser(ValueParser::string()),
230 arg!(-d --"default-features" <DEFAULT_FEATURES> "Whether to allow default features").num_args(1).required(false)
231 .value_parser(DefaultFeaturesBoolParser)
232 .hide_possible_values(true),
233 arg!(--"debug" "Compile the package in debug (\"dev\") mode")
234 .action(ArgAction::SetTrue).conflicts_with("release").conflicts_with("build-profile"),
235 arg!(--"release" "Compile the package in release mode")
236 .action(ArgAction::SetTrue).conflicts_with("debug").conflicts_with("build-profile"),
237 arg!(--"build-profile" <PROFILE> "Compile the package in the given profile").num_args(1).required(false)
238 .conflicts_with("debug")
239 .conflicts_with("release").value_parser(ValueParser::string()),
240 arg!(--"install-prereleases" "Install prerelease versions").action(ArgAction::SetTrue).conflicts_with("no-install-prereleases"),
241 arg!(--"no-install-prereleases" "Filter out prerelease versions").action(ArgAction::SetTrue).conflicts_with("install-prereleases"),
242 arg!(--"enforce-lock" "Require Cargo.lock to be up to date").action(ArgAction::SetTrue).conflicts_with("no-enforce-lock"),
243 arg!(--"no-enforce-lock" "Don't enforce Cargo.lock").action(ArgAction::SetTrue).conflicts_with("enforce-lock"),
244 arg!(--"respect-binaries" "Only install already installed binaries").action(ArgAction::SetTrue).conflicts_with("no-respect-binaries"),
245 arg!(--"no-respect-binaries" "Install all binaries").action(ArgAction::SetTrue).conflicts_with("respect-binaries"),
246 arg!(-v --"version" <VERSION_REQ> "Require a cargo-compatible version range").num_args(1).required(false)
247 .value_parser(SemverReq::from_str)
248 .conflicts_with("any-version"),
249 arg!(-a --"any-version" "Allow any version").action(ArgAction::SetTrue).conflicts_with("version"),
250 arg!(-e --"environment" <VARIABLE_EQ_TODO_VALUE>... "Environment variable to set").required(false)
251 .num_args(1)
252 .value_parser(|s: &str| if let Some((k,v)) = s.split_once('=') {
253 Ok((k.to_string(), v.to_string()))
254 } else {
255 Err("Missing VALUE")
256 }),
257 arg!(-E --"clear-environment" <VARIABLE>... "Environment variable to clear").required(false)
258 .num_args(1)
259 .value_parser(|s: &str| if s.contains('=') {
260 Err("VARIABLE can't contain a =")
261 } else {
262 Ok(s.to_string())
263 }),
264 arg!(--"inherit-environment" <VARIABLE>... "Environment variable to use from the environment").required(false)
265 .num_args(1)
266 .value_parser(|s: &str| if s.contains('=') {
267 Err("VARIABLE can't contain a =")
268 } else {
269 Ok(s.to_string())
270 }),
271 arg!(-r --"reset" "Roll back the configuration to the defaults.").action(ArgAction::SetTrue),
272 arg!(<PACKAGE> "Package to configure").value_parser(NonEmptyStringValueParser ::new())
273 ]))
274 .get_matches_mut();
275 let (_, mut matches) = matches.remove_subcommand().unwrap();
276
277 ConfigOptions {
278 cargo_dir: cargo_dir(matches.remove_one("cargo-dir")).1,
279 package: matches.remove_one("PACKAGE").unwrap(),
280 ops: matches.remove_one("toolchain")
281 .map(|t: String| if t.is_empty() {
282 ConfigOperation::RemoveToolchain
283 } else {
284 ConfigOperation::SetToolchain(t)
285 })
286 .into_iter()
287 .chain(matches.remove_many("feature").into_iter().flatten().map(ConfigOperation::AddFeature))
288 .chain(matches.remove_many("no-feature").into_iter().flatten().map(ConfigOperation::RemoveFeature))
289 .chain(matches.remove_one("default-features").map(ConfigOperation::DefaultFeatures))
290 .chain(match (matches.remove_one("debug").unwrap_or(false),
291 matches.remove_one("release").unwrap_or(false),
292 matches.remove_one::<String>("build-profile")) {
293 (true, _, _) => Some(ConfigOperation::SetBuildProfile("dev".into())),
294 (_, true, _) => Some(ConfigOperation::SetBuildProfile("release".into())),
295 (_, _, Some(prof)) => Some(ConfigOperation::SetBuildProfile(prof.into())),
296 _ => None,
297 })
298 .chain(match (matches.remove_one("install-prereleases").unwrap_or(false), matches.remove_one("no-install-prereleases").unwrap_or(false)) {
299 (true, _) => Some(ConfigOperation::SetInstallPrereleases(true)),
300 (_, true) => Some(ConfigOperation::SetInstallPrereleases(false)),
301 _ => None,
302 })
303 .chain(match (matches.remove_one("enforce-lock").unwrap_or(false), matches.remove_one("no-enforce-lock").unwrap_or(false)) {
304 (true, _) => Some(ConfigOperation::SetEnforceLock(true)),
305 (_, true) => Some(ConfigOperation::SetEnforceLock(false)),
306 _ => None,
307 })
308 .chain(match (matches.remove_one("respect-binaries").unwrap_or(false), matches.remove_one("no-respect-binaries").unwrap_or(false)) {
309 (true, _) => Some(ConfigOperation::SetRespectBinaries(true)),
310 (_, true) => Some(ConfigOperation::SetRespectBinaries(false)),
311 _ => None,
312 })
313 .chain(match (matches.remove_one("any-version").unwrap_or(false), matches.remove_one("version")) {
314 (true, _) => Some(ConfigOperation::RemoveTargetVersion),
315 (false, Some(vr)) => Some(ConfigOperation::SetTargetVersion(vr)),
316 _ => None,
317 })
318 .chain(matches.remove_many("environment")
319 .into_iter()
320 .flatten()
321 .map(|(k, v)| ConfigOperation::SetEnvironment(k, v)))
322 .chain(matches.remove_many("clear-environment").into_iter().flatten().map(ConfigOperation::ClearEnvironment))
323 .chain(matches.remove_many("inherit-environment").into_iter().flatten().map(ConfigOperation::InheritEnvironment))
324 .chain(if matches.remove_one("reset").unwrap_or(false) {
325 Some(ConfigOperation::ResetConfig)
326 } else {
327 None
328 })
329 .collect(),
330 }
331 }
332}
333
334fn cargo_dir(opt_cargo_dir: Option<PathBuf>) -> (PathBuf, PathBuf) {
335 if let Some(dir) = opt_cargo_dir {
336 match fs::canonicalize(&dir) {
337 Ok(cdir) => (dir.into(), cdir),
338 Err(_) => clerror(format_args!("--cargo-dir={:?} doesn't exist", dir)),
339 }
340 } else {
341 match env::var_os("CARGO_INSTALL_ROOT")
342 .map(PathBuf::from)
343 .or_else(|| home::cargo_home().ok())
344 .and_then(|ch| fs::canonicalize(&ch).map(|can| (ch, can)).ok()) {
345 Some(cd) => cd,
346 None => {
347 clerror(format_args!("$CARGO_INSTALL_ROOT, $CARGO_HOME, and home directory invalid, please specify the cargo home directory with the -c \
348 option"))
349 }
350 }
351 }
352}
353
354#[derive(Copy, Clone)]
355struct ExistingDirParser(&'static str);
356impl TypedValueParser for ExistingDirParser {
357 type Value = PathBuf;
358
359 fn parse_ref(&self, cmd: &Command, arg: Option<&Arg>, value: &OsStr) -> Result<Self::Value, ClapError> {
360 fs::canonicalize(value).map_err(|_| {
361 ClapError::raw(ClapErrorKind::InvalidValue,
362 format_args!("{}: {} directory \"{}\" not found", arg.unwrap(), self.0, Path::new(value).display())) .with_cmd(cmd)
364 })
365 }
366}
367
368fn package_parse(mut s: &str) -> Result<(String, Option<Semver>, Option<String>), String> {
369 let mut registry_url = None;
370 if s.starts_with('(') {
371 if let Some(idx) = s.find("):") {
372 registry_url = Some(&s[1..idx]);
373 s = &s[idx + 2..];
374 }
375 }
376
377 if let Some(idx) = s.find(':') {
378 Ok((s[0..idx].to_string(),
379 Some(Semver::parse(&s[idx + 1..]).map_err(|e| format!("Version {} provided for package {} invalid: {}", &s[idx + 1..], &s[0..idx], e))?),
380 registry_url.map(str::to_string)))
381 } else {
382 Ok((s.to_string(), None, registry_url.map(str::to_string)))
383 }
384}
385
386fn duration_parse(s: &str) -> Result<TimeDelta, String> {
387 const MULS_S: [char; 6] = ['y', 'w', 'd', 'h', 'm', 's'];
388 const MULS_V: [f64; 6] = [365.25 / 7., 7., 24., 60., 60., 1.];
389 let (base, mul) = s.strip_suffix(MULS_S).map(|stripped| (stripped, *s.as_bytes().last().unwrap() as _)).unwrap_or((s, 's'));
390 let base = f64::from_str(base).map_err(|e| e.to_string())?;
391 let val = MULS_V[MULS_S.iter().position(|&c| c == mul).unwrap()..].iter().fold(base, |a, e| a * e);
392 let (s, ns) = (val.trunc() as i64, (val.fract() * 1_000_000_000.0) as u32);
393 TimeDelta::new(s, ns).ok_or_else(|| format!("{}.{:09} too big", s, ns))
394}
395
396#[derive(Copy, Clone)]
397struct JobsParser(&'static str, NonZero<usize>);
398impl TypedValueParser for JobsParser {
399 type Value = NonZero<usize>;
400 fn parse_ref(&self, cmd: &Command, arg: Option<&Arg>, value: &OsStr) -> Result<Self::Value, ClapError> {
401 let value = value.to_str().ok_or(ClapError::new(ClapErrorKind::InvalidValue).with_cmd(cmd))?;
402 let Self(special, default) = *self;
403
404 if value != special {
405 if value.starts_with("-") {
406 NonZero::from_str(&value[1..]).map(|sub| if sub >= default {
407 NonZero::new(1).unwrap()
408 } else {
409 NonZero::new(default.get() - sub.get()).unwrap()
410 })
411 } else {
412 NonZero::from_str(value)
413 }
414 .map_err(|e| ClapError::raw(ClapErrorKind::InvalidValue, format_args!("{}: {}", arg.unwrap(), e)).with_cmd(cmd))
415 } else {
416 Ok(default)
417 }
418 }
419}
420
421#[derive(Copy, Clone)]
422struct DefaultFeaturesBoolParser;
423impl TypedValueParser for DefaultFeaturesBoolParser {
424 type Value = bool;
425
426 fn parse_ref(&self, cmd: &Command, arg: Option<&Arg>, value: &OsStr) -> Result<Self::Value, ClapError> {
427 match value.to_str().ok_or(ClapError::new(ClapErrorKind::InvalidValue).with_cmd(cmd))? {
428 "1" | "yes" | "true" => Ok(true),
429 "0" | "no" | "false" => Ok(false),
430 value => {
431 Err(ClapError::raw(ClapErrorKind::InvalidValue,
432 format_args!("{}: {} not 1|yes|true or 0|no|false", arg.unwrap(), value))
433 .with_cmd(cmd))
434 }
435 }
436 }
437
438 fn possible_values(&self) -> Option<Box<dyn Iterator<Item = PossibleValue> + '_>> {
439 Some(Box::new(["1", "yes", "true", "0", "no", "false"].iter().map(PossibleValue::new)))
440 }
441}
442
443
444fn clerror(f: Arguments) -> ! {
445 eprintln!("{}", f);
446 exit(1)
447}