use clap::Args;
use crate::storage::OciStore;
#[derive(Args, Debug)]
pub struct CpArgs {
#[arg(value_name = "SOURCE")]
pub source: String,
#[arg(value_name = "DESTINATION")]
pub destination: String,
}
pub fn run(args: &CpArgs) -> anyhow::Result<()> {
let source = crate::shortnames::resolve_ollama_api(&args.source)?;
let destination = crate::shortnames::resolve_ollama_api(&args.destination)?;
let store_root = crate::default_store()?;
let store = OciStore::open(&store_root)?;
copy(&store, &crate::default_cache()?, &source, &destination)?;
println!("copied '{}' to '{}'", args.source, args.destination);
Ok(())
}
pub fn copy(
store: &OciStore,
cache_path: &std::path::Path,
source: &str,
destination: &str,
) -> anyhow::Result<String> {
let desc = store.find(source)?;
check_digest_destination(destination, &desc.digest)?;
let digest = desc.digest.clone();
crate::storage::gc::after_retag(store, cache_path, destination, || {
store.tag(desc, destination)
})?;
Ok(digest)
}
fn check_digest_destination(destination: &str, actual: &str) -> anyhow::Result<()> {
match crate::storage::split_ref_digest(destination).1 {
Some(digest) if !digest.eq_ignore_ascii_case(actual) => anyhow::bail!(
"destination {destination} names digest {digest}, but the source's is {actual}"
),
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_digest_destination_must_match_the_copied_digest() {
assert!(check_digest_destination("docker.io/ai/m:v9", "sha256:aaaa").is_ok());
assert!(check_digest_destination("docker.io/ai/m@sha256:aaaa", "sha256:aaaa").is_ok());
assert!(check_digest_destination("docker.io/ai/m@sha256:AAAA", "sha256:aaaa").is_ok());
assert!(check_digest_destination("docker.io/ai/m@sha256:bbbb", "sha256:aaaa").is_err());
}
#[test]
fn cp_rejects_an_invalid_destination_before_writing() {
let args = CpArgs {
source: "gemma4".into(),
destination: "hf.co//foo".into(),
};
let err = run(&args).expect_err("invalid destination must error");
assert!(
err.to_string().contains("invalid model reference"),
"expected a validation error, got: {err}"
);
}
}