Merge branch 'main' into feature/bin-multi-targets

This commit is contained in:
Jiahao XU 2022-06-07 16:38:14 +10:00 committed by GitHub
commit 6f7c8fa8ab
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 69 additions and 30 deletions

View file

@ -1,8 +1,10 @@
use std::path::Path;
use std::sync::Arc;
pub use gh_crate_meta::*;
pub use log::debug;
pub use quickinstall::*;
use tokio::task::JoinHandle;
use crate::{BinstallError, PkgFmt, PkgMeta};
@ -10,9 +12,9 @@ mod gh_crate_meta;
mod quickinstall;
#[async_trait::async_trait]
pub trait Fetcher {
pub trait Fetcher: Send + Sync {
/// Create a new fetcher from some data
async fn new(data: &Data) -> Box<Self>
async fn new(data: &Data) -> Arc<Self>
where
Self: Sized;
@ -47,30 +49,59 @@ pub struct Data {
#[derive(Default)]
pub struct MultiFetcher {
fetchers: Vec<Box<dyn Fetcher>>,
fetchers: Vec<Arc<dyn Fetcher>>,
}
impl MultiFetcher {
pub fn add(&mut self, fetcher: Box<dyn Fetcher>) {
pub fn add(&mut self, fetcher: Arc<dyn Fetcher>) {
self.fetchers.push(fetcher);
}
pub async fn first_available(&self) -> Option<&dyn Fetcher> {
for fetcher in &self.fetchers {
let available = fetcher.check().await.unwrap_or_else(|err| {
debug!(
"Error while checking fetcher {}: {}",
fetcher.source_name(),
err
);
false
});
pub async fn first_available(&self) -> Option<Arc<dyn Fetcher>> {
let handles: Vec<_> = self
.fetchers
.iter()
.cloned()
.map(|fetcher| {
let fetcher_cloned = fetcher.clone();
if available {
return Some(&**fetcher);
(
AutoAbortJoinHandle(tokio::spawn(async move { fetcher.check().await })),
fetcher_cloned,
)
})
.collect();
for (mut handle, fetcher) in handles {
match (&mut handle.0).await {
Ok(Ok(true)) => return Some(fetcher),
Ok(Ok(false)) => (),
Ok(Err(err)) => {
debug!(
"Error while checking fetcher {}: {}",
fetcher.source_name(),
err
);
}
Err(join_err) => {
debug!(
"Error while checking fetcher {}: {}",
fetcher.source_name(),
join_err
);
}
}
}
None
}
}
#[derive(Debug)]
struct AutoAbortJoinHandle(JoinHandle<Result<bool, BinstallError>>);
impl Drop for AutoAbortJoinHandle {
fn drop(&mut self) {
self.0.abort();
}
}

View file

@ -1,4 +1,5 @@
use std::path::Path;
use std::sync::Arc;
use log::{debug, info, warn};
use reqwest::Method;
@ -22,8 +23,8 @@ impl GhCrateMeta {
#[async_trait::async_trait]
impl super::Fetcher for GhCrateMeta {
async fn new(data: &Data) -> Box<Self> {
Box::new(Self { data: data.clone() })
async fn new(data: &Data) -> Arc<Self> {
Arc::new(Self { data: data.clone() })
}
async fn check(&self) -> Result<bool, BinstallError> {
@ -36,7 +37,7 @@ impl super::Fetcher for GhCrateMeta {
}
info!("Checking for package at: '{url}'");
remote_exists(url.as_str(), Method::HEAD).await
remote_exists(url, Method::HEAD).await
}
async fn fetch(&self, dst: &Path) -> Result<(), BinstallError> {

View file

@ -1,4 +1,5 @@
use std::path::Path;
use std::sync::Arc;
use log::info;
use reqwest::Method;
@ -18,11 +19,11 @@ pub struct QuickInstall {
#[async_trait::async_trait]
impl super::Fetcher for QuickInstall {
async fn new(data: &Data) -> Box<Self> {
async fn new(data: &Data) -> Arc<Self> {
let crate_name = &data.name;
let version = &data.version;
let target = data.target.clone();
Box::new(Self {
Arc::new(Self {
package: format!("{crate_name}-{version}-{target}"),
target,
})
@ -32,7 +33,7 @@ impl super::Fetcher for QuickInstall {
let url = self.package_url();
self.report().await?;
info!("Checking for package at: '{url}'");
remote_exists(&url, Method::HEAD).await
remote_exists(Url::parse(&url)?, Method::HEAD).await
}
async fn fetch(&self, dst: &Path) -> Result<(), BinstallError> {

View file

@ -32,8 +32,7 @@ pub fn load_manifest_path<P: AsRef<Path>>(
Ok(manifest)
}
pub async fn remote_exists(url: &str, method: Method) -> Result<bool, BinstallError> {
let url = Url::parse(url)?;
pub async fn remote_exists(url: Url, method: Method) -> Result<bool, BinstallError> {
let req = reqwest::Client::new()
.request(method.clone(), url.clone())
.send()

View file

@ -11,7 +11,7 @@ use miette::{miette, IntoDiagnostic, Result, WrapErr};
use simplelog::{ColorChoice, ConfigBuilder, TermLogger, TerminalMode};
use structopt::StructOpt;
use tempfile::TempDir;
use tokio::{process::Command, runtime::Runtime};
use tokio::{process::Command, runtime::Runtime, task::JoinError};
use cargo_binstall::{
bins,
@ -84,6 +84,7 @@ enum MainExit {
Success(Duration),
Error(BinstallError),
Report(miette::Report),
JoinErr(JoinError),
}
impl Termination for MainExit {
@ -99,6 +100,11 @@ impl Termination for MainExit {
eprintln!("{err:?}");
ExitCode::from(16)
}
Self::JoinErr(err) => {
error!("Fatal error:");
eprintln!("{err:?}");
ExitCode::from(17)
}
}
}
}
@ -107,19 +113,20 @@ fn main() -> MainExit {
let start = Instant::now();
let rt = Runtime::new().unwrap();
let result = rt.block_on(entry());
let handle = rt.spawn(entry());
let result = rt.block_on(handle);
drop(rt);
let done = start.elapsed();
debug!("run time: {done:?}");
result
.map(|_| MainExit::Success(done))
.unwrap_or_else(|err| {
result.map_or_else(MainExit::JoinErr, |res| {
res.map(|_| MainExit::Success(done)).unwrap_or_else(|err| {
err.downcast::<BinstallError>()
.map(MainExit::Error)
.unwrap_or_else(MainExit::Report)
})
})
}
async fn entry() -> Result<()> {
@ -240,7 +247,7 @@ async fn entry() -> Result<()> {
Some(fetcher) => {
install_from_package(
binaries,
fetcher,
&*fetcher,
install_path,
meta,
opts,