use std::collections::BTreeMap;
use compmd_pack::PackName;
use serde::{Deserialize, Serialize};
pub const DEFAULT_MAX_PACK_SIZE: u64 = 10_000_000;
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Denied {
pub pack: PackName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Options {
pub registries: BTreeMap<String, String>,
#[serde(default = "default_max_pack_size")]
pub max_pack_size: u64,
#[serde(default)]
pub deny: Vec<Denied>,
}
const fn default_max_pack_size() -> u64 {
DEFAULT_MAX_PACK_SIZE
}
impl Options {
#[must_use]
pub fn new(registries: BTreeMap<String, String>) -> Self {
Self {
registries,
max_pack_size: DEFAULT_MAX_PACK_SIZE,
deny: Vec::new(),
}
}
#[must_use]
pub fn registry_of(&self, pack: &PackName) -> Option<&str> {
self.registry_of_scope(&format!("@{}", pack.scope()))
}
#[must_use]
pub fn registry_of_scope(&self, scope: &str) -> Option<&str> {
self.registries
.get(scope)
.or_else(|| self.registries.get("*"))
.map(String::as_str)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_pack_gets_its_scopes_registry_else_every_other_scopes() {
let mut options = Options::new(BTreeMap::from([
("@kit".to_owned(), "https://npm.kit.example/".to_owned()),
("*".to_owned(), "https://registry.npmjs.org/".to_owned()),
]));
let pack = |name: &str| name.parse::<PackName>().expect("a name");
assert_eq!(
options.registry_of(&pack("@kit/mermaid")),
Some("https://npm.kit.example/")
);
assert_eq!(
options.registry_of(&pack("@acme/maps")),
Some("https://registry.npmjs.org/")
);
assert_eq!(
options.registry_of_scope("@kit"),
Some("https://npm.kit.example/")
);
options.registries.remove("*");
assert_eq!(options.registry_of(&pack("@acme/maps")), None);
assert_eq!(options.registry_of_scope("@acme"), None);
assert_eq!(options.max_pack_size, DEFAULT_MAX_PACK_SIZE);
let read: Options = serde_json::from_str(r#"{"registries": {}}"#).expect("options");
assert_eq!(
(read.max_pack_size, read.deny),
(DEFAULT_MAX_PACK_SIZE, Vec::new())
);
}
}