Skip to main content

docsrs_cli/
domain.rs

1//! Domain newtypes: parse at the boundary, carry validity in the type.
2//!
3//! Follows parse-don't-validate: only fallible constructors build values.
4
5use std::fmt;
6use std::str::FromStr;
7use std::sync::LazyLock;
8
9use regex::Regex;
10
11use crate::config::{
12    MAX_CRATE_NAME_CHARS, MAX_ITEM_PATH_CHARS, MAX_QUERY_CHARS, MAX_VERSION_CHARS,
13};
14use crate::error::{AppError, AppResult, ErrorKind};
15
16/// Validated crates.io / stdlib crate name.
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18pub struct CrateName(String);
19
20impl CrateName {
21    /// Parses and validates a crate name (trim, length, charset).
22    ///
23    /// # Errors
24    ///
25    /// Returns [`ErrorKind::InvalidInput`] when the name is empty, too long, or
26    /// contains characters outside the crates.io charset.
27    ///
28    /// # Examples
29    ///
30    /// ```
31    /// use docsrs_cli::domain::CrateName;
32    ///
33    /// let name = CrateName::parse("tokio").expect("valid");
34    /// assert_eq!(name.as_str(), "tokio");
35    /// assert!(CrateName::parse("").is_err());
36    /// ```
37    pub fn parse(name: &str) -> AppResult<Self> {
38        let name = name.trim();
39        if name.is_empty() {
40            return Err(AppError::new(
41                ErrorKind::InvalidInput,
42                "crate name is empty",
43            ));
44        }
45        if name.chars().count() > MAX_CRATE_NAME_CHARS {
46            return Err(AppError::new(
47                ErrorKind::InvalidInput,
48                format!("crate name exceeds {MAX_CRATE_NAME_CHARS} characters"),
49            ));
50        }
51        static RE: LazyLock<Regex> = LazyLock::new(|| {
52            Regex::new(r"^[a-zA-Z][a-zA-Z0-9_-]*$")
53                .expect("hardcoded crate-name regex is valid by construction")
54        });
55        if !RE.is_match(name) {
56            return Err(AppError::new(
57                ErrorKind::InvalidInput,
58                format!("invalid crate name '{name}'"),
59            ));
60        }
61        Ok(Self(name.to_string()))
62    }
63
64    /// Borrow the validated name.
65    pub fn as_str(&self) -> &str {
66        &self.0
67    }
68
69    /// True for `std` / `core` / `alloc` (docs on doc.rust-lang.org).
70    pub fn is_stdlib(&self) -> bool {
71        matches!(self.0.as_str(), "std" | "core" | "alloc")
72    }
73}
74
75impl AsRef<str> for CrateName {
76    fn as_ref(&self) -> &str {
77        self.as_str()
78    }
79}
80
81impl fmt::Display for CrateName {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        f.write_str(self.as_str())
84    }
85}
86
87impl FromStr for CrateName {
88    type Err = AppError;
89
90    /// Parses via [`CrateName::parse`].
91    ///
92    /// # Errors
93    ///
94    /// Returns [`ErrorKind::InvalidInput`] for empty, oversized, or illegal names.
95    fn from_str(s: &str) -> Result<Self, Self::Err> {
96        Self::parse(s)
97    }
98}
99
100impl TryFrom<&str> for CrateName {
101    type Error = AppError;
102
103    /// Converts via [`CrateName::parse`].
104    ///
105    /// # Errors
106    ///
107    /// Returns [`ErrorKind::InvalidInput`] for empty, oversized, or illegal names.
108    fn try_from(value: &str) -> Result<Self, Self::Error> {
109        Self::parse(value)
110    }
111}
112
113/// Validated rustdoc item path (`tokio::runtime::Runtime` or `runtime/Runtime`).
114#[derive(Debug, Clone, PartialEq, Eq, Hash)]
115pub struct ItemPath {
116    /// Original trimmed input (preserves `::` vs `/` only for Display of raw when needed).
117    raw: String,
118    /// Normalized path segments.
119    segments: Vec<String>,
120}
121
122impl ItemPath {
123    /// Parses an item path with `::` or `/` separators.
124    ///
125    /// # Errors
126    ///
127    /// Returns [`ErrorKind::InvalidInput`] when the path is empty, too long, or
128    /// contains `.` / `..` segments.
129    pub fn parse(path: &str) -> AppResult<Self> {
130        let path = path.trim();
131        if path.is_empty() || path == "::" || path == "/" {
132            return Err(AppError::new(ErrorKind::InvalidInput, "item path is empty"));
133        }
134        if path.chars().count() > MAX_ITEM_PATH_CHARS {
135            return Err(AppError::new(
136                ErrorKind::InvalidInput,
137                format!("item path exceeds {MAX_ITEM_PATH_CHARS} characters"),
138            ));
139        }
140        let normalized = path.replace('/', "::");
141        let parts: Vec<String> = normalized
142            .split("::")
143            .map(|s| s.trim().to_string())
144            .filter(|s| !s.is_empty())
145            .collect();
146        if parts.is_empty() {
147            return Err(AppError::new(
148                ErrorKind::InvalidInput,
149                "item path has no segments",
150            ));
151        }
152        for seg in &parts {
153            if seg == "." || seg == ".." {
154                return Err(AppError::new(
155                    ErrorKind::InvalidInput,
156                    format!("invalid item path segment '{seg}'"),
157                ));
158            }
159            if seg.chars().any(|c| c.is_whitespace()) {
160                return Err(AppError::new(
161                    ErrorKind::InvalidInput,
162                    format!("item path segment contains whitespace: '{seg}'"),
163                ));
164            }
165            if !seg.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
166                return Err(AppError::new(
167                    ErrorKind::InvalidInput,
168                    format!(
169                        "invalid item path segment '{seg}' (use letters, digits, underscore; separate with :: or /)"
170                    ),
171                ));
172            }
173        }
174        Ok(Self {
175            raw: path.to_string(),
176            segments: parts,
177        })
178    }
179
180    /// Path segments after normalization.
181    pub fn segments(&self) -> &[String] {
182        &self.segments
183    }
184
185    /// Owned segment list (for APIs that still take `Vec<String>`).
186    pub fn into_segments(self) -> Vec<String> {
187        self.segments
188    }
189
190    /// Original trimmed input string.
191    pub fn as_str(&self) -> &str {
192        &self.raw
193    }
194}
195
196impl AsRef<str> for ItemPath {
197    fn as_ref(&self) -> &str {
198        self.as_str()
199    }
200}
201
202impl fmt::Display for ItemPath {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        f.write_str(&self.segments.join("::"))
205    }
206}
207
208impl FromStr for ItemPath {
209    type Err = AppError;
210
211    /// Parses via [`ItemPath::parse`].
212    ///
213    /// # Errors
214    ///
215    /// Returns [`ErrorKind::InvalidInput`] for empty, oversized, or illegal paths.
216    fn from_str(s: &str) -> Result<Self, Self::Err> {
217        Self::parse(s)
218    }
219}
220
221/// Validated search query string.
222#[derive(Debug, Clone, PartialEq, Eq, Hash)]
223pub struct SearchQuery(String);
224
225impl SearchQuery {
226    /// Parses a search query.
227    ///
228    /// When `allow_empty` is true, whitespace-only becomes an empty query (list-all).
229    ///
230    /// # Errors
231    ///
232    /// Returns [`ErrorKind::InvalidInput`] when the query is empty without
233    /// `allow_empty`, or when it exceeds the maximum length.
234    pub fn parse(query: &str, allow_empty: bool) -> AppResult<Self> {
235        let q = query.trim();
236        if !allow_empty && q.is_empty() {
237            return Err(AppError::new(
238                ErrorKind::InvalidInput,
239                "search query is empty",
240            ));
241        }
242        if q.chars().count() > MAX_QUERY_CHARS {
243            return Err(AppError::new(
244                ErrorKind::InvalidInput,
245                format!("query exceeds {MAX_QUERY_CHARS} characters"),
246            ));
247        }
248        Ok(Self(q.to_string()))
249    }
250
251    /// Borrow the validated query.
252    pub fn as_str(&self) -> &str {
253        &self.0
254    }
255}
256
257impl AsRef<str> for SearchQuery {
258    fn as_ref(&self) -> &str {
259        self.as_str()
260    }
261}
262
263impl fmt::Display for SearchQuery {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        f.write_str(self.as_str())
266    }
267}
268
269/// Validated crate version token (`latest`, channel, or SemVer without `v` prefix).
270#[derive(Debug, Clone, PartialEq, Eq, Hash)]
271pub struct VersionArg(String);
272
273impl VersionArg {
274    /// Parse optional CLI version; empty/`None` → `latest`.
275    ///
276    /// # Errors
277    ///
278    /// Propagates [`ErrorKind::InvalidInput`] from [`Self::parse`] when the
279    /// provided token is present and invalid.
280    pub fn parse_opt(raw: Option<&str>) -> AppResult<Self> {
281        let v = raw
282            .map(str::trim)
283            .filter(|s| !s.is_empty())
284            .unwrap_or("latest");
285        Self::parse(v)
286    }
287
288    /// Parses a non-optional version token.
289    ///
290    /// # Errors
291    ///
292    /// Returns [`ErrorKind::InvalidInput`] for unknown channels, `v`-prefixed
293    /// SemVer, build metadata, or malformed versions.
294    pub fn parse(v: &str) -> AppResult<Self> {
295        let v = v.trim();
296        if v.chars().count() > MAX_VERSION_CHARS {
297            return Err(AppError::new(
298                ErrorKind::InvalidInput,
299                format!("version exceeds {MAX_VERSION_CHARS} characters"),
300            ));
301        }
302        if v == "latest" {
303            return Ok(Self(v.to_string()));
304        }
305        if matches!(v, "stable" | "beta" | "nightly") {
306            return Ok(Self(v.to_string()));
307        }
308        if v.starts_with('v') || v.starts_with('V') {
309            return Err(AppError::new(
310                ErrorKind::InvalidInput,
311                "version must not start with 'v' prefix",
312            ));
313        }
314        if v.contains('+') {
315            return Err(AppError::new(
316                ErrorKind::InvalidInput,
317                "version build metadata is not accepted",
318            ));
319        }
320        static RE: LazyLock<Regex> = LazyLock::new(|| {
321            Regex::new(r"^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$")
322                .expect("hardcoded semver-ish version regex is valid by construction")
323        });
324        if !RE.is_match(v) {
325            return Err(AppError::new(
326                ErrorKind::InvalidInput,
327                format!("invalid version '{v}'"),
328            ));
329        }
330        Ok(Self(v.to_string()))
331    }
332
333    /// Borrow the version token.
334    pub fn as_str(&self) -> &str {
335        &self.0
336    }
337
338    /// Map to rustdoc channel for stdlib paths (`latest` → `stable`).
339    pub fn stdlib_channel(&self) -> &str {
340        crate::config::stdlib_channel(self.as_str())
341    }
342}
343
344impl AsRef<str> for VersionArg {
345    fn as_ref(&self) -> &str {
346        self.as_str()
347    }
348}
349
350impl fmt::Display for VersionArg {
351    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352        f.write_str(self.as_str())
353    }
354}
355
356impl FromStr for VersionArg {
357    type Err = AppError;
358
359    /// Parses via [`VersionArg::parse`].
360    ///
361    /// # Errors
362    ///
363    /// Returns [`ErrorKind::InvalidInput`] for unknown channels or malformed versions.
364    fn from_str(s: &str) -> Result<Self, Self::Err> {
365        Self::parse(s)
366    }
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn crate_name_ok_and_stdlib() {
375        let s = CrateName::parse("serde").unwrap();
376        assert_eq!(s.as_str(), "serde");
377        assert!(!s.is_stdlib());
378        assert!(CrateName::parse("async-trait").unwrap().as_str() == "async-trait");
379        for n in ["std", "core", "alloc"] {
380            let c = CrateName::parse(n).unwrap();
381            assert!(c.is_stdlib(), "{n}");
382        }
383    }
384
385    #[test]
386    fn crate_name_err() {
387        assert!(CrateName::parse("").is_err());
388        assert!(CrateName::parse("1bad").is_err());
389        assert!(CrateName::parse(&"a".repeat(MAX_CRATE_NAME_CHARS + 1)).is_err());
390    }
391
392    #[test]
393    fn item_path_segments_and_display() {
394        let p = ItemPath::parse("clap::Parser").unwrap();
395        assert_eq!(p.segments(), &["clap".to_string(), "Parser".to_string()]);
396        assert_eq!(p.to_string(), "clap::Parser");
397        let slash = ItemPath::parse("runtime/Runtime").unwrap();
398        assert_eq!(
399            slash.segments(),
400            &["runtime".to_string(), "Runtime".to_string()]
401        );
402        assert_eq!(
403            ItemPath::parse("async_trait").unwrap().segments(),
404            &["async_trait".to_string()]
405        );
406    }
407
408    #[test]
409    fn item_path_err() {
410        assert!(ItemPath::parse("").is_err());
411        assert!(ItemPath::parse("::").is_err());
412        assert!(ItemPath::parse("has space").is_err());
413        assert!(ItemPath::parse("foo.bar").is_err());
414        assert!(ItemPath::parse("..").is_err());
415        assert!(ItemPath::parse("a/../b").is_err());
416    }
417
418    #[test]
419    fn search_query_rules() {
420        assert!(SearchQuery::parse("", false).is_err());
421        assert_eq!(SearchQuery::parse("  ", true).unwrap().as_str(), "");
422        assert_eq!(
423            SearchQuery::parse("serde", false).unwrap().as_str(),
424            "serde"
425        );
426        assert!(SearchQuery::parse(&"q".repeat(MAX_QUERY_CHARS + 1), false).is_err());
427    }
428
429    #[test]
430    fn version_arg_policy() {
431        assert_eq!(VersionArg::parse_opt(None).unwrap().as_str(), "latest");
432        assert_eq!(VersionArg::parse_opt(Some("")).unwrap().as_str(), "latest");
433        assert_eq!(VersionArg::parse("1.0.0").unwrap().as_str(), "1.0.0");
434        assert_eq!(
435            VersionArg::parse("stable").unwrap().stdlib_channel(),
436            "stable"
437        );
438        assert_eq!(
439            VersionArg::parse("latest").unwrap().stdlib_channel(),
440            "stable"
441        );
442        assert!(VersionArg::parse("v1.0.0").is_err());
443        assert!(VersionArg::parse("1.0.0+build").is_err());
444        assert!(VersionArg::parse("not-a-version").is_err());
445    }
446}