holger-traits 3.3.2

holger's shared vocabulary: ArtifactId, RepositoryBackendTrait, ZnippyPlugin discriminants, and ArtifactFormat — including `ArtifactFormat::home()`, the format→crate map that answers which crate serves PyPI when grepping cannot.
Documentation
//! **OCI**: an image layout `<repository>/sha256-<hex>.oci.tar`, named by its digest.

use super::{ClientAt, ClientSetup, Format, Located, Named, Purl};

fn is_hex64(s: &str) -> bool {
    s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())
}

/// The Oci descriptor.
pub struct Oci;

/// The one Oci descriptor ([`super::FORMATS`]).
pub static OCI: Oci = Oci;

impl Format for Oci {
    fn name(&self) -> &'static str {
        "oci"
    }

    fn repository(&self) -> Option<crate::ArtifactFormat> {
        Some(crate::ArtifactFormat::Docker)
    }
    fn ecosystem(&self, _distro: Option<&'static str>) -> &'static str {
        "docker"
    }
    fn claims(&self, path: &str) -> bool {
        let file = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
        let ends = |exts: &[&str]| exts.iter().any(|e| file.ends_with(e));
        ends(&[".oci.tar"])
    }
    fn client_setup(&self, at: &ClientAt<'_>) -> Vec<ClientSetup> {
        let ClientAt {
            name, host, token, ..
        } = *at;
        vec![ClientSetup::new("docker", "shell", format!("docker login {host} -u token -p {token}\ndocker push {host}/{name}/<image>:<tag>\n"))]
    }
    fn identify(&self, at: &Located<'_>) -> Result<Named, String> {
        let file = at.file();
        let stem = file
            .strip_suffix(".oci.tar")
            .or_else(|| file.strip_suffix(".tar"))
            .ok_or_else(|| {
                format!(
                    "{:?} is no image layout (`<name>/<digest>.oci.tar`)",
                    at.path
                )
            })?;
        let repo = at.path.rsplit_once('/').map(|(r, _)| r).unwrap_or_default();
        // The digest the coordinate names (`sha256-<hex>`), else the layout's own.
        let digest = stem
            .strip_prefix("sha256-")
            .or_else(|| stem.strip_prefix("sha256_"))
            .filter(|h| is_hex64(h))
            .unwrap_or(at.sha256);
        let (name, repo) = match repo.rsplit_once('/') {
            Some((_, n)) => (n, repo),
            None if !repo.is_empty() => (repo, repo),
            None => (stem, ""),
        };
        let purl = Purl::new(
            "oci",
            None,
            &name.to_ascii_lowercase(),
            &format!("sha256:{digest}"),
        )
        .with("repository_url", repo);
        Ok(Named { purl, coords: None })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::format::test_at as at;

    #[test]
    fn an_image_is_named_by_its_digest() {
        let hex = "17367e4d3ae2b46c3290858e483fac09be085c92b372360fe3bf6a6150848fde";
        let path = format!("chainguard/static/sha256-{hex}.oci.tar");
        let n = OCI.identify(&at(&path, None)).unwrap();
        assert_eq!(
            n.purl.to_string(),
            format!("pkg:oci/static@sha256:{hex}?repository_url=chainguard/static")
        );
        assert_eq!(n.coords, None);
        // A coordinate that names no digest is named by the layout's own sha256.
        let own = OCI
            .identify(&at("chainguard/static/latest.oci.tar", None))
            .unwrap();
        assert_eq!(own.purl.version, "sha256:ab");
        assert!(OCI
            .identify(&at("chainguard/static/latest.zip", None))
            .is_err());
        assert_eq!(OCI.ecosystem(None), "docker");
    }
}