docsrs_cli/domain/
item_path.rs1use std::fmt;
4use std::str::FromStr;
5
6use crate::config::MAX_ITEM_PATH_CHARS;
7use crate::error::{AppError, AppResult, ErrorKind};
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct ItemPath {
12 raw: String,
14 segments: Vec<String>,
16}
17
18impl ItemPath {
19 pub fn parse(path: &str) -> AppResult<Self> {
26 let path = path.trim();
27 if path.is_empty() || path == "::" || path == "/" {
28 return Err(AppError::new(ErrorKind::InvalidInput, "item path is empty"));
29 }
30 if path.chars().count() > MAX_ITEM_PATH_CHARS {
31 return Err(AppError::new(
32 ErrorKind::InvalidInput,
33 format!("item path exceeds {MAX_ITEM_PATH_CHARS} characters"),
34 ));
35 }
36 let normalized = path.replace('/', "::");
37 let parts: Vec<String> = normalized
38 .split("::")
39 .map(|s| s.trim().to_string())
40 .filter(|s| !s.is_empty())
41 .collect();
42 if parts.is_empty() {
43 return Err(AppError::new(
44 ErrorKind::InvalidInput,
45 "item path has no segments",
46 ));
47 }
48 let mut segments = Vec::with_capacity(parts.len());
49 for seg in &parts {
50 if seg == "." || seg == ".." {
51 return Err(AppError::new(
52 ErrorKind::InvalidInput,
53 format!("invalid item path segment '{seg}'"),
54 ));
55 }
56 if seg.chars().any(|c| c.is_whitespace()) {
57 return Err(AppError::new(
58 ErrorKind::InvalidInput,
59 format!("item path segment contains whitespace: '{seg}'"),
60 ));
61 }
62 if !seg
64 .chars()
65 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
66 {
67 return Err(AppError::new(
68 ErrorKind::InvalidInput,
69 format!(
70 "invalid item path segment '{seg}' (use letters, digits, underscore or hyphen; hyphens normalize to underscore; separate with :: or /)"
71 ),
72 ));
73 }
74 segments.push(crate::item_kind::rustc_crate_name(seg));
75 }
76 Ok(Self {
77 raw: path.to_string(),
78 segments,
79 })
80 }
81
82 #[must_use]
84 pub fn segments(&self) -> &[String] {
85 &self.segments
86 }
87
88 #[must_use]
90 pub fn into_segments(self) -> Vec<String> {
91 self.segments
92 }
93
94 #[must_use]
96 pub fn as_str(&self) -> &str {
97 &self.raw
98 }
99}
100
101impl AsRef<str> for ItemPath {
102 fn as_ref(&self) -> &str {
103 self.as_str()
104 }
105}
106
107impl fmt::Display for ItemPath {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 f.write_str(&self.segments.join("::"))
110 }
111}
112
113impl FromStr for ItemPath {
114 type Err = AppError;
115
116 fn from_str(s: &str) -> Result<Self, Self::Err> {
122 Self::parse(s)
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129 use crate::config::MAX_ITEM_PATH_CHARS;
130
131 #[test]
132 fn item_path_segments_and_display() {
133 let p = ItemPath::parse("clap::Parser").unwrap();
134 assert_eq!(p.segments(), &["clap".to_string(), "Parser".to_string()]);
135 assert_eq!(p.to_string(), "clap::Parser");
136 let slash = ItemPath::parse("runtime/Runtime").unwrap();
137 assert_eq!(
138 slash.segments(),
139 &["runtime".to_string(), "Runtime".to_string()]
140 );
141 assert_eq!(
142 ItemPath::parse("async_trait").unwrap().segments(),
143 &["async_trait".to_string()]
144 );
145 assert_eq!(
147 ItemPath::parse("async-trait").unwrap().segments(),
148 &["async_trait".to_string()]
149 );
150 assert_eq!(
151 ItemPath::parse("foo-bar::Baz-Quux").unwrap().segments(),
152 &["foo_bar".to_string(), "Baz_Quux".to_string()]
153 );
154 }
155
156 #[test]
157 fn item_path_err() {
158 assert!(ItemPath::parse("").is_err());
159 assert!(ItemPath::parse("::").is_err());
160 assert!(ItemPath::parse("has space").is_err());
161 assert!(ItemPath::parse("foo.bar").is_err());
162 assert!(ItemPath::parse("..").is_err());
163 assert!(ItemPath::parse("a/../b").is_err());
164 assert!(ItemPath::parse(&format!("a::{}", "b".repeat(MAX_ITEM_PATH_CHARS))).is_err());
165 }
166}