Support new feature batch installation!

Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
This commit is contained in:
Jiahao XU 2022-07-18 16:46:51 +10:00
parent 5e7aab7373
commit 7f11b74f5e
No known key found for this signature in database
GPG key ID: 591C0B03040416D6

View file

@ -1,7 +1,8 @@
use std::{ use std::{
collections::BTreeSet, collections::BTreeSet,
ffi::OsString, ffi::OsString,
path::{Path, PathBuf}, mem::take,
path::PathBuf,
process::{ExitCode, Termination}, process::{ExitCode, Termination},
sync::Arc, sync::Arc,
time::{Duration, Instant}, time::{Duration, Instant},
@ -37,7 +38,7 @@ struct Options {
/// ///
/// This must be a crates.io package name. /// This must be a crates.io package name.
#[clap(value_name = "crate")] #[clap(value_name = "crate")]
crate_name: CrateName, crate_names: Vec<CrateName>,
/// Semver filter to select the package version to install. /// Semver filter to select the package version to install.
/// ///
@ -204,6 +205,7 @@ async fn entry() -> Result<()> {
pkg_fmt: opts.pkg_fmt.take(), pkg_fmt: opts.pkg_fmt.take(),
bin_dir: opts.bin_dir.take(), bin_dir: opts.bin_dir.take(),
}); });
let crate_names = take(&mut opts.crate_names);
let opts = Arc::new(opts); let opts = Arc::new(opts);
// Initialize reqwest client // Initialize reqwest client
@ -239,24 +241,30 @@ async fn entry() -> Result<()> {
.map_err(BinstallError::from) .map_err(BinstallError::from)
.wrap_err("Creating a temporary directory failed.")?; .wrap_err("Creating a temporary directory failed.")?;
let resolution = resolve( let tasks: Vec<_> = crate_names
.into_iter()
.map(|crate_name| {
tokio::spawn(resolve(
opts.clone(), opts.clone(),
opts.crate_name.clone(), crate_name,
desired_targets.clone(), desired_targets.clone(),
cli_overrides.clone(), cli_overrides.clone(),
temp_dir.path().to_path_buf(), temp_dir.path().to_path_buf(),
install_path.clone(), install_path.clone(),
client.clone(), client.clone(),
) ))
.await?; })
.collect();
let mut resolutions = Vec::with_capacity(tasks.len());
for task in tasks {
resolutions.push(await_task(task).await??);
}
for resolution in &resolutions {
match resolution { match resolution {
Resolution::Fetch { Resolution::Fetch {
fetcher, fetcher, bin_files, ..
package,
version,
bin_path,
bin_files,
} => { } => {
let fetcher_target = fetcher.target(); let fetcher_target = fetcher.target();
// Prompt user for confirmation // Prompt user for confirmation
@ -278,66 +286,84 @@ async fn entry() -> Result<()> {
} }
info!("This will install the following binaries:"); info!("This will install the following binaries:");
for file in &bin_files { for file in bin_files {
info!(" - {}", file.preview_bin()); info!(" - {}", file.preview_bin());
} }
if !opts.no_symlinks { if !opts.no_symlinks {
info!("And create (or update) the following symlinks:"); info!("And create (or update) the following symlinks:");
for file in &bin_files { for file in bin_files {
info!(" - {}", file.preview_link()); info!(" - {}", file.preview_link());
} }
} }
}
Resolution::InstallFromSource { .. } => {
warn!("The package will be installed from source (with cargo)",)
}
}
}
if !opts.dry_run { if !opts.dry_run {
uithread.confirm().await?; uithread.confirm().await?;
} }
install_from_package(
fetcher.as_ref(),
opts,
package,
temp_dir,
version,
&bin_path,
&bin_files,
)
.await
}
Resolution::InstallFromSource { package } => {
if !opts.no_cleanup {
temp_dir.close().unwrap_or_else(|err| {
warn!("Failed to clean up some resources: {err}");
});
}
let desired_targets = desired_targets.get().await; let desired_targets = desired_targets.get().await;
let target = desired_targets let target = desired_targets
.first() .first()
.ok_or_else(|| miette!("No viable targets found, try with `--targets`"))?; .ok_or_else(|| miette!("No viable targets found, try with `--targets`"))?;
// Prompt user for source install let tasks: Vec<_> = resolutions
warn!("The package will be installed from source (with cargo)",); .into_iter()
.map(|resolution| match resolution {
Resolution::Fetch {
fetcher,
package,
crate_name,
version,
bin_path,
bin_files,
} => tokio::spawn(install_from_package(
fetcher,
opts.clone(),
package,
crate_name,
temp_dir.path().to_path_buf(),
version,
bin_path,
bin_files,
)),
Resolution::InstallFromSource { package } => {
if !opts.dry_run { if !opts.dry_run {
uithread.confirm().await?; tokio::spawn(install_from_source(package, target.clone()))
install_from_source(package, target).await
} else { } else {
info!( info!(
"Dry-run: running `cargo install {} --version {} --target {target}`", "Dry-run: running `cargo install {} --version {} --target {target}`",
package.name, package.version package.name, package.version
); );
tokio::spawn(async { Ok(()) })
}
}
})
.collect();
for task in tasks {
await_task(task).await??;
}
if !opts.no_cleanup {
temp_dir.close().unwrap_or_else(|err| {
warn!("Failed to clean up some resources: {err}");
});
}
Ok(()) Ok(())
} }
}
}
}
enum Resolution { enum Resolution {
Fetch { Fetch {
fetcher: Arc<dyn Fetcher>, fetcher: Arc<dyn Fetcher>,
package: Package<Meta>, package: Package<Meta>,
crate_name: CrateName,
version: String, version: String,
bin_path: PathBuf, bin_path: PathBuf,
bin_files: Vec<bins::BinFile>, bin_files: Vec<bins::BinFile>,
@ -446,6 +472,7 @@ async fn resolve(
Ok(Resolution::Fetch { Ok(Resolution::Fetch {
fetcher, fetcher,
package, package,
crate_name,
version, version,
bin_path, bin_path,
bin_files, bin_files,
@ -498,20 +525,22 @@ fn collect_bin_files(
Ok(bin_files) Ok(bin_files)
} }
#[allow(unused, clippy::too_many_arguments)]
async fn install_from_package( async fn install_from_package(
fetcher: &dyn Fetcher, fetcher: Arc<dyn Fetcher>,
opts: Arc<Options>, opts: Arc<Options>,
package: Package<Meta>, package: Package<Meta>,
temp_dir: TempDir, crate_name: CrateName,
temp_dir: PathBuf,
version: String, version: String,
bin_path: &Path, bin_path: PathBuf,
bin_files: &[bins::BinFile], bin_files: Vec<bins::BinFile>,
) -> Result<()> { ) -> Result<()> {
// Download package // Download package
if opts.dry_run { if opts.dry_run {
info!("Dry run, not downloading package"); info!("Dry run, not downloading package");
} else { } else {
fetcher.fetch_and_extract(bin_path).await?; fetcher.fetch_and_extract(&bin_path).await?;
} }
#[cfg(incomplete)] #[cfg(incomplete)]
@ -528,7 +557,7 @@ async fn install_from_package(
debug!("Fetching signature file: {sig_url}"); debug!("Fetching signature file: {sig_url}");
// Download signature file // Download signature file
let sig_path = temp_dir.path().join(format!("{pkg_name}.sig")); let sig_path = temp_dir.join(format!("{pkg_name}.sig"));
download(&sig_url, &sig_path).await?; download(&sig_url, &sig_path).await?;
// TODO: do the signature check // TODO: do the signature check
@ -544,7 +573,7 @@ async fn install_from_package(
} }
let cvs = metafiles::CrateVersionSource { let cvs = metafiles::CrateVersionSource {
name: opts.crate_name.name.clone(), name: crate_name.name.clone(),
version: package.version.parse().into_diagnostic()?, version: package.version.parse().into_diagnostic()?,
source: metafiles::Source::Registry( source: metafiles::Source::Registry(
url::Url::parse("https://github.com/rust-lang/crates.io-index").unwrap(), url::Url::parse("https://github.com/rust-lang/crates.io-index").unwrap(),
@ -553,25 +582,17 @@ async fn install_from_package(
info!("Installing binaries..."); info!("Installing binaries...");
block_in_place(|| { block_in_place(|| {
for file in bin_files { for file in &bin_files {
file.install_bin()?; file.install_bin()?;
} }
// Generate symlinks // Generate symlinks
if !opts.no_symlinks { if !opts.no_symlinks {
for file in bin_files { for file in &bin_files {
file.install_link()?; file.install_link()?;
} }
} }
if opts.no_cleanup {
let _ = temp_dir.into_path();
} else {
temp_dir.close().unwrap_or_else(|err| {
warn!("Failed to clean up some resources: {err}");
});
}
let bins: BTreeSet<String> = bin_files.iter().map(|bin| bin.base_name.clone()).collect(); let bins: BTreeSet<String> = bin_files.iter().map(|bin| bin.base_name.clone()).collect();
{ {
@ -602,7 +623,7 @@ async fn install_from_package(
}) })
} }
async fn install_from_source(package: Package<Meta>, target: &str) -> Result<()> { async fn install_from_source(package: Package<Meta>, target: String) -> Result<()> {
debug!( debug!(
"Running `cargo install {} --version {} --target {target}`", "Running `cargo install {} --version {} --target {target}`",
package.name, package.version package.name, package.version