docsrs_cli/domain/
version.rs1use 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#[repr(transparent)]
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17pub struct VersionArg(String);
18
19impl VersionArg {
20 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 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 #[must_use]
82 pub fn as_str(&self) -> &str {
83 &self.0
84 }
85
86 #[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 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}