1use 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
24pub 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
33pub 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 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
62pub 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
83pub fn is_method_path(kind: ItemKind, segs: &[String]) -> bool {
92 associated_item_path(kind, segs) == Some(AssocAnchorKind::Method)
93}
94
95pub 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
113pub 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 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 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
152pub 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
163pub 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
183pub 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 if let Some(assoc) = associated_item_path(kind, &segs) {
201 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 let anchor = format!("{}{member_name}", assoc.primary_prefix());
214 let parent_kind = parent_kind_override.unwrap_or(assoc.parent_kind_probe()[0]);
217 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 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 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
375pub 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
384pub 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}