compmd_host/registry/
options.rs1use std::collections::BTreeMap;
4
5use compmd_pack::PackName;
6use serde::{Deserialize, Serialize};
7
8pub const DEFAULT_MAX_PACK_SIZE: u64 = 10_000_000;
10
11#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Denied {
14 pub pack: PackName,
16 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub version: Option<String>,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct Options {
25 pub registries: BTreeMap<String, String>,
27 #[serde(default = "default_max_pack_size")]
29 pub max_pack_size: u64,
30 #[serde(default)]
32 pub deny: Vec<Denied>,
33}
34
35const fn default_max_pack_size() -> u64 {
37 DEFAULT_MAX_PACK_SIZE
38}
39
40impl Options {
41 #[must_use]
43 pub fn new(registries: BTreeMap<String, String>) -> Self {
44 Self {
45 registries,
46 max_pack_size: DEFAULT_MAX_PACK_SIZE,
47 deny: Vec::new(),
48 }
49 }
50
51 #[must_use]
53 pub fn registry_of(&self, pack: &PackName) -> Option<&str> {
54 self.registry_of_scope(&format!("@{}", pack.scope()))
55 }
56
57 #[must_use]
59 pub fn registry_of_scope(&self, scope: &str) -> Option<&str> {
60 self.registries
61 .get(scope)
62 .or_else(|| self.registries.get("*"))
63 .map(String::as_str)
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn a_pack_gets_its_scopes_registry_else_every_other_scopes() {
73 let mut options = Options::new(BTreeMap::from([
74 ("@kit".to_owned(), "https://npm.kit.example/".to_owned()),
75 ("*".to_owned(), "https://registry.npmjs.org/".to_owned()),
76 ]));
77 let pack = |name: &str| name.parse::<PackName>().expect("a name");
78 assert_eq!(
79 options.registry_of(&pack("@kit/mermaid")),
80 Some("https://npm.kit.example/")
81 );
82 assert_eq!(
83 options.registry_of(&pack("@acme/maps")),
84 Some("https://registry.npmjs.org/")
85 );
86 assert_eq!(
87 options.registry_of_scope("@kit"),
88 Some("https://npm.kit.example/")
89 );
90 options.registries.remove("*");
91 assert_eq!(options.registry_of(&pack("@acme/maps")), None);
92 assert_eq!(options.registry_of_scope("@acme"), None);
93 assert_eq!(options.max_pack_size, DEFAULT_MAX_PACK_SIZE);
94 let read: Options = serde_json::from_str(r#"{"registries": {}}"#).expect("options");
95 assert_eq!(
96 (read.max_pack_size, read.deny),
97 (DEFAULT_MAX_PACK_SIZE, Vec::new())
98 );
99 }
100}