Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Support specifing versions via crate_name@req #210

Merged
merged 6 commits into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 9 additions & 16 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,7 @@ pub enum BinstallError {
///
/// This may be the case when using the `--version` option.
///
/// Note that using `--version 1.2.3` is interpreted as the requirement `^1.2.3` as per
/// Cargo.toml rules. If you want the exact version 1.2.3, use `--version '=1.2.3'`.
/// Note that using `--version 1.2.3` is interpreted as the requirement `=1.2.3`.
///
/// - Code: `binstall::version::mismatch`
/// - Exit: 82
Expand All @@ -167,21 +166,15 @@ pub enum BinstallError {
v: semver::Version,
},

/// Warning: The resolved version may not be what was meant.
///
/// This occurs when using the `--version` option with a bare version, like `--version 1.2.3`.
/// That is parsed as the semver requirement `^1.2.3`, but the user may have expected that to
/// be an exact version (which should be specified with `--version '=1.2.3'`.
///
/// - Code: `binstall::version::warning`
/// - Exit: none (runtime warning only)
#[error("version semantic mismatch: {ver} <> {req}")]
/// This occurs when you specified `--version` while also using
/// form `$crate_name@$ver` tp specify version requirements.
#[error("duplicate version requirements")]
#[diagnostic(
severity(warning),
code(binstall::version::warning),
help("You specified `--version {req}` but the package resolved that to '{ver}'.\nUse `--version '={req}'` if you want an exact match.")
severity(error),
code(binstall::version::requirement),
help("Remove the `--version req` or simply use `$crate_name`")
)]
VersionWarning { ver: String, req: String },
DuplicateVersionReq,
}

impl BinstallError {
Expand All @@ -208,7 +201,7 @@ impl BinstallError {
VersionReq { .. } => 81,
VersionMismatch { .. } => 82,
VersionUnavailable { .. } => 83,
VersionWarning { .. } => unimplemented!("BUG: warnings do not terminate"),
DuplicateVersionReq => 84,
};

// reserved codes
Expand Down
3 changes: 3 additions & 0 deletions src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ pub use path_ext::*;
mod tls_version;
pub use tls_version::TLSVersion;

mod crate_name;
pub use crate_name::CrateName;

/// Load binstall metadata from the crate `Cargo.toml` at the provided path
pub fn load_manifest_path<P: AsRef<Path>>(
manifest_path: P,
Expand Down
39 changes: 39 additions & 0 deletions src/helpers/crate_name.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
use std::convert::Infallible;
use std::fmt;
use std::str::FromStr;

#[derive(Debug)]
pub struct CrateName {
pub name: String,
pub version: Option<String>,
}

impl fmt::Display for CrateName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name)?;

if let Some(version) = &self.version {
write!(f, "@{version}")?;
}

Ok(())
}
}

impl FromStr for CrateName {
type Err = Infallible;

fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(if let Some((name, version)) = s.split_once('@') {
CrateName {
name: name.to_string(),
version: Some(version.to_string()),
}
} else {
CrateName {
name: s.to_string(),
version: None,
}
})
}
}
53 changes: 28 additions & 25 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::{
ffi::OsString,
path::{Path, PathBuf},
process::{ExitCode, Termination},
str::FromStr,
time::{Duration, Instant},
};

Expand Down Expand Up @@ -36,14 +35,14 @@ struct Options {
///
/// This must be a crates.io package name.
#[clap(value_name = "crate")]
name: String,
crate_name: CrateName,

/// Semver filter to select the package version to install.
///
/// This is in Cargo.toml dependencies format: `--version 1.2.3` is equivalent to
/// `--version "^1.2.3"`. Use `=1.2.3` to install a specific version.
#[clap(long, default_value = "*")]
version: String,
#[clap(long)]
version: Option<String>,

/// Override binary target set.
///
Expand Down Expand Up @@ -237,34 +236,34 @@ async fn entry() -> Result<()> {
.map_err(BinstallError::from)
.wrap_err("Creating a temporary directory failed.")?;

info!("Installing package: '{}'", opts.name);
info!("Installing package: '{}'", opts.crate_name);

let mut version = match (&opts.crate_name.version, &opts.version) {
(Some(version), None) => version.to_string(),
(None, Some(version)) => version.to_string(),
(Some(_), Some(_)) => Err(BinstallError::DuplicateVersionReq)?,
(None, None) => "*".to_string(),
};

if version
.chars()
.next()
.map(|ch| ch.is_ascii_digit())
.unwrap_or(false)
{
version.insert(0, '=');
}

// Fetch crate via crates.io, git, or use a local manifest path
// TODO: work out which of these to do based on `opts.name`
// TODO: support git-based fetches (whole repo name rather than just crate name)
let manifest = match opts.manifest_path.clone() {
Some(manifest_path) => load_manifest_path(manifest_path.join("Cargo.toml"))?,
None => fetch_crate_cratesio(&client, &opts.name, &opts.version).await?,
None => fetch_crate_cratesio(&client, &opts.crate_name.name, &version).await?,
};

let package = manifest.package.unwrap();

let is_plain_version = semver::Version::from_str(&opts.version).is_ok();
if is_plain_version && package.version != opts.version {
warn!("Warning!");
eprintln!(
"{:?}",
miette::Report::new(BinstallError::VersionWarning {
ver: package.version.clone(),
req: opts.version.clone()
})
);

if !opts.dry_run {
uithread.confirm().await?;
}
}

let (mut meta, binaries) = (
package
.metadata
Expand Down Expand Up @@ -312,7 +311,9 @@ async fn entry() -> Result<()> {
meta.merge(&cli_overrides);

// Generate temporary binary path
let bin_path = temp_dir.path().join(format!("bin-{}", opts.name));
let bin_path = temp_dir
.path()
.join(format!("bin-{}", opts.crate_name.name));
debug!("Using temporary binary path: {}", bin_path.display());

let bin_files = collect_bin_files(
Expand Down Expand Up @@ -363,6 +364,7 @@ async fn entry() -> Result<()> {
opts,
package,
temp_dir,
version,
&bin_path,
&bin_files,
)
Expand Down Expand Up @@ -438,6 +440,7 @@ async fn install_from_package(
opts: Options,
package: Package<Meta>,
temp_dir: TempDir,
version: String,
bin_path: &Path,
bin_files: &[bins::BinFile],
) -> Result<()> {
Expand Down Expand Up @@ -478,7 +481,7 @@ async fn install_from_package(
}

let cvs = metafiles::CrateVersionSource {
name: opts.name,
name: opts.crate_name.name,
version: package.version.parse().into_diagnostic()?,
source: metafiles::Source::Registry(
url::Url::parse("https://github.com/rust-lang/crates.io-index").unwrap(),
Expand Down Expand Up @@ -521,7 +524,7 @@ async fn install_from_package(
c2.insert(
cvs.clone(),
metafiles::v2::CrateInfo {
version_req: Some(opts.version),
version_req: Some(version),
bins,
profile: "release".into(),
target: fetcher.target().to_string(),
Expand Down