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, ErrorDetail, InternalOp};
10use crate::item_kind::{ItemKind, rustc_crate_name};
11
12use super::assoc::{AssocAnchorKind, associated_item_path, member_only_family};
13use super::hits::{leaf_eq_ignore_ascii, unique_best_score_hit};
14use super::types::SearchInCrateHit;
15
16fn default_docs_origin(crate_name: &CrateName) -> AllowedOrigin {
17    if crate_name.is_stdlib() {
18        AllowedOrigin::stdlib_docs_default()
19    } else {
20        AllowedOrigin::docs_rs_default()
21    }
22}
23
24/// Build crate index URL with rustc hyphen→underscore segment.
25///
26/// # Errors
27///
28/// Propagates [`crate::error::ErrorKind::Internal`] from [`readme_url_on_origin`] when the URL is invalid.
29pub fn readme_url(crate_name: &CrateName, version: &VersionArg) -> AppResult<Url> {
30    readme_url_on_origin(&default_docs_origin(crate_name), crate_name, version)
31}
32
33/// Build readme URL against an allowlisted origin (production or wiremock).
34///
35/// # Errors
36///
37/// Returns [`crate::error::ErrorKind::Internal`] when `origin` / path segments do not form a valid URL.
38pub fn readme_url_on_origin(
39    origin: &AllowedOrigin,
40    crate_name: &CrateName,
41    version: &VersionArg,
42) -> AppResult<Url> {
43    let origin = origin.as_str().trim_end_matches('/');
44    let s = if crate_name.is_stdlib() {
45        // doc.rust-lang.org/{channel}/{crate}/index.html
46        let channel = version.stdlib_channel();
47        format!("{origin}/{channel}/{crate_name}/index.html")
48    } else {
49        let rustc = rustc_crate_name(crate_name.as_str());
50        format!("{origin}/{crate_name}/{version}/{rustc}/index.html")
51    };
52    Url::parse(&s).map_err(|e| {
53        AppError::of_with_source(
54            ErrorDetail::Internal {
55                op: InternalOp::UrlBuild,
56            },
57            e,
58        )
59    })
60}
61
62/// Build rustdoc item or module URL.
63///
64/// # Errors
65///
66/// Propagates [`crate::error::ErrorKind::InvalidInput`] or [`crate::error::ErrorKind::Internal`] from
67/// [`get_item_url_on_origin`].
68pub fn get_item_url(
69    crate_name: &CrateName,
70    version: &VersionArg,
71    kind: ItemKind,
72    segments: &[String],
73) -> AppResult<Url> {
74    get_item_url_on_origin(
75        &default_docs_origin(crate_name),
76        crate_name,
77        version,
78        kind,
79        segments,
80    )
81}
82
83/// Detect associated method / inherent method path: `Type::method` where Type is
84/// UpperCamel and method starts lowercase (or kind forced as method via parse alias).
85///
86/// `segs` must already have the crate-root prefix stripped (see
87/// [`strip_crate_prefix_segments`]).
88///
89/// Narrow view of [`associated_item_path`], kept because callers that only care
90/// about functions read better without matching on the family enum.
91pub fn is_method_path(kind: ItemKind, segs: &[String]) -> bool {
92    associated_item_path(kind, segs) == Some(AssocAnchorKind::Method)
93}
94
95/// Strip leading crate name / rustc root from item path segments (same rules as URL builder).
96pub fn strip_crate_prefix_segments(
97    crate_name: &CrateName,
98    kind: ItemKind,
99    segments: &[String],
100) -> Vec<String> {
101    let rustc_root = rustc_crate_name(crate_name.as_str());
102    let mut s = segments.to_vec();
103    if let Some(first) = s.first() {
104        let f = first.as_str();
105        let is_crate_prefix = f == crate_name.as_str() || f == rustc_root.as_str();
106        if is_crate_prefix && (s.len() >= 2 || kind == ItemKind::Module) {
107            s.remove(0);
108        }
109    }
110    s
111}
112
113/// Pick a unique parent type path for `Type::method` short forms (e.g. `Runtime` → `runtime::Runtime`).
114///
115/// Exact leaf match among struct/enum/trait/type/union only. When several exact
116/// leaves exist, prefers a unique best `score` (lower is better).
117pub fn pick_unique_type_path(leaf: &str, hits: &[SearchInCrateHit]) -> Option<String> {
118    let needle = leaf.trim().to_ascii_lowercase();
119    if needle.is_empty() {
120        return None;
121    }
122    let exact: Vec<&SearchInCrateHit> = hits
123        .iter()
124        .filter(|h| {
125            // Same list the live fetch probes, read from the family instead of a
126            // local copy: a parent kind reachable there must be reachable here.
127            AssocAnchorKind::Method
128                .parent_kind_probe()
129                .iter()
130                .any(|k| k.as_str() == h.kind.as_str())
131                && leaf_eq_ignore_ascii(&h.name, &needle)
132        })
133        .collect();
134    if exact.len() == 1 {
135        return Some(exact[0].name.clone());
136    }
137    if exact.is_empty() {
138        return None;
139    }
140    // Prefer struct when multiple kinds share the same leaf (rare).
141    let structs: Vec<_> = exact
142        .iter()
143        .filter(|h| h.kind == "struct")
144        .copied()
145        .collect();
146    if structs.len() == 1 {
147        return Some(structs[0].name.clone());
148    }
149    unique_best_score_hit(exact.into_iter()).map(|h| h.name.clone())
150}
151
152/// Build method path segments from a resolved parent type path + method leaf.
153pub fn method_segments_from_parent(parent_path: &str, method_leaf: &str) -> Vec<String> {
154    let mut segs: Vec<String> = parent_path
155        .split("::")
156        .filter(|s| !s.is_empty())
157        .map(str::to_string)
158        .collect();
159    segs.push(method_leaf.to_string());
160    segs
161}
162
163/// Build get-item URL against a custom origin (wiremock tests).
164///
165/// Associated items (`Runtime::new`, `Iterator::Item`, `Duration::MAX`) resolve
166/// to the parent page plus the family's anchor fragment (rustdoc layout). Free
167/// items keep `{kind}.{name}.html`.
168///
169/// # Errors
170///
171/// Returns [`crate::error::ErrorKind::InvalidInput`] when a non-module path lacks an item name.
172/// Returns [`crate::error::ErrorKind::Internal`] when the assembled path is not a valid URL.
173pub fn get_item_url_on_origin(
174    origin: &AllowedOrigin,
175    crate_name: &CrateName,
176    version: &VersionArg,
177    kind: ItemKind,
178    segments: &[String],
179) -> AppResult<Url> {
180    get_item_url_on_origin_with_parent_kind(origin, crate_name, version, kind, segments, None)
181}
182
183/// Like [`get_item_url_on_origin`] but forces the parent type kind for methods.
184///
185/// # Errors
186/// Same as [`get_item_url_on_origin`].
187pub fn get_item_url_on_origin_with_parent_kind(
188    origin: &AllowedOrigin,
189    crate_name: &CrateName,
190    version: &VersionArg,
191    kind: ItemKind,
192    segments: &[String],
193    parent_kind_override: Option<ItemKind>,
194) -> AppResult<Url> {
195    let origin = origin.as_str().trim_end_matches('/');
196    let rustc_root = rustc_crate_name(crate_name.as_str());
197    let segs = strip_crate_prefix_segments(crate_name, kind, segments);
198
199    // Associated item: Parent::member → parent page + #{prefix}{member}
200    if let Some(assoc) = associated_item_path(kind, &segs) {
201        // associated_item_path requires ≥2 segments; fail closed if that breaks.
202        let (parent_name, member_name) = match segs.as_slice() {
203            [.., parent, member] => (parent.clone(), member.clone()),
204            _ => {
205                return Err(AppError::of(ErrorDetail::Internal {
206                    op: InternalOp::AssocPathTooShort,
207                }));
208            }
209        };
210        // Only one fragment fits in a URL. The extractor still probes every
211        // prefix of the family against the page it fetches, so a required trait
212        // method planned as `#method.X` still resolves through `#tymethod.X`.
213        let anchor = format!("{}{member_name}", assoc.primary_prefix());
214        // Probe order leads with the kind that hosts this family most often:
215        // traits for associated types, structs for methods and constants.
216        let parent_kind = parent_kind_override.unwrap_or(assoc.parent_kind_probe()[0]);
217        // Every kind in a `parent_kind_probe` list owns a page by construction;
218        // a `None` here would mean the probe tables named a member as a host.
219        let parent_prefix = parent_kind.file_prefix().ok_or_else(|| {
220            AppError::of(ErrorDetail::Internal {
221                op: InternalOp::AssocParentOwnsNoPage,
222            })
223        })?;
224        let mod_parts: Vec<String> = if segs.len() == 2 {
225            if crate_name.is_stdlib() {
226                Vec::new()
227            } else {
228                vec![rustc_root.clone()]
229            }
230        } else {
231            let mut m = if crate_name.is_stdlib() {
232                Vec::new()
233            } else {
234                vec![rustc_root.clone()]
235            };
236            for p in &segs[..segs.len() - 2] {
237                m.push(rustc_crate_name(p));
238            }
239            m
240        };
241        let url_str = if crate_name.is_stdlib() {
242            let channel = version.stdlib_channel();
243            if mod_parts.is_empty() {
244                format!(
245                    "{origin}/{channel}/{crate_name}/{parent_prefix}.{parent_name}.html#{anchor}"
246                )
247            } else {
248                format!(
249                    "{origin}/{channel}/{crate_name}/{}/{}.{}.html#{anchor}",
250                    mod_parts.join("/"),
251                    parent_prefix,
252                    parent_name
253                )
254            }
255        } else if mod_parts.is_empty() {
256            format!(
257                "{origin}/{crate_name}/{version}/{rustc_root}/{parent_prefix}.{parent_name}.html#{anchor}"
258            )
259        } else {
260            format!(
261                "{origin}/{crate_name}/{version}/{}/{}.{}.html#{anchor}",
262                mod_parts.join("/"),
263                parent_prefix,
264                parent_name
265            )
266        };
267        return Url::parse(&url_str).map_err(|e| {
268            AppError::of_with_source(
269                ErrorDetail::Internal {
270                    op: InternalOp::UrlBuild,
271                },
272                e,
273            )
274        });
275    }
276
277    // Fail closed before the free-item branch. An enum variant and a struct
278    // field exist only as anchors on their parent, so reaching here means the
279    // path had no `Parent::member` shape. Building `variant.Some.html` would be
280    // an HTTP 404 dressed up as a plan; naming the missing parent is actionable.
281    if let Some(family) = member_only_family(kind) {
282        return Err(AppError::of(ErrorDetail::MemberKindNeedsParent {
283            kind: kind.as_str(),
284            member: segs.last().map_or("member", String::as_str).to_string(),
285            parent_kinds: family
286                .parent_kind_probe_names()
287                .collect::<Vec<_>>()
288                .join(", "),
289        }));
290    }
291
292    // Safe after the guard above: every remaining kind owns a page.
293    let file_prefix = kind.file_prefix().unwrap_or(kind.as_str());
294
295    let url_str = if crate_name.is_stdlib() {
296        let channel = version.stdlib_channel();
297        if kind == ItemKind::Module {
298            let mut parts: Vec<String> = Vec::new();
299            for p in &segs {
300                parts.push(rustc_crate_name(p));
301            }
302            if parts.is_empty() {
303                format!("{origin}/{channel}/{crate_name}/index.html")
304            } else {
305                format!(
306                    "{origin}/{channel}/{crate_name}/{}/index.html",
307                    parts.join("/")
308                )
309            }
310        } else {
311            if segs.is_empty() {
312                return Err(AppError::of(ErrorDetail::ItemPathMissingItemName));
313            }
314            let item_name = segs
315                .last()
316                .ok_or_else(|| AppError::of(ErrorDetail::ItemPathMissingItemName))?;
317            let mod_parts: Vec<String> = segs[..segs.len().saturating_sub(1)]
318                .iter()
319                .map(|p| rustc_crate_name(p))
320                .collect();
321            if mod_parts.is_empty() {
322                format!("{origin}/{channel}/{crate_name}/{file_prefix}.{item_name}.html")
323            } else {
324                format!(
325                    "{origin}/{channel}/{crate_name}/{}/{}.{}.html",
326                    mod_parts.join("/"),
327                    file_prefix,
328                    item_name
329                )
330            }
331        }
332    } else if kind == ItemKind::Module {
333        let mut parts: Vec<String> = vec![rustc_root];
334        for p in &segs {
335            parts.push(rustc_crate_name(p));
336        }
337        format!(
338            "{origin}/{crate_name}/{version}/{}/index.html",
339            parts.join("/")
340        )
341    } else {
342        if segs.is_empty() {
343            return Err(AppError::of(ErrorDetail::ItemPathMissingItemName));
344        }
345        let item_name = segs
346            .last()
347            .ok_or_else(|| AppError::of(ErrorDetail::ItemPathMissingItemName))?;
348        let mod_parts: Vec<String> = if segs.len() == 1 {
349            vec![rustc_root]
350        } else {
351            let mut m = vec![rustc_root];
352            for p in &segs[..segs.len() - 1] {
353                m.push(rustc_crate_name(p));
354            }
355            m
356        };
357        format!(
358            "{origin}/{crate_name}/{version}/{}/{}.{}.html",
359            mod_parts.join("/"),
360            file_prefix,
361            item_name
362        )
363    };
364
365    Url::parse(&url_str).map_err(|e| {
366        AppError::of_with_source(
367            ErrorDetail::Internal {
368                op: InternalOp::UrlBuild,
369            },
370            e,
371        )
372    })
373}
374
375/// Build all.html index URL.
376///
377/// # Errors
378///
379/// Propagates [`crate::error::ErrorKind::Internal`] from [`all_html_url_on_origin`].
380pub fn all_html_url(crate_name: &CrateName, version: &VersionArg) -> AppResult<Url> {
381    all_html_url_on_origin(&default_docs_origin(crate_name), crate_name, version)
382}
383
384/// Build all.html URL against an allowlisted origin (production or wiremock).
385///
386/// # Errors
387///
388/// Returns [`crate::error::ErrorKind::Internal`] when `origin` / path segments do not form a valid URL.
389pub fn all_html_url_on_origin(
390    origin: &AllowedOrigin,
391    crate_name: &CrateName,
392    version: &VersionArg,
393) -> AppResult<Url> {
394    let origin = origin.as_str().trim_end_matches('/');
395    let s = if crate_name.is_stdlib() {
396        let channel = version.stdlib_channel();
397        format!("{origin}/{channel}/{crate_name}/all.html")
398    } else {
399        let rustc = rustc_crate_name(crate_name.as_str());
400        format!("{origin}/{crate_name}/{version}/{rustc}/all.html")
401    };
402    Url::parse(&s).map_err(|e| {
403        AppError::of_with_source(
404            ErrorDetail::Internal {
405                op: InternalOp::UrlBuild,
406            },
407            e,
408        )
409    })
410}