Skip to main content

compmd_pack/
name.rs

1//! A pack's name (spec ยง6.4): always scoped, `@scope/name`, an npm package's.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use crate::invalid::Invalid;
9
10/// The scope the spec reserves: `@compmd/core` is built into processors, and `@compmd/*` is never fetched.
11const RESERVED: &str = "compmd";
12
13/// The longest name npm takes.
14const LONGEST: usize = 214;
15
16/// A pack's name, `@scope/name`.
17#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
18#[serde(try_from = "String", into = "String")]
19pub struct PackName(String);
20
21impl PackName {
22    /// The name `text`, when it is one: `@`, a scope, `/` and a name, each part lowercase letters, digits, `-`, `.`,
23    /// `_` and `~`, not starting with `.` or `_`, as npm names scoped packages; at most 214 characters.
24    ///
25    /// # Errors
26    ///
27    /// [`Invalid::Name`] when it isn't one.
28    pub fn new(text: impl Into<String>) -> Result<Self, Invalid> {
29        let text = text.into();
30        let plain = |part: &str| {
31            !part.is_empty()
32                && !part.starts_with(['.', '_'])
33                && part.bytes().all(|byte| {
34                    byte.is_ascii_lowercase()
35                        || byte.is_ascii_digit()
36                        || matches!(byte, b'-' | b'.' | b'_' | b'~')
37                })
38        };
39        let scoped = text.len() <= LONGEST
40            && text
41                .strip_prefix('@')
42                .and_then(|rest| rest.split_once('/'))
43                .is_some_and(|(scope, name)| plain(scope) && plain(name));
44        if scoped {
45            Ok(Self(text))
46        } else {
47            Err(Invalid::Name(text))
48        }
49    }
50
51    /// The name as written.
52    #[must_use]
53    pub fn as_str(&self) -> &str {
54        &self.0
55    }
56
57    /// Its scope, without `@`: `kit` for `@kit/mermaid`.
58    #[must_use]
59    pub fn scope(&self) -> &str {
60        self.parts().0
61    }
62
63    /// Its name in the scope: `mermaid` for `@kit/mermaid`.
64    #[must_use]
65    pub fn name(&self) -> &str {
66        self.parts().1
67    }
68
69    /// Whether it is in the scope the spec reserves, `@compmd/`.
70    #[must_use]
71    pub fn is_reserved(&self) -> bool {
72        self.scope() == RESERVED
73    }
74
75    fn parts(&self) -> (&str, &str) {
76        self.0[1..].split_once('/').unwrap_or_default()
77    }
78}
79
80impl FromStr for PackName {
81    type Err = Invalid;
82
83    fn from_str(text: &str) -> Result<Self, Self::Err> {
84        Self::new(text)
85    }
86}
87
88impl TryFrom<String> for PackName {
89    type Error = Invalid;
90
91    fn try_from(text: String) -> Result<Self, Self::Error> {
92        Self::new(text)
93    }
94}
95
96impl From<PackName> for String {
97    fn from(name: PackName) -> Self {
98        name.0
99    }
100}
101
102impl fmt::Display for PackName {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        f.write_str(&self.0)
105    }
106}
107
108impl PartialEq<str> for PackName {
109    fn eq(&self, other: &str) -> bool {
110        self.0 == other
111    }
112}
113
114impl PartialEq<&str> for PackName {
115    fn eq(&self, other: &&str) -> bool {
116        self.0 == *other
117    }
118}
119
120#[cfg(test)]
121mod tests {
122    use super::*;
123
124    #[test]
125    fn a_name_is_scoped_and_plain() {
126        for text in ["@kit/mermaid", "@comp-markdown/mermaid", "@a1/b.c_d~e"] {
127            let name = PackName::new(text).expect(text);
128            assert_eq!(name.as_str(), text);
129            assert_eq!(name.to_string(), text);
130            assert_eq!(name, text);
131            assert!(name == *text, "against a `str` too");
132        }
133        let name: PackName = "@kit/mermaid".parse().expect("a name");
134        assert_eq!((name.scope(), name.name()), ("kit", "mermaid"));
135        assert!(!name.is_reserved());
136        assert!(PackName::new("@compmd/core").expect("a name").is_reserved());
137    }
138
139    #[test]
140    fn what_isnt_a_name_is_refused_saying_why() {
141        for text in [
142            "mermaid",
143            "@kit",
144            "@kit/",
145            "@/mermaid",
146            "@kit/../x",
147            "@kit/.x",
148            "@kit/_x",
149            "@KIT/x",
150            "@kit/a/b",
151            "@kit/a b",
152        ] {
153            assert_eq!(
154                PackName::new(text),
155                Err(Invalid::Name(text.to_owned())),
156                "{text}"
157            );
158        }
159        let long = format!("@kit/{}", "a".repeat(LONGEST));
160        assert!(PackName::new(long).is_err());
161        assert!(
162            Invalid::Name("x".to_owned())
163                .to_string()
164                .contains("`@scope/name`")
165        );
166    }
167
168    #[test]
169    fn a_name_is_a_string_in_json() {
170        let name: PackName = serde_json::from_str(r#""@kit/mermaid""#).expect("a name");
171        assert_eq!(
172            serde_json::to_string(&name).expect("JSON"),
173            r#""@kit/mermaid""#
174        );
175        assert!(serde_json::from_str::<PackName>(r#""mermaid""#).is_err());
176        assert_eq!(String::from(name), "@kit/mermaid");
177        assert_eq!(
178            PackName::try_from("@kit/x".to_owned()),
179            PackName::new("@kit/x")
180        );
181    }
182}