Skip to main content

docsrs_cli/domain/
version.rs

1//! Validated crate version token.
2
3use std::fmt;
4use std::str::FromStr;
5use std::sync::LazyLock;
6
7use regex::Regex;
8
9use crate::config::MAX_VERSION_CHARS;
10use crate::error::{AppError, AppResult, ErrorDetail, Subject};
11
12use super::regex::compile_bounded_regex;
13
14/// Validated crate version token (`latest`, channel, or SemVer without `v` prefix).
15#[repr(transparent)]
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17pub struct VersionArg(String);
18
19impl VersionArg {
20    /// Parse optional CLI version; empty/`None` → `latest`.
21    ///
22    /// # Errors
23    ///
24    /// Propagates [`crate::error::ErrorKind::InvalidInput`] from [`Self::parse`] when the
25    /// provided token is present and invalid.
26    pub fn parse_opt(raw: Option<&str>) -> AppResult<Self> {
27        let v = raw
28            .map(str::trim)
29            .filter(|s| !s.is_empty())
30            .unwrap_or("latest");
31        Self::parse(v)
32    }
33
34    /// Parses a non-optional version token.
35    ///
36    /// # Errors
37    ///
38    /// Returns [`crate::error::ErrorKind::InvalidInput`] for unknown channels, `v`-prefixed
39    /// SemVer, build metadata, or malformed versions.
40    ///
41    /// # Panics
42    ///
43    /// Panics only if the hardcoded semver-ish regex fails to compile inside its
44    /// [`std::sync::LazyLock`]. The pattern is a compile-time literal well under
45    /// the bounded `size_limit` / `dfa_size_limit`, so no runtime input can reach
46    /// this path.
47    pub fn parse(v: &str) -> AppResult<Self> {
48        let v = v.trim();
49        if v.chars().count() > MAX_VERSION_CHARS {
50            return Err(AppError::of(ErrorDetail::TooLong {
51                subject: Subject::Version,
52                limit: MAX_VERSION_CHARS,
53            }));
54        }
55        if v == "latest" {
56            return Ok(Self(v.to_string()));
57        }
58        if matches!(v, "stable" | "beta" | "nightly") {
59            return Ok(Self(v.to_string()));
60        }
61        if v.starts_with('v') || v.starts_with('V') {
62            return Err(AppError::of(ErrorDetail::VersionVPrefix));
63        }
64        if v.contains('+') {
65            return Err(AppError::of(ErrorDetail::VersionBuildMetadata));
66        }
67        static RE: LazyLock<Regex> = LazyLock::new(|| {
68            compile_bounded_regex(r"^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$")
69                .expect("hardcoded semver-ish version regex is valid by construction")
70        });
71        if !RE.is_match(v) {
72            return Err(AppError::of(ErrorDetail::Invalid {
73                subject: Subject::Version,
74                value: v.to_string(),
75            }));
76        }
77        Ok(Self(v.to_string()))
78    }
79
80    /// Borrow the version token.
81    #[must_use]
82    pub fn as_str(&self) -> &str {
83        &self.0
84    }
85
86    /// Map to rustdoc channel for stdlib paths (`latest` → `stable`).
87    ///
88    /// Single source of truth for channel mapping (TYPE-L-010).
89    #[must_use]
90    pub fn stdlib_channel(&self) -> &str {
91        match self.as_str() {
92            "latest" => "stable",
93            other => other,
94        }
95    }
96}
97
98impl AsRef<str> for VersionArg {
99    fn as_ref(&self) -> &str {
100        self.as_str()
101    }
102}
103
104impl fmt::Display for VersionArg {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        f.write_str(self.as_str())
107    }
108}
109
110impl FromStr for VersionArg {
111    type Err = AppError;
112
113    /// Parses via [`VersionArg::parse`].
114    ///
115    /// # Errors
116    ///
117    /// Returns [`crate::error::ErrorKind::InvalidInput`] for unknown channels or malformed versions.
118    fn from_str(s: &str) -> Result<Self, Self::Err> {
119        Self::parse(s)
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use std::mem::size_of;
127
128    #[test]
129    fn version_arg_policy() {
130        assert_eq!(VersionArg::parse_opt(None).unwrap().as_str(), "latest");
131        assert_eq!(VersionArg::parse_opt(Some("")).unwrap().as_str(), "latest");
132        assert_eq!(VersionArg::parse("1.0.0").unwrap().as_str(), "1.0.0");
133        assert_eq!(
134            VersionArg::parse("stable").unwrap().stdlib_channel(),
135            "stable"
136        );
137        assert_eq!(
138            VersionArg::parse("latest").unwrap().stdlib_channel(),
139            "stable"
140        );
141        assert!(VersionArg::parse("v1.0.0").is_err());
142        assert!(VersionArg::parse("1.0.0+build").is_err());
143        assert!(VersionArg::parse("not-a-version").is_err());
144    }
145
146    #[test]
147    fn version_arg_transparent_layout() {
148        assert_eq!(size_of::<VersionArg>(), size_of::<String>());
149    }
150}