use anyhow::Context;
use clap::Args;
use crate::ffi;
use crate::hf::ClassifiedRef;
#[derive(Args, Debug)]
pub struct TransferArgs {
#[arg(value_name = "SOURCE")]
pub source: String,
#[arg(value_name = "DESTINATION")]
pub destination: String,
#[arg(long, value_name = "PATH")]
pub sign_key: Option<String>,
}
pub fn run(args: &TransferArgs) -> anyhow::Result<()> {
let source = crate::shortnames::resolve(&args.source)?;
let destination = crate::shortnames::resolve(&args.destination)?;
let sign_key = args
.sign_key
.as_deref()
.map(crate::verify::check_signing_key)
.transpose()?;
let rt = tokio::runtime::Runtime::new().context("start tokio runtime")?;
let (outcome, source_confirmed) = rt.block_on(async {
match crate::hf::classify(&source).await {
ClassifiedRef::Hf(reference) => crate::hf::transfer::transfer(&reference, &destination)
.await
.map(|o| (o, true)),
ClassifiedRef::Source(reference) => crate::sources::transfer(&reference, &destination)
.await
.map(|o| (o, true)),
ClassifiedRef::Other(normalized) => {
let mut verdict = crate::verify::check(&normalized, None)?;
verdict.report();
verdict.notices.clear();
let pinned = match &verdict.digest {
Some(digest) => crate::verify::pin_to_digest(&normalized, digest),
None => normalized.clone(),
};
let outcome = ffi::transfer(&pinned, &destination)?;
let confirmed = match (&verdict.digest, &outcome.digest) {
(Some(verified), Some(pushed)) => verified.eq_ignore_ascii_case(pushed),
(None, _) => true,
(Some(_), None) => false,
};
if !confirmed {
verdict.escalate(format!(
"{normalized} was verified, but {destination} received a different manifest"
))?;
verdict.report();
}
Ok((outcome, confirmed))
}
}
})?;
if outcome.changed {
println!("Transferred {source} to {destination}");
} else {
println!("{destination} already up to date with {source}");
}
if let Some(key) = &sign_key {
if !source_confirmed {
anyhow::bail!(
"refusing to sign {destination}: the source changed while being transferred, \
so the manifest pushed is not the one that was verified"
);
}
let digest = outcome.digest.as_deref().ok_or_else(|| {
anyhow::anyhow!(
"cannot sign {destination}: the transfer did not report which manifest it pushed"
)
})?;
let key = key
.to_str()
.context("signing key path is not valid UTF-8")?;
let signed = ffi::sign(
&destination,
digest,
key,
&crate::verify::signing_password(),
)
.with_context(|| format!("sign {destination}"))?;
println!("Signed {destination} ({signed}) with {key}");
}
Ok(())
}