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
//! **Debian**: a `.deb`, named by its control file (its SOURCE package for the advisories).

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

/// **A `.deb`'s coordinates, as Debian's advisories name them**: its
/// control file's SOURCE package and version (`Source: openssl (3.0.11-1)`, else `Source:`
/// with the binary's `Version:`, else `Package:` and `Version:`).
pub fn deb_source_coords(control: &str) -> Option<(String, String)> {
    let version = control_field(control, "Version")?;
    let (name, version) = match control_field(control, "Source") {
        Some(src) => match src.split_once('(') {
            Some((n, v)) => (
                n.trim().to_string(),
                v.trim_end_matches(')').trim().to_string(),
            ),
            None => (src, version),
        },
        None => (control_field(control, "Package")?, version),
    };
    (!name.is_empty() && !version.is_empty()).then_some((name, version))
}

/// One field of a control stanza (no continuation lines).
pub fn control_field(control: &str, key: &str) -> Option<String> {
    control.lines().find_map(|l| {
        let (k, v) = l.split_once(':')?;
        (k.trim().eq_ignore_ascii_case(key) && !l.starts_with([' ', '\t']))
            .then(|| v.trim().to_string())
            .filter(|v| !v.is_empty())
    })
}

/// The Deb descriptor.
pub struct Deb;

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

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

    fn repository(&self) -> Option<crate::ArtifactFormat> {
        Some(crate::ArtifactFormat::Deb)
    }
    fn ecosystem(&self, _distro: Option<&'static str>) -> &'static str {
        "deb"
    }
    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(&[".deb", ".udeb"])
    }
    fn reads_row(&self) -> bool {
        true
    }
    /// The view signs its metadata and apt checks it with the key the box serves: no
    /// `[trusted=yes]`.
    fn client_setup(&self, at: &ClientAt<'_>) -> Vec<ClientSetup> {
        let ClientAt {
            name,
            base,
            host,
            token,
            key_path,
            trust,
        } = *at;
        vec![
            ClientSetup::new("apt", "shell", format!("sudo install -d -m 0755 /etc/apt/keyrings\ncurl -fsSL {base}{key_path} | sudo tee /etc/apt/keyrings/{name}.asc >/dev/null\n{trust}# Check that the file holds that key before apt trusts it:\ngpg --show-keys /etc/apt/keyrings/{name}.asc\n")),
            ClientSetup::new("apt", format!("/etc/apt/sources.list.d/{name}.list"), format!("deb [signed-by=/etc/apt/keyrings/{name}.asc] {base}/{name} stable main\n")),
            ClientSetup::new("apt", format!("/etc/apt/auth.conf.d/{name}.conf"), format!("machine {host}/{name}\nlogin token\npassword {token}\n")),
        ]
    }
    fn identify(&self, at: &Located<'_>) -> Result<Named, String> {
        // apt installs what the control file names, so the file name is never read (P14).
        let Some(IndexRow::Deb { control }) = at.row else {
            return Err(format!(
                "the control file of {:?} does not read, and a .deb is named by nothing else",
                at.path
            ));
        };
        let package = control_field(control, "Package")
            .ok_or_else(|| format!("the control file of {:?} names no Package", at.path))?;
        let version = control_field(control, "Version")
            .ok_or_else(|| format!("the control file of {:?} names no Version", at.path))?;
        let source = deb_source_coords(control);
        let purl = Purl::new("deb", Some("debian"), &package, &version)
            .with(
                "arch",
                &control_field(control, "Architecture").unwrap_or_default(),
            )
            .with(
                "upstream",
                source
                    .as_ref()
                    .map(|(n, _)| n.as_str())
                    .filter(|n| *n != package)
                    .unwrap_or_default(),
            );
        Ok(Named {
            purl,
            coords: source,
        })
    }
}

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

    #[test]
    fn a_deb_is_named_by_its_control_file_and_its_source() {
        let row = IndexRow::Deb {
            control: "Package: libssl3\nSource: openssl\nVersion: 3.0.11-1~deb12u2\nArchitecture: amd64\n".into(),
        };
        let n = DEB
            .identify(&at(
                "pool/main/i/innocent/innocent_1.0_amd64.deb",
                Some(&row),
            ))
            .unwrap();
        assert_eq!(
            n.purl.to_string(),
            "pkg:deb/debian/libssl3@3.0.11-1~deb12u2?arch=amd64&upstream=openssl"
        );
        assert_eq!(
            n.coords,
            Some(("openssl".into(), "3.0.11-1~deb12u2".into()))
        );
        assert_eq!(
            deb_source_coords("Package: a\nSource: b (2.0)\nVersion: 1.0\n"),
            Some(("b".into(), "2.0".into()))
        );
        assert_eq!(
            control_field("Package: a\nVersion: 1\n", "Version"),
            Some("1".into())
        );
        assert!(DEB.claims("x.udeb") && !DEB.claims("x.rpm"));
        assert!(DEB.reads_row());
    }
}