use async_trait::async_trait;
use serde::{Deserialize, Serialize};
pub use znippy_common;
pub use bytes::Bytes;
pub use anyhow;
pub mod backend;
pub use backend::{
chunks_of, collect_body, is_unsupported, unsupported, Access, Archive, ArchiveInfo, Cap, Caps,
ChunkIter, Decorator, HttpBytesReply, HttpReply, RepositoryBackendTrait, StreamedGet,
Unsupported, READER_PREALLOC_CAP,
};
#[cfg(feature = "http")]
pub mod http;
pub mod znippy_base;
pub use nornir_hash::hex_encode;
pub use znippy_base::{sha256_hex, DocMemo, ZnippyBase};
pub mod znippy_format;
pub mod migrate;
pub mod safe_path;
pub mod format;
pub mod index_row;
#[cfg(feature = "test-support")]
pub mod test_support;
pub use znippy_format::{
ensure_supported_format, recorded_format_version, ArchiveFormatError, FormatGate,
MAX_SUPPORTED_ZNIPPY_FORMAT, ZNIPPY_FORMAT_VERSION_KEY,
};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ArtifactId {
pub namespace: Option<String>,
pub name: String,
pub version: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum ArtifactFormat {
Maven3,
Pip,
Rust,
Go,
Nuget,
Npm,
Gem,
Deb,
Rpm,
Helm,
Docker,
Conda,
Composer,
Znippy,
Raw,
}
impl ArtifactFormat {
pub fn znippy_type_id(&self) -> i8 {
use znippy_common::plugin::ArchiveTypePlugin;
use znippy_common::plugins::{cargo_native, skeletons};
match self {
ArtifactFormat::Rust => cargo_native::CargoPlugin::new().type_id(),
ArtifactFormat::Pip => 2,
ArtifactFormat::Maven3 => 3,
ArtifactFormat::Go => skeletons::GoPlugin.type_id(),
ArtifactFormat::Nuget => skeletons::NugetPlugin.type_id(),
ArtifactFormat::Npm => znippy_common::plugins::npm_native::NpmPlugin.type_id(),
ArtifactFormat::Rpm => znippy_common::plugins::rpm_native::RpmPlugin.type_id(),
ArtifactFormat::Deb => znippy_common::plugins::deb_native::DebPlugin.type_id(),
ArtifactFormat::Gem => znippy_common::plugins::gem_native::GemPlugin.type_id(),
ArtifactFormat::Docker => skeletons::DockerPlugin.type_id(),
ArtifactFormat::Helm => skeletons::HelmPlugin.type_id(),
ArtifactFormat::Conda => znippy_common::plugins::conda_native::CondaPlugin.type_id(),
ArtifactFormat::Composer => skeletons::ComposerPlugin.type_id(),
ArtifactFormat::Znippy => 100,
ArtifactFormat::Raw => 0,
}
}
pub fn from_format_str(s: &str) -> Option<Self> {
Some(match s.to_lowercase().as_str() {
"maven2" | "maven" | "maven3" | "java" => ArtifactFormat::Maven3,
"pip" | "pypi" | "python" => ArtifactFormat::Pip,
"rust" | "cargo" | "crates.io" | "cratesio" => ArtifactFormat::Rust,
"go" | "golang" => ArtifactFormat::Go,
"nuget" | "dotnet" => ArtifactFormat::Nuget,
"npm" | "node" => ArtifactFormat::Npm,
"gem" | "ruby" | "rubygems" => ArtifactFormat::Gem,
"deb" | "debian" | "apt" => ArtifactFormat::Deb,
"rpm" | "yum" | "dnf" => ArtifactFormat::Rpm,
"helm" | "chart" => ArtifactFormat::Helm,
"docker" | "oci" => ArtifactFormat::Docker,
"conda" | "anaconda" => ArtifactFormat::Conda,
"composer" | "php" => ArtifactFormat::Composer,
"znippy" | "snippy" => ArtifactFormat::Znippy,
"raw" | "generic" => ArtifactFormat::Raw,
_ => return None,
})
}
pub fn home(&self) -> FormatHome {
let (config_key, aliases, crate_dir, package, also) = match self {
ArtifactFormat::Maven3 => (
"maven3",
&["maven", "maven2", "java"][..],
"znippy-maven",
"holger-znippy-maven-repository",
None,
),
ArtifactFormat::Pip => (
"pip",
&["pypi", "python"][..],
"znippy-python",
"holger-znippy-python-repository",
None,
),
ArtifactFormat::Rust => (
"rust",
&["cargo", "crates.io", "cratesio"][..],
"znippy-rust",
"holger-rust-znippy-repository",
Some(("file-rust", "holger-rust-file-repository")),
),
ArtifactFormat::Go => (
"go",
&["golang"][..],
"znippy-go",
"holger-znippy-go-repository",
None,
),
ArtifactFormat::Nuget => (
"nuget",
&["dotnet"][..],
"znippy-nuget",
"holger-znippy-nuget-repository",
None,
),
ArtifactFormat::Npm => (
"npm",
&["node"][..],
"znippy-npm",
"holger-znippy-npm-repository",
None,
),
ArtifactFormat::Gem => (
"gem",
&["ruby", "rubygems"][..],
"znippy-gem",
"holger-znippy-gem-repository",
None,
),
ArtifactFormat::Deb => (
"deb",
&["debian", "apt"][..],
"znippy-deb",
"holger-znippy-deb-repository",
None,
),
ArtifactFormat::Rpm => (
"rpm",
&["yum", "dnf"][..],
"znippy-rpm",
"holger-znippy-rpm-repository",
None,
),
ArtifactFormat::Helm => (
"helm",
&["chart"][..],
"znippy-helm",
"holger-znippy-helm-repository",
None,
),
ArtifactFormat::Docker => (
"docker",
&["oci"][..],
"znippy-docker",
"holger-znippy-docker-repository",
Some(("file-oci", "holger-file-oci-repository")),
),
ArtifactFormat::Conda => (
"conda",
&["anaconda"][..],
"znippy-conda",
"holger-znippy-conda-repository",
None,
),
ArtifactFormat::Composer => (
"composer",
&["php"][..],
"znippy-composer",
"holger-znippy-composer-repository",
None,
),
ArtifactFormat::Znippy => (
"znippy",
&["snippy"][..],
"znippy-package",
"holger-znippy-package-repository",
None,
),
ArtifactFormat::Raw => ("raw", &["generic"][..], "", "holger-server-lib", None),
};
FormatHome {
format: self.clone(),
config_key,
aliases,
crate_dir,
package,
also,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatHome {
pub format: ArtifactFormat,
pub config_key: &'static str,
pub aliases: &'static [&'static str],
pub crate_dir: &'static str,
pub package: &'static str,
pub also: Option<(&'static str, &'static str)>,
}
impl FormatHome {
pub fn all_names(&self) -> Vec<&'static str> {
std::iter::once(self.config_key)
.chain(self.aliases.iter().copied())
.collect()
}
}
pub const ALL_ARTIFACT_FORMATS: &[ArtifactFormat] = &[
ArtifactFormat::Maven3,
ArtifactFormat::Pip,
ArtifactFormat::Rust,
ArtifactFormat::Go,
ArtifactFormat::Nuget,
ArtifactFormat::Npm,
ArtifactFormat::Gem,
ArtifactFormat::Deb,
ArtifactFormat::Rpm,
ArtifactFormat::Helm,
ArtifactFormat::Docker,
ArtifactFormat::Conda,
ArtifactFormat::Composer,
ArtifactFormat::Znippy,
ArtifactFormat::Raw,
];
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum UpstreamAuth {
#[default]
None,
Basic { username: String, password: String },
Bearer { token: String },
ApiKey { header: String, key: String },
Mtls { cert_pem: String, key_pem: String },
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ArtifactMeta {
pub size: Option<u64>,
pub sha256: Option<String>,
pub content_type: Option<String>,
}
pub trait Upstream: RepositoryBackendTrait {
fn base_url(&self) -> &str;
fn auth(&self) -> &UpstreamAuth;
fn metadata(&self, id: &ArtifactId) -> anyhow::Result<Option<ArtifactMeta>>;
fn advertised_sha256(&self, id: &ArtifactId) -> anyhow::Result<Option<String>> {
Ok(self
.metadata(id)?
.and_then(|m| m.sha256)
.and_then(|s| normalize_sha256(s.trim().trim_start_matches("sha256:"))))
}
}
#[derive(Debug, Clone, Default)]
pub struct ArchiveTokens {
path: Option<std::path::PathBuf>,
}
impl ArchiveTokens {
pub const fn none() -> Self {
Self { path: None }
}
pub fn at(path: impl Into<std::path::PathBuf>) -> Self {
Self {
path: Some(path.into()),
}
}
pub fn path(&self) -> Option<&std::path::Path> {
self.path.as_deref()
}
pub fn open(&self) -> Option<ArchiveTokenIndex> {
let path = self.path.as_deref()?;
znippy_common::ArchiveReader::open(path)
.ok()
.map(|reader| ArchiveTokenIndex { reader })
}
}
pub struct ArchiveTokenIndex {
reader: znippy_common::ArchiveReader,
}
const CHANGE_TOKEN_TAG: &[u8] = b"holger.change-token.v1";
impl ArchiveTokenIndex {
pub fn rows(&self) -> usize {
self.reader.row_count()
}
pub fn token(&self, relative_path: &str) -> Option<String> {
let chunks = self.reader.locate(relative_path);
if chunks.is_empty() {
return None;
}
let mut h = znippy_common::blake3::Hasher::new();
h.update(CHANGE_TOKEN_TAG);
h.update(&(relative_path.len() as u64).to_le_bytes());
h.update(relative_path.as_bytes());
h.update(&(chunks.len() as u64).to_le_bytes());
for c in &chunks {
h.update(&c.chunk_seq.to_le_bytes());
h.update(&c.checksum);
}
Some(nornir_hash::hex_encode(h.finalize().as_bytes()))
}
}
pub fn list_archive_entries<F>(
reader: &dyn znippy_common::ZnippyReader,
tokens: Option<&ArchiveTokenIndex>,
name_filter: Option<&str>,
limit: usize,
content_type: &str,
coordinate: F,
) -> anyhow::Result<Vec<ArtifactEntry>>
where
F: Fn(&str) -> Option<ArtifactId>,
{
let mut out = Vec::new();
for path in reader.list_files()? {
let Some(id) = coordinate(&path) else {
continue;
};
if let Some(f) = name_filter {
if !id.name.contains(f) {
continue;
}
}
out.push(
ArtifactEntry::unknown_provenance(
id,
reader.file_size(&path).unwrap_or(0) as i64,
content_type,
)
.with_change_token(tokens.and_then(|t| t.token(&path))),
);
if limit != 0 && out.len() >= limit {
break;
}
}
Ok(out)
}
pub fn crate_download_coordinate(repo: &str, suburl: &str) -> Option<ArtifactId> {
let path = suburl.split('?').next().unwrap_or("");
match path
.trim_start_matches('/')
.split('/')
.collect::<Vec<_>>()
.as_slice()
{
[r, "crates", name, version, "download"]
if *r == repo && !name.is_empty() && !version.is_empty() =>
{
Some(ArtifactId {
namespace: None,
name: name.to_string(),
version: version.to_string(),
})
}
_ => None,
}
}
pub fn split_name_version(stem: &str) -> Option<(&str, &str)> {
let b = stem.as_bytes();
let i = (0..b.len().saturating_sub(1)).find(|&i| b[i] == b'-' && b[i + 1].is_ascii_digit())?;
let (n, v) = (&stem[..i], &stem[i + 1..]);
(!n.is_empty() && !v.is_empty()).then_some((n, v))
}
pub fn coordinate_from_name_dash_version(path: &str, suffix: &str) -> Option<ArtifactId> {
let file = path.rsplit('/').next().unwrap_or(path);
let (name, version) = split_name_version(file.strip_suffix(suffix)?)?;
Some(ArtifactId {
namespace: None,
name: name.to_string(),
version: version.to_string(),
})
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteRepository {
pub name: String,
pub format: String,
pub repo_type: String,
pub url: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoteAsset {
pub path: String,
pub download_url: String,
pub content_type: Option<String>,
pub size: Option<u64>,
#[serde(default)]
pub sha256: Option<String>,
#[serde(default)]
pub change_token: Option<String>,
}
#[async_trait]
pub trait ConnectorTrait: Send + Sync {
fn name(&self) -> &str;
async fn list_repositories(&self) -> anyhow::Result<Vec<RemoteRepository>>;
async fn list_assets(&self, repository: &str) -> anyhow::Result<Vec<RemoteAsset>>;
async fn download_asset(&self, asset: &RemoteAsset) -> anyhow::Result<Vec<u8>>;
async fn upload_asset(&self, repository: &str, path: &str, data: &[u8]) -> anyhow::Result<()>;
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RepositoryInfo {
pub name: String,
pub repo_type: String,
pub writable: bool,
pub has_archive: bool,
pub supports_listing: bool,
pub is_group: bool,
pub members: Vec<String>,
}
impl RepositoryInfo {
pub fn of(name: &str, repo: &dyn RepositoryBackendTrait) -> RepositoryInfo {
let caps = repo.caps();
RepositoryInfo {
name: name.to_string(),
repo_type: format!("{:?}", repo.format()),
writable: repo.is_writable(),
has_archive: caps.archive,
supports_listing: caps.listing,
is_group: caps.group,
members: repo.members(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ArtifactEntry {
pub id: ArtifactId,
pub size_bytes: i64,
pub content_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub published_unix_ms: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sha256: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub change_token: Option<String>,
}
impl ArtifactEntry {
pub const UNKNOWN_PROVENANCE: ArtifactEntry = ArtifactEntry {
id: ArtifactId {
namespace: None,
name: String::new(),
version: String::new(),
},
size_bytes: 0,
content_type: String::new(),
published_unix_ms: None,
sha256: None,
change_token: None,
};
pub fn unknown_provenance(
id: ArtifactId,
size_bytes: i64,
content_type: impl Into<String>,
) -> Self {
ArtifactEntry {
id,
size_bytes,
content_type: content_type.into(),
published_unix_ms: None,
sha256: None,
change_token: None,
}
}
#[must_use]
pub fn with_published_unix_ms(mut self, ms: Option<i64>) -> Self {
self.published_unix_ms = normalize_published_unix_ms(ms);
self
}
#[must_use]
pub fn with_sha256(mut self, digest: Option<impl AsRef<str>>) -> Self {
self.sha256 = digest.and_then(|d| normalize_sha256(d.as_ref()));
self
}
#[must_use]
pub fn with_change_token(mut self, token: Option<impl AsRef<str>>) -> Self {
self.change_token = token.and_then(|t| normalize_change_token(t.as_ref()));
self
}
#[must_use]
pub fn with_published_system_time(self, t: Option<std::time::SystemTime>) -> Self {
self.with_published_unix_ms(t.and_then(system_time_to_unix_ms))
}
}
pub fn system_time_to_unix_ms(t: std::time::SystemTime) -> Option<i64> {
let d = t.duration_since(std::time::UNIX_EPOCH).ok()?;
i64::try_from(d.as_millis()).ok().filter(|ms| *ms > 0)
}
pub fn pep503_name(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut prev_sep = false;
for ch in s.chars() {
if matches!(ch, '-' | '_' | '.') {
if !prev_sep {
out.push('-');
}
prev_sep = true;
} else {
out.push(ch.to_ascii_lowercase());
prev_sep = false;
}
}
out
}
pub fn normalize_sha256(s: &str) -> Option<String> {
let t = s.trim();
if t.len() != 64 || !t.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
Some(t.to_ascii_lowercase())
}
pub fn normalize_published_unix_ms(ms: Option<i64>) -> Option<i64> {
ms.filter(|v| *v > 0)
}
pub const MAX_CHANGE_TOKEN_LEN: usize = 512;
pub fn normalize_change_token(s: &str) -> Option<String> {
let t = s.trim();
if t.is_empty() || t.len() > MAX_CHANGE_TOKEN_LEN || t.chars().any(char::is_control) {
return None;
}
Some(t.to_string())
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Health {
pub status: String,
pub version: String,
pub uptime_seconds: i64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ServerProfile {
pub profile: String,
pub read_only: bool,
pub label: String,
pub writable_repo_count: i32,
}
impl Default for ServerProfile {
fn default() -> Self {
Self {
profile: "dynamic".into(),
read_only: false,
label: "DYNAMIC / WRITABLE".into(),
writable_repo_count: 0,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchQuery {
pub name: String,
pub namespace: String,
pub version: String,
pub path: String,
pub repositories: Vec<String>,
pub limit: i32,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchArtifactHit {
pub repository: String,
pub id: ArtifactId,
pub size_bytes: i64,
pub content_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchPathHit {
pub repository: String,
pub path: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SearchResults {
pub artifacts: Vec<SearchArtifactHit>,
pub paths: Vec<SearchPathHit>,
pub truncated: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SbomDoc {
pub document: Vec<u8>,
pub size_bytes: i64,
pub content_address: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PropertyKv {
pub key: String,
pub values: Vec<String>,
}
#[async_trait]
pub trait HolgerObject: Send + Sync {
async fn fetch(&self, repository: &str, id: &ArtifactId) -> anyhow::Result<Option<Bytes>>;
async fn put(&self, repository: &str, id: &ArtifactId, data: &[u8]) -> anyhow::Result<()>;
async fn list_repositories(&self) -> anyhow::Result<Vec<RepositoryInfo>>;
async fn list_artifacts(
&self,
repository: &str,
name_filter: Option<String>,
limit: u32,
page_token: Option<String>,
) -> anyhow::Result<(Vec<ArtifactEntry>, String)>;
async fn list_archive_files(
&self,
repository: &str,
prefix: Option<String>,
) -> anyhow::Result<Vec<String>>;
async fn archive_info(&self, repository: &str) -> anyhow::Result<ArchiveInfo>;
async fn health(&self) -> anyhow::Result<Health>;
async fn server_profile(&self) -> anyhow::Result<ServerProfile>;
async fn search(&self, query: &SearchQuery) -> anyhow::Result<SearchResults>;
async fn fetch_sbom(
&self,
repository: &str,
id: &ArtifactId,
) -> anyhow::Result<Option<SbomDoc>>;
async fn get_properties(
&self,
repository: &str,
id: &ArtifactId,
) -> anyhow::Result<Vec<PropertyKv>>;
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "testmatrix")]
use nornir_testmatrix::functional_status as fstatus;
#[test]
fn znippy_type_ids_match_znippy_skeletons() {
assert_eq!(ArtifactFormat::Go.znippy_type_id(), 4);
assert_eq!(ArtifactFormat::Nuget.znippy_type_id(), 5);
assert_eq!(ArtifactFormat::Npm.znippy_type_id(), 6);
assert_eq!(ArtifactFormat::Rpm.znippy_type_id(), 8);
assert_eq!(ArtifactFormat::Deb.znippy_type_id(), 9);
assert_eq!(ArtifactFormat::Gem.znippy_type_id(), 11);
assert_eq!(ArtifactFormat::Docker.znippy_type_id(), 12);
assert_eq!(ArtifactFormat::Helm.znippy_type_id(), 13);
assert_eq!(ArtifactFormat::Conda.znippy_type_id(), 14);
assert_eq!(ArtifactFormat::Composer.znippy_type_id(), 17);
assert_eq!(ArtifactFormat::Rust.znippy_type_id(), 1);
assert_eq!(ArtifactFormat::Pip.znippy_type_id(), 2);
assert_eq!(ArtifactFormat::Maven3.znippy_type_id(), 3);
#[cfg(feature = "testmatrix")]
{
let ok = ArtifactFormat::Helm.znippy_type_id() == 13
&& ArtifactFormat::Rust.znippy_type_id() == 1
&& ArtifactFormat::Composer.znippy_type_id() == 17;
fstatus(
"traits",
"znippy_type_ids_match",
ok,
&format!(
"Rust=1 Pip=2 Maven3=3 Helm=13 Composer=17 (helm={})",
ArtifactFormat::Helm.znippy_type_id()
),
);
}
}
#[test]
fn znippy_type_ids_derive_from_znippy_handlers_not_holger_copies() {
use znippy_common::plugin::ArchiveTypePlugin;
use znippy_common::plugins::{
cargo_native::CargoPlugin, conda_native::CondaPlugin, deb_native::DebPlugin,
gem_native::GemPlugin, npm_native::NpmPlugin, rpm_native::RpmPlugin, skeletons,
};
let pairs: &[(ArtifactFormat, i8)] = &[
(ArtifactFormat::Rust, CargoPlugin::new().type_id()),
(ArtifactFormat::Npm, NpmPlugin.type_id()),
(ArtifactFormat::Gem, GemPlugin.type_id()),
(ArtifactFormat::Conda, CondaPlugin.type_id()),
(ArtifactFormat::Rpm, RpmPlugin.type_id()),
(ArtifactFormat::Deb, DebPlugin.type_id()),
(ArtifactFormat::Go, skeletons::GoPlugin.type_id()),
(ArtifactFormat::Nuget, skeletons::NugetPlugin.type_id()),
(ArtifactFormat::Docker, skeletons::DockerPlugin.type_id()),
(ArtifactFormat::Helm, skeletons::HelmPlugin.type_id()),
(
ArtifactFormat::Composer,
skeletons::ComposerPlugin.type_id(),
),
];
let mut all_ok = true;
for (fmt, znippy_id) in pairs {
let holger_id = fmt.znippy_type_id();
if holger_id != *znippy_id {
all_ok = false;
}
assert_eq!(
holger_id, *znippy_id,
"{fmt:?}: holger znippy_type_id()={holger_id} drifted from znippy handler type_id()={znippy_id}"
);
}
#[cfg(feature = "testmatrix")]
fstatus(
"traits",
"znippy_type_ids_derive_from_handlers",
all_ok,
&format!(
"{} formats derive their discriminant from znippy handlers",
pairs.len()
),
);
let _ = all_ok;
}
#[test]
fn upstream_auth_defaults_to_none() {
assert_eq!(UpstreamAuth::default(), UpstreamAuth::None);
assert_ne!(
UpstreamAuth::Bearer { token: "t".into() },
UpstreamAuth::Basic {
username: "u".into(),
password: "p".into()
}
);
}
#[test]
fn every_format_names_a_crate_that_exists() {
let repo_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("traits/ has a parent")
.to_path_buf();
for fmt in ALL_ARTIFACT_FORMATS {
let home = fmt.home();
for name in home.all_names() {
assert_eq!(
ArtifactFormat::from_format_str(name),
Some(fmt.clone()),
"{fmt:?}: the name {name:?} must resolve back to it"
);
}
for (dir, package) in std::iter::once((home.crate_dir, home.package))
.chain(home.also)
.filter(|(d, _)| !d.is_empty())
{
let manifest = repo_root
.join("server/repository")
.join(dir)
.join("Cargo.toml");
assert!(
manifest.is_file(),
"{fmt:?}: home() points at server/repository/{dir}, which does not exist \
(renamed? then update ArtifactFormat::home)"
);
let text = std::fs::read_to_string(&manifest).expect("read Cargo.toml");
assert!(
text.lines()
.any(|l| l.trim() == format!("name = \"{package}\"")),
"{fmt:?}: server/repository/{dir} is not package {package:?} \
(renamed? then update ArtifactFormat::home)"
);
}
}
}
#[test]
fn a_digest_that_is_not_a_digest_becomes_unknown() {
assert_eq!(normalize_sha256(&"a".repeat(64)), Some("a".repeat(64)));
assert_eq!(
normalize_sha256(&"A".repeat(64)),
Some("a".repeat(64)),
"hex is lowercased"
);
assert_eq!(
normalize_sha256(&format!(" {} ", "a".repeat(64))),
Some("a".repeat(64))
);
for bad in [
"",
"sha256:".to_string().as_str(),
&format!("sha256:{}", "a".repeat(64)),
&"a".repeat(63),
&"a".repeat(65),
&"z".repeat(64),
] {
assert_eq!(
normalize_sha256(bad),
None,
"{bad:?} must not be accepted as a digest"
);
}
}
#[test]
fn an_empty_or_unusable_change_token_becomes_unknown() {
assert_eq!(normalize_change_token(""), None);
assert_eq!(normalize_change_token(" "), None);
assert_eq!(
normalize_change_token("a\u{0}b"),
None,
"control characters are refused"
);
assert_eq!(
normalize_change_token(&"x".repeat(MAX_CHANGE_TOKEN_LEN + 1)),
None
);
assert_eq!(
normalize_change_token(" abc "),
Some("abc".to_string()),
"trimmed"
);
assert_eq!(
ArtifactEntry::unknown_provenance(
ArtifactId {
namespace: None,
name: "a".into(),
version: "1".into()
},
1,
"t",
)
.with_change_token(Some(""))
.change_token,
None,
"and the builder drops it rather than carrying it"
);
}
#[test]
fn the_proto3_zero_values_are_not_answers() {
assert_eq!(
normalize_published_unix_ms(Some(0)),
None,
"0 is what nobody-set looks like"
);
assert_eq!(normalize_published_unix_ms(Some(-1)), None);
assert_eq!(normalize_published_unix_ms(None), None);
assert_eq!(normalize_published_unix_ms(Some(1)), Some(1));
assert_eq!(
normalize_sha256(""),
None,
"the empty string is not a digest"
);
}
#[test]
fn an_entry_that_knows_nothing_says_so_and_cannot_be_talked_into_a_value() {
let id = ArtifactId {
namespace: None,
name: "a".into(),
version: "1".into(),
};
let e = ArtifactEntry::unknown_provenance(id.clone(), 7, "application/octet-stream");
assert_eq!(e.published_unix_ms, None);
assert_eq!(e.sha256, None);
assert_eq!(e.size_bytes, 7);
let e = e.with_published_unix_ms(Some(0)).with_sha256(Some(""));
assert_eq!(e.published_unix_ms, None, "a zero must not become a time");
assert_eq!(e.sha256, None, "an empty string must not become a digest");
let e = e
.with_published_unix_ms(Some(1_726_000_000_000))
.with_sha256(Some("B".repeat(64)));
assert_eq!(e.published_unix_ms, Some(1_726_000_000_000));
assert_eq!(e.sha256, Some("b".repeat(64)));
let lit = ArtifactEntry {
id,
size_bytes: 7,
content_type: "application/octet-stream".into(),
..ArtifactEntry::UNKNOWN_PROVENANCE
};
assert_eq!(lit.published_unix_ms, None);
assert_eq!(lit.sha256, None);
}
#[test]
fn a_system_time_at_the_epoch_is_unknown_rather_than_zero() {
assert_eq!(system_time_to_unix_ms(std::time::UNIX_EPOCH), None);
assert_eq!(
system_time_to_unix_ms(std::time::UNIX_EPOCH - std::time::Duration::from_secs(1)),
None
);
let ms = system_time_to_unix_ms(std::time::SystemTime::now()).expect("now is after 1970");
assert!(ms > 1_700_000_000_000, "milliseconds, not seconds: {ms}");
}
#[test]
fn the_shared_znippy_listing_answers_unknown_for_every_row() {
let e = ArtifactEntry::unknown_provenance(
ArtifactId {
namespace: None,
name: "x".into(),
version: "1".into(),
},
1,
"application/octet-stream",
);
assert_eq!((e.published_unix_ms, e.sha256), (None, None));
}
#[test]
fn the_pypi_four_name_split_is_pinned() {
let home = ArtifactFormat::Pip.home();
assert_eq!(
home.config_key, "pip",
"operators write ron_repo_type: \"pip\""
);
assert!(
home.aliases.contains(&"pypi"),
"the docs/UI name must be findable"
);
assert!(
home.aliases.contains(&"python"),
"the crate's own name must be findable"
);
assert_eq!(
home.crate_dir, "znippy-python",
"the implementation lives under a THIRD name — that is the whole point"
);
assert_ne!(home.crate_dir, home.config_key);
assert_ne!(home.crate_dir, "pypi");
}
#[test]
fn format_str_roundtrips_aliases() {
assert_eq!(
ArtifactFormat::from_format_str("cargo"),
Some(ArtifactFormat::Rust)
);
assert_eq!(
ArtifactFormat::from_format_str("golang"),
Some(ArtifactFormat::Go)
);
assert_eq!(
ArtifactFormat::from_format_str("dotnet"),
Some(ArtifactFormat::Nuget)
);
assert_eq!(
ArtifactFormat::from_format_str("oci"),
Some(ArtifactFormat::Docker)
);
assert_eq!(ArtifactFormat::from_format_str("nope"), None);
#[cfg(feature = "testmatrix")]
{
let ok = ArtifactFormat::from_format_str("cargo") == Some(ArtifactFormat::Rust)
&& ArtifactFormat::from_format_str("oci") == Some(ArtifactFormat::Docker)
&& ArtifactFormat::from_format_str("nope").is_none();
fstatus(
"traits",
"format_str_aliases_roundtrip",
ok,
"cargo->Rust golang->Go dotnet->Nuget oci->Docker nope->None",
);
}
}
}