use super::{sha256_file, verify_sha256, FetchError, FetchRequest, Fetched, Fetcher, ProgressFn};
use async_trait::async_trait;
use std::time::Duration;
const PROGRESS_POLL_INTERVAL: Duration = Duration::from_millis(100);
pub struct CommandFetcher {
name: String,
schemes: Vec<String>,
program: String,
args: Vec<String>,
}
impl CommandFetcher {
pub fn new(
name: impl Into<String>,
schemes: Vec<String>,
program: impl Into<String>,
args: Vec<String>,
) -> Self {
Self {
name: name.into(),
schemes,
program: program.into(),
args,
}
}
fn build_args(&self, request: &FetchRequest) -> Vec<String> {
let destination = request.destination.to_string_lossy().into_owned();
let directory = request
.destination
.parent()
.map(|parent| parent.to_string_lossy().into_owned())
.unwrap_or_default();
let name = request
.destination
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
self.args
.iter()
.map(|arg| {
arg.replace("{uri}", &request.address.uri)
.replace("{dest}", &destination)
.replace("{dir}", &directory)
.replace("{name}", &name)
})
.collect()
}
async fn run(
&self,
request: &FetchRequest,
progress: Option<&ProgressFn<'_>>,
) -> Result<(), FetchError> {
if let Some(parent) = request.destination.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let args = self.build_args(request);
let mut child = tokio::process::Command::new(&self.program)
.args(&args)
.spawn()
.map_err(|error| FetchError::Command(format!("{}: {error}", self.program)))?;
let status = match progress {
None => child
.wait()
.await
.map_err(|error| FetchError::Command(format!("{}: {error}", self.program)))?,
Some(progress) => {
let mut last = 0u64;
loop {
match child.try_wait() {
Ok(Some(status)) => {
report_size(&request.destination, progress, &mut last).await;
break status;
}
Ok(None) => {}
Err(error) => {
return Err(FetchError::Command(format!("{}: {error}", self.program)));
}
}
report_size(&request.destination, progress, &mut last).await;
tokio::time::sleep(PROGRESS_POLL_INTERVAL).await;
}
}
};
if !status.success() {
return Err(FetchError::Command(format!(
"{} exited with {status}",
self.program
)));
}
Ok(())
}
async fn finish(&self, request: &FetchRequest) -> Result<Fetched, FetchError> {
let bytes = tokio::fs::metadata(&request.destination)
.await
.map_err(|error| {
FetchError::Command(format!(
"{} exited successfully but did not create {}: {error}",
self.program,
request.destination.display()
))
})?
.len();
let digest = sha256_file(&request.destination).await.ok();
if let Some(actual) = digest.as_deref() {
verify_sha256(request.expected_sha256.as_deref(), actual)?;
}
Ok(Fetched {
path: request.destination.clone(),
bytes,
sha256: digest,
address: request.address.clone(),
})
}
}
async fn report_size(destination: &std::path::Path, progress: &ProgressFn<'_>, last: &mut u64) {
if let Ok(metadata) = tokio::fs::metadata(destination).await {
let bytes = metadata.len();
if bytes > *last {
*last = bytes;
progress(bytes);
}
}
}
#[async_trait]
impl Fetcher for CommandFetcher {
fn name(&self) -> &str {
&self.name
}
fn schemes(&self) -> &[String] {
&self.schemes
}
async fn fetch(&self, request: &FetchRequest) -> Result<Fetched, FetchError> {
self.run(request, None).await?;
self.finish(request).await
}
async fn fetch_with_progress(
&self,
request: &FetchRequest,
progress: &ProgressFn<'_>,
) -> Result<Fetched, FetchError> {
self.run(request, Some(progress)).await?;
self.finish(request).await
}
}