-
Notifications
You must be signed in to change notification settings - Fork 198
/
rustdoc.rs
1900 lines (1697 loc) · 64.2 KB
/
rustdoc.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! rustdoc handler
use crate::{
db::Pool,
repositories::RepositoryStatsUpdater,
utils,
web::{
crate_details::CrateDetails, csp::Csp, error::Nope, file::File, match_version,
metrics::RenderingTimesRecorder, redirect_base, MatchSemver, MetaData,
},
Config, Metrics, Storage,
};
use iron::url::percent_encoding::percent_decode;
use iron::{
headers::{CacheControl, CacheDirective, Expires, HttpDate},
modifiers::Redirect,
status, Handler, IronResult, Request, Response, Url,
};
use lol_html::errors::RewritingError;
use router::Router;
use serde::Serialize;
use std::path::Path;
#[derive(Clone)]
pub struct RustLangRedirector {
url: Url,
}
impl RustLangRedirector {
pub fn new(target: &'static str) -> Self {
let url = iron::url::Url::parse("https://doc.rust-lang.org/stable/")
.expect("failed to parse rust-lang.org base URL")
.join(target)
.expect("failed to append crate name to rust-lang.org base URL");
let url = Url::from_generic_url(url).expect("failed to convert url::Url to iron::Url");
Self { url }
}
}
impl iron::Handler for RustLangRedirector {
fn handle(&self, _req: &mut Request) -> IronResult<Response> {
Ok(Response::with((status::Found, Redirect(self.url.clone()))))
}
}
/// Handler called for `/:crate` and `/:crate/:version` URLs. Automatically redirects to the docs
/// or crate details page based on whether the given crate version was successfully built.
pub fn rustdoc_redirector_handler(req: &mut Request) -> IronResult<Response> {
fn redirect_to_doc(
req: &Request,
name: &str,
vers: &str,
target: Option<&str>,
target_name: &str,
) -> IronResult<Response> {
let mut url_str = if let Some(target) = target {
format!(
"{}/{}/{}/{}/{}/",
redirect_base(req),
name,
vers,
target,
target_name
)
} else {
format!("{}/{}/{}/{}/", redirect_base(req), name, vers, target_name)
};
if let Some(query) = req.url.query() {
url_str.push('?');
url_str.push_str(query);
}
let url = ctry!(req, Url::parse(&url_str));
let mut resp = Response::with((status::Found, Redirect(url)));
resp.headers.set(Expires(HttpDate(time::now())));
Ok(resp)
}
fn redirect_to_crate(req: &Request, name: &str, vers: &str) -> IronResult<Response> {
let url = ctry!(
req,
Url::parse(&format!("{}/crate/{}/{}", redirect_base(req), name, vers)),
);
let mut resp = Response::with((status::Found, Redirect(url)));
resp.headers.set(Expires(HttpDate(time::now())));
Ok(resp)
}
let metrics = extension!(req, Metrics).clone();
let mut rendering_time = RenderingTimesRecorder::new(&metrics.rustdoc_redirect_rendering_times);
// this unwrap is safe because iron urls are always able to use `path_segments`
// i'm using this instead of `req.url.path()` to avoid allocating the Vec, and also to avoid
// keeping the borrow alive into the return statement
if req
.url
.as_ref()
.path_segments()
.unwrap()
.last()
.map_or(false, |s| s.ends_with(".js"))
{
// javascript files should be handled by the file server instead of erroneously
// redirecting to the crate root page
if req.url.as_ref().path_segments().unwrap().count() > 2 {
// this URL is actually from a crate-internal path, serve it there instead
rendering_time.step("serve JS for crate");
return rustdoc_html_server_handler(req);
} else {
rendering_time.step("serve JS");
let storage = extension!(req, Storage);
let config = extension!(req, Config);
let path = req.url.path();
let path = path.join("/");
return match File::from_path(storage, &path, config) {
Ok(f) => Ok(f.serve()),
Err(..) => Err(Nope::ResourceNotFound.into()),
};
}
} else if req
.url
.as_ref()
.path_segments()
.unwrap()
.last()
.map_or(false, |s| s.ends_with(".ico"))
{
// route .ico files into their dedicated handler so that docs.rs's favicon is always
// displayed
rendering_time.step("serve ICO");
return super::statics::ico_handler(req);
}
let router = extension!(req, Router);
let mut conn = extension!(req, Pool).get()?;
// this handler should never called without crate pattern
let crate_name = cexpect!(req, router.find("crate"));
let mut crate_name = percent_decode(crate_name.as_bytes())
.decode_utf8()
.unwrap_or_else(|_| crate_name.into())
.into_owned();
let req_version = router.find("version");
let mut target = router.find("target");
// it doesn't matter if the version that was given was exact or not, since we're redirecting
// anyway
rendering_time.step("match version");
let v = match_version(&mut conn, &crate_name, req_version)?;
if let Some(new_name) = v.corrected_name {
// `match_version` checked against -/_ typos, so if we have a name here we should
// use that instead
crate_name = new_name;
}
let (version, id) = v.version.into_parts();
// get target name and whether it has docs
// FIXME: This is a bit inefficient but allowing us to use less code in general
rendering_time.step("fetch release doc status");
let (target_name, has_docs): (String, bool) = {
let rows = ctry!(
req,
conn.query(
"SELECT target_name, rustdoc_status
FROM releases
WHERE releases.id = $1",
&[&id]
),
);
(rows[0].get(0), rows[0].get(1))
};
if target == Some("index.html") || target == Some(&target_name) {
target = None;
}
if has_docs {
rendering_time.step("redirect to doc");
redirect_to_doc(req, &crate_name, &version, target, &target_name)
} else {
rendering_time.step("redirect to crate");
redirect_to_crate(req, &crate_name, &version)
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct RustdocPage {
latest_path: String,
latest_version: String,
target: String,
inner_path: String,
is_latest_version: bool,
is_prerelease: bool,
krate: CrateDetails,
metadata: MetaData,
}
impl RustdocPage {
fn into_response(
self,
rustdoc_html: &[u8],
max_parse_memory: usize,
req: &mut Request,
file_path: &str,
) -> IronResult<Response> {
use iron::{headers::ContentType, status::Status};
let templates = req
.extensions
.get::<super::TemplateData>()
.expect("missing TemplateData from the request extensions");
let metrics = req
.extensions
.get::<crate::Metrics>()
.expect("missing Metrics from the request extensions");
// Build the page of documentation
let ctx = ctry!(req, tera::Context::from_serialize(self));
// Extract the head and body of the rustdoc file so that we can insert it into our own html
// while logging OOM errors from html rewriting
let html = match utils::rewrite_lol(rustdoc_html, max_parse_memory, ctx, templates) {
Err(RewritingError::MemoryLimitExceeded(..)) => {
metrics.html_rewrite_ooms.inc();
let config = extension!(req, Config);
let err = anyhow::anyhow!(
"Failed to serve the rustdoc file '{}' because rewriting it surpassed the memory limit of {} bytes",
file_path, config.max_parse_memory,
);
ctry!(req, Err(err))
}
result => ctry!(req, result),
};
let mut response = Response::with((Status::Ok, html));
response.headers.set(ContentType::html());
Ok(response)
}
}
/// Serves documentation generated by rustdoc.
///
/// This includes all HTML files for an individual crate, as well as the `search-index.js`, which is
/// also crate-specific.
pub fn rustdoc_html_server_handler(req: &mut Request) -> IronResult<Response> {
let metrics = extension!(req, Metrics).clone();
let mut rendering_time = RenderingTimesRecorder::new(&metrics.rustdoc_rendering_times);
// Pages generated by Rustdoc are not ready to be served with a CSP yet.
req.extensions
.get_mut::<Csp>()
.expect("missing CSP")
.suppress(true);
// Get the request parameters
let router = extension!(req, Router);
// Get the crate name and version from the request
let (name, url_version) = (
router.find("crate").unwrap_or("").to_string(),
router.find("version"),
);
let pool = extension!(req, Pool);
let mut conn = pool.get()?;
let config = extension!(req, Config);
let storage = extension!(req, Storage);
let mut req_path = req.url.path();
// Remove the name and version from the path
req_path.drain(..2).for_each(drop);
// Convenience closure to allow for easy redirection
let redirect = |name: &str, vers: &str, path: &[&str]| -> IronResult<Response> {
// Format and parse the redirect url
let redirect_path = format!(
"{}/{}/{}/{}",
redirect_base(req),
name,
vers,
path.join("/")
);
let url = ctry!(req, Url::parse(&redirect_path));
Ok(super::redirect(url))
};
rendering_time.step("match version");
// Check the database for releases with the requested version while doing the following:
// * If no matching releases are found, return a 404 with the underlying error
// Then:
// * If both the name and the version are an exact match, return the version of the crate.
// * If there is an exact match, but the requested crate name was corrected (dashes vs. underscores), redirect to the corrected name.
// * If there is a semver (but not exact) match, redirect to the exact version.
let release_found = match_version(&mut conn, &name, url_version)?;
let version = match release_found.version {
MatchSemver::Exact((version, _)) => {
// Redirect when the requested crate name isn't correct
if let Some(name) = release_found.corrected_name {
return redirect(&name, &version, &req_path);
}
version
}
// Redirect when the requested version isn't correct
MatchSemver::Semver((v, _)) => {
// to prevent cloudfront caching the wrong artifacts on URLs with loose semver
// versions, redirect the browser to the returned version instead of loading it
// immediately
return redirect(&name, &v, &req_path);
}
};
let updater = extension!(req, RepositoryStatsUpdater);
rendering_time.step("crate details");
// Get the crate's details from the database
// NOTE: we know this crate must exist because we just checked it above (or else `match_version` is buggy)
let krate = cexpect!(req, CrateDetails::new(&mut conn, &name, &version, updater));
// if visiting the full path to the default target, remove the target from the path
// expects a req_path that looks like `[/:target]/.*`
if req_path.get(0).copied() == Some(&krate.metadata.default_target) {
return redirect(&name, &version, &req_path[1..]);
}
rendering_time.step("fetch from storage");
// Create the path to access the file from
let mut path = req_path.join("/");
if path.ends_with('/') {
req_path.pop(); // get rid of empty string
path.push_str("index.html");
req_path.push("index.html");
}
let mut path = ctry!(req, percent_decode(path.as_bytes()).decode_utf8());
// Attempt to load the file from the database
let blob = match storage.fetch_rustdoc_file(&name, &version, &path, krate.archive_storage) {
Ok(file) => file,
Err(err) => {
log::debug!("got error serving {}: {}", path, err);
// If it fails, we try again with /index.html at the end
path.to_mut().push_str("/index.html");
req_path.push("index.html");
return if ctry!(
req,
storage.rustdoc_file_exists(&name, &version, &path, krate.archive_storage)
) {
redirect(&name, &version, &req_path)
} else if req_path.get(0).map_or(false, |p| p.contains('-')) {
// This is a target, not a module; it may not have been built.
// Redirect to the default target and show a search page instead of a hard 404.
redirect(
&format!("/crate/{}", name),
&format!("{}/target-redirect", version),
&req_path,
)
} else {
Err(Nope::ResourceNotFound.into())
};
}
};
// Serve non-html files directly
if !path.ends_with(".html") {
rendering_time.step("serve asset");
return Ok(File(blob).serve());
}
rendering_time.step("find latest path");
let latest_release = krate.latest_release();
// Get the latest version of the crate
let latest_version = latest_release.version.to_string();
let is_latest_version = latest_version == version;
let is_prerelease = semver::Version::parse(&version)
// should be impossible unless there is a semver incompatible version in the db
// Note that there is a redirect earlier for semver matches to the exact version
.map_err(|err| {
log::error!(
"invalid semver in database for crate {}: {}. Err: {}",
name,
&version,
err
);
Nope::InternalServerError
})?
.is_prerelease();
// The path within this crate version's rustdoc output
let (target, inner_path) = {
let mut inner_path = req_path.clone();
let target = if inner_path.len() > 1
&& krate
.metadata
.doc_targets
.iter()
.any(|s| s == inner_path[0])
{
inner_path.remove(0)
} else {
""
};
(target, inner_path.join("/"))
};
// If the requested crate version is the most recent, use it to build the url
let mut latest_path = if is_latest_version {
format!("/{}/{}", name, latest_version)
// If the requested version is not the latest, then find the path of the latest version for the `Go to latest` link
} else if latest_release.build_status {
let target = if target.is_empty() {
&krate.metadata.default_target
} else {
target
};
format!(
"/crate/{}/{}/target-redirect/{}/{}",
name, latest_version, target, inner_path
)
} else {
format!("/crate/{}/{}", name, latest_version)
};
if let Some(query) = req.url.query() {
latest_path.push('?');
latest_path.push_str(query);
}
metrics
.recently_accessed_releases
.record(krate.crate_id, krate.release_id, target);
let target = if target.is_empty() {
String::new()
} else {
format!("{}/", target)
};
rendering_time.step("rewrite html");
RustdocPage {
latest_path,
latest_version,
target,
inner_path,
is_latest_version,
is_prerelease,
metadata: krate.metadata.clone(),
krate,
}
.into_response(&blob.content, config.max_parse_memory, req, &path)
}
/// Checks whether the given path exists.
/// The crate's `target_name` is used to confirm whether a platform triple is part of the path.
///
/// Note that path is overloaded in this context to mean both the path of a URL
/// and the file path of a static file in the DB.
///
/// `req_path` is assumed to have the following format:
/// `rustdoc/crate/version[/platform]/module/[kind.name.html|index.html]`
///
/// Returns a path that can be appended to `/crate/version/` to create a complete URL.
fn path_for_version(
req_path: &[&str],
known_platforms: &[String],
storage: &Storage,
config: &Config,
) -> String {
// Simple case: page exists in the latest version, so just change the version number
if File::from_path(storage, &req_path.join("/"), config).is_ok() {
// NOTE: this adds 'index.html' if it wasn't there before
return req_path[3..].join("/");
}
// check if req_path[3] is the platform choice or the name of the crate
// Note we don't require the platform to have a trailing slash.
let platform = if known_platforms.iter().any(|s| s == req_path[3]) && req_path.len() >= 4 {
req_path[3]
} else {
""
};
let is_source_view = if platform.is_empty() {
// /{name}/{version}/src/{crate}/index.html
req_path.get(3).copied() == Some("src")
} else {
// /{name}/{version}/{platform}/src/{crate}/index.html
req_path.get(4).copied() == Some("src")
};
// this page doesn't exist in the latest version
let last_component = *req_path.last().unwrap();
let search_item = if last_component == "index.html" {
// this is a module
req_path.get(req_path.len() - 2).copied()
// no trailing slash; no one should be redirected here but we handle it gracefully anyway
} else if last_component == platform {
// nothing to search for
None
} else if !is_source_view {
// this is an item
last_component.split('.').nth(1)
} else {
// if this is a Rust source file, try searching for the module;
// else, don't try searching at all, we don't know how to find it
last_component.strip_suffix(".rs.html")
};
if let Some(search) = search_item {
format!("{}?search={}", platform, search)
} else {
platform.to_owned()
}
}
pub fn target_redirect_handler(req: &mut Request) -> IronResult<Response> {
let router = extension!(req, Router);
let name = cexpect!(req, router.find("name"));
let version = cexpect!(req, router.find("version"));
let pool = extension!(req, Pool);
let mut conn = pool.get()?;
let storage = extension!(req, Storage);
let config = extension!(req, Config);
let base = redirect_base(req);
let updater = extension!(req, RepositoryStatsUpdater);
let crate_details = match CrateDetails::new(&mut conn, name, version, updater) {
Some(krate) => krate,
None => return Err(Nope::VersionNotFound.into()),
};
// [crate, :name, :version, target-redirect, :target, *path]
// is transformed to
// [rustdoc, :name, :version, :target?, *path]
// path might be empty, but target is guaranteed to be there because of the route used
let file_path = {
let mut file_path = req.url.path();
file_path[0] = "rustdoc";
file_path.remove(3);
if file_path[3] == crate_details.metadata.default_target {
file_path.remove(3);
}
if let Some(last @ &mut "") = file_path.last_mut() {
*last = "index.html";
}
file_path
};
let path = path_for_version(
&file_path,
&crate_details.metadata.doc_targets,
storage,
config,
);
let url = format!(
"{base}/{name}/{version}/{path}",
base = base,
name = name,
version = version,
path = path
);
let url = ctry!(req, Url::parse(&url));
let mut resp = Response::with((status::Found, Redirect(url)));
resp.headers.set(Expires(HttpDate(time::now())));
Ok(resp)
}
pub fn badge_handler(req: &mut Request) -> IronResult<Response> {
use badge::{Badge, BadgeOptions};
use iron::headers::ContentType;
let version = {
let mut params = req.url.as_ref().query_pairs();
match params.find(|(key, _)| key == "version") {
Some((_, version)) => version.into_owned(),
None => "*".to_owned(),
}
};
let name = cexpect!(req, extension!(req, Router).find("crate"));
let mut conn = extension!(req, Pool).get()?;
let options =
match match_version(&mut conn, name, Some(&version)).and_then(|m| m.assume_exact()) {
Ok(MatchSemver::Exact((version, id))) => {
let rows = ctry!(
req,
conn.query(
"SELECT rustdoc_status
FROM releases
WHERE releases.id = $1",
&[&id]
),
);
if !rows.is_empty() && rows[0].get(0) {
BadgeOptions {
subject: "docs".to_owned(),
status: version,
color: "#4d76ae".to_owned(),
}
} else {
BadgeOptions {
subject: "docs".to_owned(),
status: version,
color: "#e05d44".to_owned(),
}
}
}
Ok(MatchSemver::Semver((version, _))) => {
let base_url = format!("{}/{}/badge.svg", redirect_base(req), name);
let url = ctry!(
req,
iron::url::Url::parse_with_params(&base_url, &[("version", version)]),
);
let iron_url = ctry!(req, Url::from_generic_url(url));
return Ok(super::redirect(iron_url));
}
Err(Nope::VersionNotFound) => BadgeOptions {
subject: "docs".to_owned(),
status: "version not found".to_owned(),
color: "#e05d44".to_owned(),
},
Err(_) => BadgeOptions {
subject: "docs".to_owned(),
status: "no builds".to_owned(),
color: "#e05d44".to_owned(),
},
};
let mut resp = Response::with((status::Ok, ctry!(req, Badge::new(options)).to_svg()));
resp.headers
.set(ContentType("image/svg+xml".parse().unwrap()));
resp.headers.set(Expires(HttpDate(time::now())));
resp.headers.set(CacheControl(vec![
CacheDirective::NoCache,
CacheDirective::NoStore,
CacheDirective::MustRevalidate,
]));
Ok(resp)
}
/// Serves shared web resources used by rustdoc-generated documentation.
///
/// This includes common `css` and `js` files that only change when the compiler is updated, but are
/// otherwise the same for all crates documented with that compiler. Those have a custom handler to
/// deduplicate them and save space.
pub struct SharedResourceHandler;
impl Handler for SharedResourceHandler {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let path = req.url.path();
let filename = path.last().unwrap(); // unwrap is fine: vector is non-empty
if let Some(extension) = Path::new(filename).extension() {
if ["js", "css", "woff", "woff2", "svg", "png"]
.iter()
.any(|s| *s == extension)
{
let storage = extension!(req, Storage);
let config = extension!(req, Config);
if let Ok(file) = File::from_path(storage, filename, config) {
return Ok(file.serve());
}
}
}
// Just always return a 404 here - the main handler will then try the other handlers
Err(Nope::ResourceNotFound.into())
}
}
#[cfg(test)]
mod test {
use crate::test::*;
use anyhow::Context;
use kuchiki::traits::TendrilSink;
use reqwest::StatusCode;
use std::collections::BTreeMap;
use test_case::test_case;
fn try_latest_version_redirect(
path: &str,
web: &TestFrontend,
) -> Result<Option<String>, anyhow::Error> {
assert_success(path, web)?;
let data = web.get(path).send()?.text()?;
log::info!("fetched path {} and got content {}\nhelp: if this is missing the header, remember to add <html><head></head><body></body></html>", path, data);
let dom = kuchiki::parse_html().one(data);
if let Some(elem) = dom
.select("form > ul > li > a.warn")
.expect("invalid selector")
.next()
{
let link = elem.attributes.borrow().get("href").unwrap().to_string();
assert_success(&link, web)?;
Ok(Some(link))
} else {
Ok(None)
}
}
fn latest_version_redirect(path: &str, web: &TestFrontend) -> Result<String, anyhow::Error> {
try_latest_version_redirect(path, web)?
.with_context(|| anyhow::anyhow!("no redirect found for {}", path))
}
#[test_case(true)]
#[test_case(false)]
// regression test for https://github.com/rust-lang/docs.rs/issues/552
fn settings_html(archive_storage: bool) {
wrapper(|env| {
// first release works, second fails
env.fake_release()
.name("buggy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("settings.html")
.rustdoc_file("directory_1/index.html")
.rustdoc_file("directory_2.html/index.html")
.rustdoc_file("all.html")
.rustdoc_file("directory_3/.gitignore")
.rustdoc_file("directory_4/empty_file_no_ext")
.create()?;
env.fake_release()
.name("buggy")
.version("0.2.0")
.archive_storage(archive_storage)
.build_result_failed()
.create()?;
let web = env.frontend();
assert_success("/", web)?;
assert_success("/crate/buggy/0.1.0/", web)?;
assert_success("/buggy/0.1.0/directory_1/index.html", web)?;
assert_success("/buggy/0.1.0/directory_2.html/index.html", web)?;
assert_success("/buggy/0.1.0/directory_3/.gitignore", web)?;
assert_success("/buggy/0.1.0/settings.html", web)?;
assert_success("/buggy/0.1.0/all.html", web)?;
assert_success("/buggy/0.1.0/directory_4/empty_file_no_ext", web)?;
Ok(())
});
}
#[test_case(true)]
#[test_case(false)]
fn default_target_redirects_to_base(archive_storage: bool) {
wrapper(|env| {
env.fake_release()
.name("dummy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.create()?;
let web = env.frontend();
// no explicit default-target
let base = "/dummy/0.1.0/dummy/";
assert_success(base, web)?;
assert_redirect("/dummy/0.1.0/x86_64-unknown-linux-gnu/dummy/", base, web)?;
// set an explicit target that requires cross-compile
let target = "x86_64-pc-windows-msvc";
env.fake_release()
.name("dummy")
.version("0.2.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.default_target(target)
.create()?;
let base = "/dummy/0.2.0/dummy/";
assert_success(base, web)?;
assert_redirect("/dummy/0.2.0/x86_64-pc-windows-msvc/dummy/", base, web)?;
// set an explicit target without cross-compile
// also check that /:crate/:version/:platform/all.html doesn't panic
let target = "x86_64-unknown-linux-gnu";
env.fake_release()
.name("dummy")
.version("0.3.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.rustdoc_file("all.html")
.default_target(target)
.create()?;
let base = "/dummy/0.3.0/dummy/";
assert_success(base, web)?;
assert_redirect("/dummy/0.3.0/x86_64-unknown-linux-gnu/dummy/", base, web)?;
assert_redirect(
"/dummy/0.3.0/x86_64-unknown-linux-gnu/all.html",
"/dummy/0.3.0/all.html",
web,
)?;
assert_redirect("/dummy/0.3.0/", base, web)?;
assert_redirect("/dummy/0.3.0/index.html", base, web)?;
Ok(())
});
}
#[test_case(true)]
#[test_case(false)]
fn go_to_latest_version(archive_storage: bool) {
wrapper(|env| {
env.fake_release()
.name("dummy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/blah/index.html")
.rustdoc_file("dummy/blah/blah.html")
.rustdoc_file("dummy/struct.will-be-deleted.html")
.create()?;
env.fake_release()
.name("dummy")
.version("0.2.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/blah/index.html")
.rustdoc_file("dummy/blah/blah.html")
.create()?;
let web = env.frontend();
// check it works at all
let redirect = latest_version_redirect("/dummy/0.1.0/dummy/", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-unknown-linux-gnu/dummy/index.html"
);
// check it keeps the subpage
let redirect = latest_version_redirect("/dummy/0.1.0/dummy/blah/", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-unknown-linux-gnu/dummy/blah/index.html"
);
let redirect = latest_version_redirect("/dummy/0.1.0/dummy/blah/blah.html", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-unknown-linux-gnu/dummy/blah/blah.html"
);
// check it also works for deleted pages
let redirect =
latest_version_redirect("/dummy/0.1.0/dummy/struct.will-be-deleted.html", web)?;
assert_eq!(redirect, "/crate/dummy/0.2.0/target-redirect/x86_64-unknown-linux-gnu/dummy/struct.will-be-deleted.html");
Ok(())
})
}
#[test_case(true)]
#[test_case(false)]
fn go_to_latest_version_keeps_platform(archive_storage: bool) {
wrapper(|env| {
env.fake_release()
.name("dummy")
.version("0.1.0")
.archive_storage(archive_storage)
.add_platform("x86_64-pc-windows-msvc")
.rustdoc_file("dummy/struct.Blah.html")
.create()?;
env.fake_release()
.name("dummy")
.version("0.2.0")
.archive_storage(archive_storage)
.add_platform("x86_64-pc-windows-msvc")
.create()?;
let web = env.frontend();
let redirect =
latest_version_redirect("/dummy/0.1.0/x86_64-pc-windows-msvc/dummy", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-pc-windows-msvc/dummy/index.html"
);
let redirect =
latest_version_redirect("/dummy/0.1.0/x86_64-pc-windows-msvc/dummy/", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-pc-windows-msvc/dummy/index.html"
);
let redirect = latest_version_redirect(
"/dummy/0.1.0/x86_64-pc-windows-msvc/dummy/struct.Blah.html",
web,
)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-pc-windows-msvc/dummy/struct.Blah.html"
);
Ok(())
})
}
#[test_case(true)]
#[test_case(false)]
fn redirect_latest_goes_to_crate_if_build_failed(archive_storage: bool) {
wrapper(|env| {
env.fake_release()
.name("dummy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.create()?;
env.fake_release()
.name("dummy")
.version("0.2.0")
.archive_storage(archive_storage)
.build_result_failed()
.create()?;
let web = env.frontend();
let redirect = latest_version_redirect("/dummy/0.1.0/dummy/", web)?;
assert_eq!(redirect, "/crate/dummy/0.2.0");
Ok(())
})
}
#[test_case(true)]
#[test_case(false)]
fn redirect_latest_does_not_go_to_yanked_versions(archive_storage: bool) {
wrapper(|env| {
env.fake_release()
.name("dummy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.create()?;
env.fake_release()
.name("dummy")
.version("0.2.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.create()?;
env.fake_release()
.name("dummy")
.version("0.2.1")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.yanked(true)
.create()?;
let web = env.frontend();
let redirect = latest_version_redirect("/dummy/0.1.0/dummy/", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-unknown-linux-gnu/dummy/index.html"
);
let redirect = latest_version_redirect("/dummy/0.2.1/dummy/", web)?;
assert_eq!(
redirect,
"/crate/dummy/0.2.0/target-redirect/x86_64-unknown-linux-gnu/dummy/index.html"
);
Ok(())
})
}
#[test_case(true)]
#[test_case(false)]
fn redirect_latest_with_all_yanked(archive_storage: bool) {
wrapper(|env| {
env.fake_release()
.name("dummy")
.version("0.1.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.yanked(true)
.create()?;
env.fake_release()
.name("dummy")
.version("0.2.0")
.archive_storage(archive_storage)
.rustdoc_file("dummy/index.html")
.yanked(true)
.create()?;
env.fake_release()
.name("dummy")