Skip to main content

docsrs_cli/docs_rs/
urls.rs

1//! docs.rs / doc.rust-lang.org URL builders and path helpers.
2//!
3//! Pure URL construction — no HTTP, no HTML parse (one-shot safe).
4//! Callers pass domain newtypes so validity is proven by the type (ADR 0006).
5
6use url::Url;
7
8use crate::domain::{AllowedOrigin, CrateName, VersionArg};
9use crate::error::{AppError, AppResult, ErrorKind};
10use crate::item_kind::{ItemKind, rustc_crate_name};
11
12use super::hits::{leaf_eq_ignore_ascii, unique_best_score_hit};
13use super::types::SearchInCrateHit;
14
15fn default_docs_origin(crate_name: &CrateName) -> AllowedOrigin {
16    if crate_name.is_stdlib() {
17        AllowedOrigin::stdlib_docs_default()
18    } else {
19        AllowedOrigin::docs_rs_default()
20    }
21}
22
23/// Build crate index URL with rustc hyphen→underscore segment.
24///
25/// # Errors
26///
27/// Propagates [`ErrorKind::Internal`] from [`readme_url_on_origin`] when the URL is invalid.
28pub fn readme_url(crate_name: &CrateName, version: &VersionArg) -> AppResult<Url> {
29    readme_url_on_origin(&default_docs_origin(crate_name), crate_name, version)
30}
31
32/// Build readme URL against an allowlisted origin (production or wiremock).
33///
34/// # Errors
35///
36/// Returns [`ErrorKind::Internal`] when `origin` / path segments do not form a valid URL.
37pub fn readme_url_on_origin(
38    origin: &AllowedOrigin,
39    crate_name: &CrateName,
40    version: &VersionArg,
41) -> AppResult<Url> {
42    let origin = origin.as_str().trim_end_matches('/');
43    let s = if crate_name.is_stdlib() {
44        // doc.rust-lang.org/{channel}/{crate}/index.html
45        let channel = version.stdlib_channel();
46        format!("{origin}/{channel}/{crate_name}/index.html")
47    } else {
48        let rustc = rustc_crate_name(crate_name.as_str());
49        format!("{origin}/{crate_name}/{version}/{rustc}/index.html")
50    };
51    Url::parse(&s).map_err(|e| AppError::with_source(ErrorKind::Internal, "invalid readme URL", e))
52}
53
54/// Build rustdoc item or module URL.
55///
56/// # Errors
57///
58/// Propagates [`ErrorKind::InvalidInput`] or [`ErrorKind::Internal`] from
59/// [`get_item_url_on_origin`].
60pub fn get_item_url(
61    crate_name: &CrateName,
62    version: &VersionArg,
63    kind: ItemKind,
64    segments: &[String],
65) -> AppResult<Url> {
66    get_item_url_on_origin(
67        &default_docs_origin(crate_name),
68        crate_name,
69        version,
70        kind,
71        segments,
72    )
73}
74
75/// Detect associated method / inherent method path: `Type::method` where Type is
76/// UpperCamel and method starts lowercase (or kind forced as method via parse alias).
77///
78/// `segs` must already have the crate-root prefix stripped (see
79/// [`strip_crate_prefix_segments`]).
80pub fn is_method_path(kind: ItemKind, segs: &[String]) -> bool {
81    if segs.len() < 2 {
82        return false;
83    }
84    if kind != ItemKind::Fn {
85        return false;
86    }
87    let parent = segs[segs.len() - 2].as_str();
88    let method = segs[segs.len() - 1].as_str();
89    let parent_type = parent
90        .chars()
91        .next()
92        .is_some_and(|c| c.is_ascii_uppercase());
93    let method_fn = method
94        .chars()
95        .next()
96        .is_some_and(|c| c.is_ascii_lowercase() || c == '_');
97    parent_type && method_fn
98}
99
100/// Strip leading crate name / rustc root from item path segments (same rules as URL builder).
101pub fn strip_crate_prefix_segments(
102    crate_name: &CrateName,
103    kind: ItemKind,
104    segments: &[String],
105) -> Vec<String> {
106    let rustc_root = rustc_crate_name(crate_name.as_str());
107    let mut s = segments.to_vec();
108    if let Some(first) = s.first() {
109        let f = first.as_str();
110        let is_crate_prefix = f == crate_name.as_str() || f == rustc_root.as_str();
111        if is_crate_prefix && (s.len() >= 2 || kind == ItemKind::Module) {
112            s.remove(0);
113        }
114    }
115    s
116}
117
118/// Parent type kinds accepted when resolving a short method path via all.html.
119pub const METHOD_PARENT_KIND_NAMES: &[&str] = &["struct", "enum", "trait", "type", "union"];
120
121/// Pick a unique parent type path for `Type::method` short forms (e.g. `Runtime` → `runtime::Runtime`).
122///
123/// Exact leaf match among struct/enum/trait/type/union only. When several exact
124/// leaves exist, prefers a unique best `score` (lower is better).
125pub fn pick_unique_type_path(leaf: &str, hits: &[SearchInCrateHit]) -> Option<String> {
126    let needle = leaf.trim().to_ascii_lowercase();
127    if needle.is_empty() {
128        return None;
129    }
130    let exact: Vec<&SearchInCrateHit> = hits
131        .iter()
132        .filter(|h| {
133            METHOD_PARENT_KIND_NAMES.contains(&h.kind.as_str())
134                && leaf_eq_ignore_ascii(&h.name, &needle)
135        })
136        .collect();
137    if exact.len() == 1 {
138        return Some(exact[0].name.clone());
139    }
140    if exact.is_empty() {
141        return None;
142    }
143    // Prefer struct when multiple kinds share the same leaf (rare).
144    let structs: Vec<_> = exact.iter().filter(|h| h.kind == "struct").copied().collect();
145    if structs.len() == 1 {
146        return Some(structs[0].name.clone());
147    }
148    unique_best_score_hit(exact.into_iter()).map(|h| h.name.clone())
149}
150
151/// Build method path segments from a resolved parent type path + method leaf.
152pub fn method_segments_from_parent(parent_path: &str, method_leaf: &str) -> Vec<String> {
153    let mut segs: Vec<String> = parent_path
154        .split("::")
155        .filter(|s| !s.is_empty())
156        .map(str::to_string)
157        .collect();
158    segs.push(method_leaf.to_string());
159    segs
160}
161
162/// Parent type kinds tried when resolving a method URL (struct first — common case).
163pub(super) const METHOD_PARENT_KINDS: &[ItemKind] = &[
164    ItemKind::Struct,
165    ItemKind::Enum,
166    ItemKind::Trait,
167    ItemKind::Type,
168    ItemKind::Union,
169];
170
171/// Build get-item URL against a custom origin (wiremock tests).
172///
173/// Associated methods (`Runtime::new`) resolve to the parent type page plus
174/// `#method.{name}` (rustdoc layout). Free functions keep `{kind}.{name}.html`.
175///
176/// # Errors
177///
178/// Returns [`ErrorKind::InvalidInput`] when a non-module path lacks an item name.
179/// Returns [`ErrorKind::Internal`] when the assembled path is not a valid URL.
180pub fn get_item_url_on_origin(
181    origin: &AllowedOrigin,
182    crate_name: &CrateName,
183    version: &VersionArg,
184    kind: ItemKind,
185    segments: &[String],
186) -> AppResult<Url> {
187    get_item_url_on_origin_with_parent_kind(origin, crate_name, version, kind, segments, None)
188}
189
190/// Like [`get_item_url_on_origin`] but forces the parent type kind for methods.
191pub fn get_item_url_on_origin_with_parent_kind(
192    origin: &AllowedOrigin,
193    crate_name: &CrateName,
194    version: &VersionArg,
195    kind: ItemKind,
196    segments: &[String],
197    parent_kind_override: Option<ItemKind>,
198) -> AppResult<Url> {
199    let origin = origin.as_str().trim_end_matches('/');
200    let rustc_root = rustc_crate_name(crate_name.as_str());
201    let segs: Vec<String> = {
202        let mut s = segments.to_vec();
203        if let Some(first) = s.first() {
204            let f = first.as_str();
205            let is_crate_prefix = f == crate_name.as_str() || f == rustc_root.as_str();
206            if is_crate_prefix && (s.len() >= 2 || kind == ItemKind::Module) {
207                s.remove(0);
208            }
209        }
210        s
211    };
212
213    // Associated method: Type::method → parent page + #method.name
214    if is_method_path(kind, &segs) {
215        // is_method_path requires ≥2 segments; fail closed if invariant breaks.
216        let (parent_name, method_name) = match segs.as_slice() {
217            [.., parent, method] => (parent.clone(), method.clone()),
218            _ => {
219                return Err(AppError::new(
220                    ErrorKind::Internal,
221                    "method path invariant broken: expected at least 2 segments",
222                ));
223            }
224        };
225        let parent_kind = parent_kind_override.unwrap_or(ItemKind::Struct);
226        let mod_parts: Vec<String> = if segs.len() == 2 {
227            if crate_name.is_stdlib() {
228                Vec::new()
229            } else {
230                vec![rustc_root.clone()]
231            }
232        } else {
233            let mut m = if crate_name.is_stdlib() {
234                Vec::new()
235            } else {
236                vec![rustc_root.clone()]
237            };
238            for p in &segs[..segs.len() - 2] {
239                m.push(rustc_crate_name(p));
240            }
241            m
242        };
243        let url_str = if crate_name.is_stdlib() {
244            let channel = version.stdlib_channel();
245            if mod_parts.is_empty() {
246                format!(
247                    "{origin}/{channel}/{crate_name}/{}.{}.html#method.{method_name}",
248                    parent_kind.file_prefix(),
249                    parent_name
250                )
251            } else {
252                format!(
253                    "{origin}/{channel}/{crate_name}/{}/{}.{}.html#method.{method_name}",
254                    mod_parts.join("/"),
255                    parent_kind.file_prefix(),
256                    parent_name
257                )
258            }
259        } else if mod_parts.is_empty() {
260            format!(
261                "{origin}/{crate_name}/{version}/{}/{}.{}.html#method.{method_name}",
262                rustc_root,
263                parent_kind.file_prefix(),
264                parent_name
265            )
266        } else {
267            format!(
268                "{origin}/{crate_name}/{version}/{}/{}.{}.html#method.{method_name}",
269                mod_parts.join("/"),
270                parent_kind.file_prefix(),
271                parent_name
272            )
273        };
274        return Url::parse(&url_str)
275            .map_err(|e| AppError::with_source(ErrorKind::Internal, "invalid get-item URL", e));
276    }
277
278    let url_str = if crate_name.is_stdlib() {
279        let channel = version.stdlib_channel();
280        if kind == ItemKind::Module {
281            let mut parts: Vec<String> = Vec::new();
282            for p in &segs {
283                parts.push(rustc_crate_name(p));
284            }
285            if parts.is_empty() {
286                format!("{origin}/{channel}/{crate_name}/index.html")
287            } else {
288                format!(
289                    "{origin}/{channel}/{crate_name}/{}/index.html",
290                    parts.join("/")
291                )
292            }
293        } else {
294            if segs.is_empty() {
295                return Err(AppError::new(
296                    ErrorKind::InvalidInput,
297                    "item path missing item name",
298                ));
299            }
300            let item_name = segs.last().ok_or_else(|| {
301                AppError::new(ErrorKind::InvalidInput, "item path missing item name")
302            })?;
303            let mod_parts: Vec<String> = segs[..segs.len().saturating_sub(1)]
304                .iter()
305                .map(|p| rustc_crate_name(p))
306                .collect();
307            if mod_parts.is_empty() {
308                format!(
309                    "{origin}/{channel}/{crate_name}/{}.{}.html",
310                    kind.file_prefix(),
311                    item_name
312                )
313            } else {
314                format!(
315                    "{origin}/{channel}/{crate_name}/{}/{}.{}.html",
316                    mod_parts.join("/"),
317                    kind.file_prefix(),
318                    item_name
319                )
320            }
321        }
322    } else if kind == ItemKind::Module {
323        let mut parts: Vec<String> = vec![rustc_root];
324        for p in &segs {
325            parts.push(rustc_crate_name(p));
326        }
327        format!(
328            "{origin}/{crate_name}/{version}/{}/index.html",
329            parts.join("/")
330        )
331    } else {
332        if segs.is_empty() {
333            return Err(AppError::new(
334                ErrorKind::InvalidInput,
335                "item path missing item name",
336            ));
337        }
338        let item_name = segs
339            .last()
340            .ok_or_else(|| AppError::new(ErrorKind::InvalidInput, "item path missing item name"))?;
341        let mod_parts: Vec<String> = if segs.len() == 1 {
342            vec![rustc_root]
343        } else {
344            let mut m = vec![rustc_root];
345            for p in &segs[..segs.len() - 1] {
346                m.push(rustc_crate_name(p));
347            }
348            m
349        };
350        format!(
351            "{origin}/{crate_name}/{version}/{}/{}.{}.html",
352            mod_parts.join("/"),
353            kind.file_prefix(),
354            item_name
355        )
356    };
357
358    Url::parse(&url_str)
359        .map_err(|e| AppError::with_source(ErrorKind::Internal, "invalid get-item URL", e))
360}
361
362/// Build all.html index URL.
363///
364/// # Errors
365///
366/// Propagates [`ErrorKind::Internal`] from [`all_html_url_on_origin`].
367pub fn all_html_url(crate_name: &CrateName, version: &VersionArg) -> AppResult<Url> {
368    all_html_url_on_origin(&default_docs_origin(crate_name), crate_name, version)
369}
370
371/// Build all.html URL against an allowlisted origin (production or wiremock).
372///
373/// # Errors
374///
375/// Returns [`ErrorKind::Internal`] when `origin` / path segments do not form a valid URL.
376pub fn all_html_url_on_origin(
377    origin: &AllowedOrigin,
378    crate_name: &CrateName,
379    version: &VersionArg,
380) -> AppResult<Url> {
381    let origin = origin.as_str().trim_end_matches('/');
382    let s = if crate_name.is_stdlib() {
383        let channel = version.stdlib_channel();
384        format!("{origin}/{channel}/{crate_name}/all.html")
385    } else {
386        let rustc = rustc_crate_name(crate_name.as_str());
387        format!("{origin}/{crate_name}/{version}/{rustc}/all.html")
388    };
389    Url::parse(&s)
390        .map_err(|e| AppError::with_source(ErrorKind::Internal, "invalid all.html URL", e))
391}