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
//! **Maven**: a file under `<group path>/<artifact>/<version>/`, named by its coordinates.

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

/// `<group path>/<artifact>/<version>/<artifact>-<version>[-<classifier>].<ext>[.<checksum>]`.
fn maven_parts(path: &str) -> Option<(String, String, String, String)> {
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    if segs.len() < 4 {
        return None;
    }
    let n = segs.len();
    let (artifact, version, file) = (segs[n - 3], segs[n - 2], segs[n - 1]);
    let rest = file.strip_prefix(&format!("{artifact}-{version}"))?;
    if !(rest.starts_with('.') || rest.starts_with('-')) {
        return None;
    }
    Some((
        segs[..n - 3].join("."),
        artifact.to_string(),
        version.to_string(),
        rest.to_string(),
    ))
}

/// The Maven descriptor.
pub struct Maven;

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

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

    fn repository(&self) -> Option<crate::ArtifactFormat> {
        Some(crate::ArtifactFormat::Maven3)
    }
    fn ecosystem(&self, _distro: Option<&'static str>) -> &'static str {
        "maven"
    }
    fn claims(&self, path: &str) -> bool {
        maven_parts(path).is_some()
    }
    fn client_setup(&self, at: &ClientAt<'_>) -> Vec<ClientSetup> {
        let ClientAt {
            name, base, token, ..
        } = *at;
        vec![ClientSetup::new(
            "maven",
            "~/.m2/settings.xml",
            format!(
                "<settings>\n  <servers>\n    <server>\n      <id>{name}</id>\n      <username>token</username>\n      <password>{token}</password>\n    </server>\n  </servers>\n  <mirrors>\n    <mirror>\n      <id>{name}</id>\n      <mirrorOf>*</mirrorOf>\n      <url>{base}/{name}/</url>\n    </mirror>\n  </mirrors>\n</settings>\n"
            ),
        )]
    }
    fn identify(&self, at: &Located<'_>) -> Result<Named, String> {
        if let Some((n, v)) = at.declared {
            let (g, a) = n.split_once(':').unwrap_or(("", n));
            return Ok(Named {
                purl: Purl::new("maven", Some(g), a, v),
                coords: Some((n.to_string(), v.to_string())),
            });
        }
        let (group, artifact, version, rest) = maven_parts(at.path).ok_or_else(|| {
            format!(
                "{:?} is no Maven file (`<group>/<artifact>/<version>/<artifact>-<version>[-<classifier>].<ext>`)",
                at.path
            )
        })?;
        // `-sources.jar` → classifier `sources`, type `jar`; `.pom` → type `pom`.
        let (classifier, ty) = match rest.strip_prefix('-') {
            Some(r) => match r.split_once('.') {
                Some((c, t)) => (c.to_string(), t.to_string()),
                None => (r.to_string(), String::new()),
            },
            None => (String::new(), rest.trim_start_matches('.').to_string()),
        };
        let purl = Purl::new("maven", Some(&group), &artifact, &version)
            .with("classifier", &classifier)
            .with("type", &ty);
        Ok(Named {
            purl,
            coords: Some((format!("{group}:{artifact}"), version)),
        })
    }
}

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

    #[test]
    fn a_maven_file_is_named_by_its_coordinates() {
        let n = MAVEN
            .identify(&at(
                "org/apache/logging/log4j/log4j-core/2.14.1/log4j-core-2.14.1.jar",
                None,
            ))
            .unwrap();
        assert_eq!(
            n.purl.to_string(),
            "pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1?type=jar"
        );
        assert_eq!(
            n.coords,
            Some((
                "org.apache.logging.log4j:log4j-core".into(),
                "2.14.1".into()
            ))
        );
        assert!(MAVEN.claims("g/a/1/a-1.pom"));
        assert!(!MAVEN.claims("a-1.jar"));
        assert!(MAVEN.identify(&at("a-1.jar", None)).is_err());
        assert_eq!(MAVEN.ecosystem(None), "maven");
    }
}