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
//! **Python**: a wheel or an sdist, named by its core metadata (`METADATA` / `PKG-INFO`).

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

/// `Name:` / `Version:` of a core-metadata document.
fn metadata_fields(m: &[u8]) -> Option<(String, String)> {
    let text = String::from_utf8_lossy(m);
    let head = text.split("\n\n").next().unwrap_or(&text);
    let field = |k: &str| {
        head.lines().find_map(|l| {
            let (a, b) = l.split_once(':')?;
            a.trim()
                .eq_ignore_ascii_case(k)
                .then(|| b.trim().to_string())
        })
    };
    Some((field("Name")?, field("Version")?))
}

/// The Python descriptor.
pub struct Pypi;

/// The one Python descriptor ([`super::FORMATS`]).
pub static PYPI: Pypi = Pypi;

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

    fn repository(&self) -> Option<crate::ArtifactFormat> {
        Some(crate::ArtifactFormat::Pip)
    }
    fn ecosystem(&self, _distro: Option<&'static str>) -> &'static str {
        "pip"
    }
    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(&[".whl", ".tar.gz", ".zip", ".tar.bz2"])
    }
    fn reads_row(&self) -> bool {
        true
    }
    fn client_setup(&self, at: &ClientAt<'_>) -> Vec<ClientSetup> {
        let ClientAt {
            name, host, token, ..
        } = *at;
        vec![
            ClientSetup::new("pip", "~/.config/pip/pip.conf", format!("[global]\nindex-url = https://token:{token}@{host}/{name}/simple/\n")),
            ClientSetup::new("pip", "shell", format!("pip install --index-url https://token:{token}@{host}/{name}/simple/ <package>\n")),
        ]
    }
    fn identify(&self, at: &Located<'_>) -> Result<Named, String> {
        let file = at.file();
        let lower = file.to_ascii_lowercase();
        let said = match at.declared {
            Some((n, v)) => Some((n.to_string(), v.to_string())),
            None if lower.ends_with(".whl") => {
                let mut it = file.split('-');
                match (it.next(), it.next()) {
                    (Some(n), Some(v)) if !n.is_empty() && !v.is_empty() => {
                        Some((n.to_string(), v.to_string()))
                    }
                    _ => None,
                }
            }
            None => [".tar.gz", ".zip", ".tar.bz2"]
                .iter()
                .find_map(|ext| {
                    lower
                        .ends_with(ext)
                        .then(|| &file[..file.len() - ext.len()])
                })
                .and_then(|stem| stem.rsplit_once('-'))
                .filter(|(n, v)| !n.is_empty() && !v.is_empty())
                .map(|(n, v)| (n.to_string(), v.to_string())),
        };
        let own = match at.row {
            Some(IndexRow::Wheel {
                metadata: Some(m), ..
            }) => metadata_fields(m),
            _ => None,
        };
        let pep503 = crate::pep503_name;
        let (name, version) = match (said, own) {
            (Some(s), Some(o)) if pep503(&s.0) != pep503(&o.0) => {
                return Err(mismatch(
                    self.name(),
                    (&s.0, &s.1),
                    (&o.0, &o.1),
                    "METADATA",
                ))
            }
            (Some(s), _) => s,
            (None, Some(o)) => o,
            (None, None) => {
                return Err(format!(
                "{file:?} is no Python distribution (a wheel or an sdist named `<name>-<version>`)"
            ))
            }
        };
        Ok(Named {
            purl: Purl::new("pypi", None, &pep503(&name), &version),
            coords: Some((name, version)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn at<'a>(path: &'a str, row: Option<&'a IndexRow>) -> Located<'a> {
        Located {
            path,
            sha256: "ab",
            distro: None,
            declared: None,
            row,
        }
    }

    fn wheel_row(metadata: &str) -> IndexRow {
        IndexRow::Wheel {
            metadata: Some(metadata.as_bytes().to_vec()),
            sha256: Some("0".repeat(64)),
        }
    }

    #[test]
    fn a_wheel_and_an_sdist_are_named_by_pep_503() {
        let w = PYPI
            .identify(&at("files/PyYAML-5.3-cp38-cp38-linux_x86_64.whl", None))
            .unwrap();
        assert_eq!(w.purl.to_string(), "pkg:pypi/pyyaml@5.3");
        assert_eq!(w.coords, Some(("PyYAML".into(), "5.3".into())));
        for f in [
            "Foo.Bar-1.0.tar.gz",
            "Foo.Bar-1.0.zip",
            "Foo.Bar-1.0.tar.bz2",
        ] {
            assert_eq!(
                PYPI.identify(&at(f, None)).unwrap().purl.to_string(),
                "pkg:pypi/foo-bar@1.0",
                "{f}"
            );
        }
    }

    #[test]
    fn the_wheels_metadata_names_it_and_a_mismatch_is_refused() {
        let ok = wheel_row("Metadata-Version: 2.1\nName: pyyaml\nVersion: 5.3\n\nbody");
        assert!(PYPI
            .identify(&at("PyYAML-5.3-py3-none-any.whl", Some(&ok)))
            .is_ok());
        let evil = wheel_row("Name: requests\nVersion: 5.3\n");
        let e = PYPI
            .identify(&at("PyYAML-5.3-py3-none-any.whl", Some(&evil)))
            .unwrap_err();
        assert!(
            e.contains("names itself requests@5.3 in its METADATA"),
            "{e}"
        );
        let only_row = PYPI.identify(&at("blob", Some(&ok))).unwrap();
        assert_eq!(only_row.coords, Some(("pyyaml".into(), "5.3".into())));
    }

    #[test]
    fn what_is_no_distribution_is_refused_and_not_claimed() {
        assert!(PYPI.identify(&at("notes/README", None)).is_err());
        assert!(PYPI.identify(&at("-1.0.tar.gz", None)).is_err());
        assert!(!PYPI.claims("x/README"));
        assert!(PYPI.claims("x/A-1.0-py3-none-any.WHL"));
        assert_eq!(PYPI.ecosystem(None), "pip");
    }
}