Skip to content

Commit 9379325

Browse files
committed
refactor(install): Move version parsing to the CLI
1 parent 28b7c84 commit 9379325

File tree

4 files changed

+78
-73
lines changed

4 files changed

+78
-73
lines changed

src/bin/cargo/commands/install.rs

Lines changed: 58 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
use crate::command_prelude::*;
22

33
use anyhow::anyhow;
4+
use anyhow::bail;
5+
use anyhow::format_err;
46
use cargo::core::{GitReference, SourceId, Workspace};
57
use cargo::ops;
68
use cargo::util::IntoUrl;
9+
use cargo::util::ToSemver;
10+
use cargo::util::VersionReqExt;
11+
use cargo::CargoResult;
12+
use semver::VersionReq;
713

814
use cargo_util::paths;
915

@@ -15,6 +21,7 @@ pub fn cli() -> Command {
1521
opt("version", "Specify a version to install")
1622
.alias("vers")
1723
.value_name("VERSION")
24+
.value_parser(parse_semver_flag)
1825
.requires("crate"),
1926
)
2027
.arg(
@@ -98,7 +105,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
98105
// but not `Config::reload_rooted_at` which is always cwd)
99106
let path = path.map(|p| paths::normalize_path(&p));
100107

101-
let version = args.get_one::<String>("version").map(String::as_str);
108+
let version = args.get_one::<VersionReq>("version");
102109
let krates = args
103110
.get_many::<CrateVersion>("crate")
104111
.unwrap_or_default()
@@ -187,7 +194,7 @@ pub fn exec(config: &mut Config, args: &ArgMatches) -> CliResult {
187194
Ok(())
188195
}
189196

190-
type CrateVersion = (String, Option<String>);
197+
type CrateVersion = (String, Option<VersionReq>);
191198

192199
fn parse_crate(krate: &str) -> crate::CargoResult<CrateVersion> {
193200
let (krate, version) = if let Some((k, v)) = krate.split_once('@') {
@@ -196,7 +203,7 @@ fn parse_crate(krate: &str) -> crate::CargoResult<CrateVersion> {
196203
anyhow::bail!("missing crate name before '@'");
197204
}
198205
let krate = k.to_owned();
199-
let version = Some(v.to_owned());
206+
let version = Some(parse_semver_flag(v)?);
200207
(krate, version)
201208
} else {
202209
let krate = krate.to_owned();
@@ -211,14 +218,58 @@ fn parse_crate(krate: &str) -> crate::CargoResult<CrateVersion> {
211218
Ok((krate, version))
212219
}
213220

221+
/// Parses x.y.z as if it were =x.y.z, and gives CLI-specific error messages in the case of invalid
222+
/// values.
223+
fn parse_semver_flag(v: &str) -> CargoResult<VersionReq> {
224+
// If the version begins with character <, >, =, ^, ~ parse it as a
225+
// version range, otherwise parse it as a specific version
226+
let first = v
227+
.chars()
228+
.next()
229+
.ok_or_else(|| format_err!("no version provided for the `--version` flag"))?;
230+
231+
let is_req = "<>=^~".contains(first) || v.contains('*');
232+
if is_req {
233+
match v.parse::<VersionReq>() {
234+
Ok(v) => Ok(v),
235+
Err(_) => bail!(
236+
"the `--version` provided, `{}`, is \
237+
not a valid semver version requirement\n\n\
238+
Please have a look at \
239+
https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html \
240+
for the correct format",
241+
v
242+
),
243+
}
244+
} else {
245+
match v.to_semver() {
246+
Ok(v) => Ok(VersionReq::exact(&v)),
247+
Err(e) => {
248+
let mut msg = e.to_string();
249+
250+
// If it is not a valid version but it is a valid version
251+
// requirement, add a note to the warning
252+
if v.parse::<VersionReq>().is_ok() {
253+
msg.push_str(&format!(
254+
"\n\n tip: if you want to specify semver range, \
255+
add an explicit qualifier, like '^{}'",
256+
v
257+
));
258+
}
259+
bail!(msg);
260+
}
261+
}
262+
}
263+
}
264+
214265
fn resolve_crate(
215266
krate: String,
216-
local_version: Option<String>,
217-
version: Option<&str>,
267+
local_version: Option<VersionReq>,
268+
version: Option<&VersionReq>,
218269
) -> crate::CargoResult<CrateVersion> {
219270
let version = match (local_version, version) {
220-
(Some(l), Some(g)) => {
221-
anyhow::bail!("cannot specify both `@{l}` and `--version {g}`");
271+
(Some(_), Some(_)) => {
272+
anyhow::bail!("cannot specify both `@<VERSION>` and `--version <VERSION>`");
222273
}
223274
(Some(l), None) => Some(l),
224275
(None, Some(g)) => Some(g.to_owned()),

src/cargo/ops/cargo_install.rs

Lines changed: 14 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,10 @@ use crate::ops::{common_for_install_and_uninstall::*, FilterRule};
1111
use crate::ops::{CompileFilter, Packages};
1212
use crate::sources::{GitSource, PathSource, SourceConfigMap};
1313
use crate::util::errors::CargoResult;
14-
use crate::util::{Config, Filesystem, Rustc, ToSemver, VersionReqExt};
14+
use crate::util::{Config, Filesystem, Rustc};
1515
use crate::{drop_println, ops};
1616

17-
use anyhow::{bail, format_err, Context as _};
17+
use anyhow::{bail, Context as _};
1818
use cargo_util::paths;
1919
use itertools::Itertools;
2020
use semver::VersionReq;
@@ -38,12 +38,12 @@ impl Drop for Transaction {
3838
}
3939
}
4040

41-
struct InstallablePackage<'cfg, 'a> {
41+
struct InstallablePackage<'cfg> {
4242
config: &'cfg Config,
4343
opts: ops::CompileOptions,
4444
root: Filesystem,
4545
source_id: SourceId,
46-
vers: Option<&'a str>,
46+
vers: Option<VersionReq>,
4747
force: bool,
4848
no_track: bool,
4949

@@ -53,7 +53,7 @@ struct InstallablePackage<'cfg, 'a> {
5353
target: String,
5454
}
5555

56-
impl<'cfg, 'a> InstallablePackage<'cfg, 'a> {
56+
impl<'cfg> InstallablePackage<'cfg> {
5757
// Returns pkg to install. None if pkg is already installed
5858
pub fn new(
5959
config: &'cfg Config,
@@ -62,12 +62,12 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> {
6262
krate: Option<&str>,
6363
source_id: SourceId,
6464
from_cwd: bool,
65-
vers: Option<&'a str>,
66-
original_opts: &'a ops::CompileOptions,
65+
vers: Option<&VersionReq>,
66+
original_opts: &ops::CompileOptions,
6767
force: bool,
6868
no_track: bool,
6969
needs_update_if_source_is_index: bool,
70-
) -> CargoResult<Option<InstallablePackage<'cfg, 'a>>> {
70+
) -> CargoResult<Option<Self>> {
7171
if let Some(name) = krate {
7272
if name == "." {
7373
bail!(
@@ -82,8 +82,8 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> {
8282
let pkg = {
8383
let dep = {
8484
if let Some(krate) = krate {
85-
let vers = if let Some(vers_flag) = vers {
86-
Some(parse_semver_flag(vers_flag)?.to_string())
85+
let vers = if let Some(vers) = vers {
86+
Some(vers.to_string())
8787
} else if source_id.is_registry() {
8888
// Avoid pre-release versions from crate.io
8989
// unless explicitly asked for
@@ -234,7 +234,7 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> {
234234
opts,
235235
root,
236236
source_id,
237-
vers,
237+
vers: vers.cloned(),
238238
force,
239239
no_track,
240240

@@ -604,7 +604,7 @@ Consider enabling some of the needed features by passing, e.g., `--features=\"{e
604604
pub fn install(
605605
config: &Config,
606606
root: Option<&str>,
607-
krates: Vec<(String, Option<String>)>,
607+
krates: Vec<(String, Option<VersionReq>)>,
608608
source_id: SourceId,
609609
from_cwd: bool,
610610
opts: &ops::CompileOptions,
@@ -619,7 +619,7 @@ pub fn install(
619619
let (krate, vers) = krates
620620
.iter()
621621
.next()
622-
.map(|(k, v)| (Some(k.as_str()), v.as_deref()))
622+
.map(|(k, v)| (Some(k.as_str()), v.as_ref()))
623623
.unwrap_or((None, None));
624624
let installable_pkg = InstallablePackage::new(
625625
config, root, map, krate, source_id, from_cwd, vers, opts, force, no_track, true,
@@ -648,7 +648,7 @@ pub fn install(
648648
Some(krate.as_str()),
649649
source_id,
650650
from_cwd,
651-
vers.as_deref(),
651+
vers.as_ref(),
652652
opts,
653653
force,
654654
no_track,
@@ -805,54 +805,6 @@ fn make_ws_rustc_target<'cfg>(
805805
Ok((ws, rustc, target))
806806
}
807807

808-
/// Parses x.y.z as if it were =x.y.z, and gives CLI-specific error messages in the case of invalid
809-
/// values.
810-
fn parse_semver_flag(v: &str) -> CargoResult<VersionReq> {
811-
// If the version begins with character <, >, =, ^, ~ parse it as a
812-
// version range, otherwise parse it as a specific version
813-
let first = v
814-
.chars()
815-
.next()
816-
.ok_or_else(|| format_err!("no version provided for the `--version` flag"))?;
817-
818-
let is_req = "<>=^~".contains(first) || v.contains('*');
819-
if is_req {
820-
match v.parse::<VersionReq>() {
821-
Ok(v) => Ok(v),
822-
Err(_) => bail!(
823-
"the `--version` provided, `{}`, is \
824-
not a valid semver version requirement\n\n\
825-
Please have a look at \
826-
https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html \
827-
for the correct format",
828-
v
829-
),
830-
}
831-
} else {
832-
match v.to_semver() {
833-
Ok(v) => Ok(VersionReq::exact(&v)),
834-
Err(e) => {
835-
let mut msg = format!(
836-
"the `--version` provided, `{}`, is \
837-
not a valid semver version: {}\n",
838-
v, e
839-
);
840-
841-
// If it is not a valid version but it is a valid version
842-
// requirement, add a note to the warning
843-
if v.parse::<VersionReq>().is_ok() {
844-
msg.push_str(&format!(
845-
"\nif you want to specify semver range, \
846-
add an explicit qualifier, like ^{}",
847-
v
848-
));
849-
}
850-
bail!(msg);
851-
}
852-
}
853-
}
854-
}
855-
856808
/// Display a list of installed binaries.
857809
pub fn install_list(dst: Option<&str>, config: &Config) -> CargoResult<()> {
858810
let root = resolve_root(dst, config)?;

tests/testsuite/install.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1617,7 +1617,7 @@ fn inline_and_explicit_version() {
16171617

16181618
cargo_process("install [email protected] --version 0.1.1")
16191619
.with_status(101)
1620-
.with_stderr("error: cannot specify both `@0.1.1` and `--version 0.1.1`")
1620+
.with_stderr("error: cannot specify both `@<VERSION>` and `--version <VERSION>`")
16211621
.run();
16221622
}
16231623

tests/testsuite/install_upgrade.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -230,12 +230,14 @@ fn ambiguous_version_no_longer_allowed() {
230230
cargo_process("install foo --version=1.0")
231231
.with_stderr(
232232
"\
233-
[ERROR] the `--version` provided, `1.0`, is not a valid semver version: cannot parse '1.0' as a semver
233+
[ERROR] invalid value '1.0' for '--version <VERSION>': cannot parse '1.0' as a semver
234234
235-
if you want to specify semver range, add an explicit qualifier, like ^1.0
235+
tip: if you want to specify semver range, add an explicit qualifier, like '^1.0'
236+
237+
For more information, try '--help'.
236238
",
237239
)
238-
.with_status(101)
240+
.with_status(1)
239241
.run();
240242
}
241243

0 commit comments

Comments
 (0)