Skip to main content

docsrs_cli/domain/
item_path.rs

1//! Validated rustdoc item path.
2
3use std::fmt;
4use std::str::FromStr;
5
6use crate::config::MAX_ITEM_PATH_CHARS;
7use crate::error::{AppError, AppResult, ErrorKind};
8
9/// Validated rustdoc item path (`tokio::runtime::Runtime` or `runtime/Runtime`).
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct ItemPath {
12    /// Original trimmed input (preserves `::` vs `/` only for Display of raw when needed).
13    raw: String,
14    /// Normalized path segments.
15    segments: Vec<String>,
16}
17
18impl ItemPath {
19    /// Parses an item path with `::` or `/` separators.
20    ///
21    /// # Errors
22    ///
23    /// Returns [`ErrorKind::InvalidInput`] when the path is empty, too long, or
24    /// contains `.` / `..` segments.
25    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            // Accept hyphen (crates.io style) and normalize to underscore (rustc paths).
63            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    /// Path segments after normalization.
83    #[must_use]
84    pub fn segments(&self) -> &[String] {
85        &self.segments
86    }
87
88    /// Owned segment list (for APIs that still take `Vec<String>`).
89    #[must_use]
90    pub fn into_segments(self) -> Vec<String> {
91        self.segments
92    }
93
94    /// Original trimmed input string.
95    #[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    /// Parses via [`ItemPath::parse`].
117    ///
118    /// # Errors
119    ///
120    /// Returns [`ErrorKind::InvalidInput`] for empty, oversized, or illegal paths.
121    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        // Hyphen normalizes to underscore (rustc path).
146        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}