1 //! Script to check the validity of `href` links in our HTML documentation.
3 //! In the past we've been quite error prone to writing in broken links as most
4 //! of them are manually rather than automatically added. As files move over
5 //! time or apis change old links become stale or broken. The purpose of this
6 //! script is to check all relative links in our documentation to make sure they
7 //! actually point to a valid place.
9 //! Currently this doesn't actually do any HTML parsing or anything fancy like
10 //! that, it just has a simple "regex" to search for `href` and `id` tags.
11 //! These values are then translated to file URLs if possible and then the
12 //! destination is asserted to exist.
14 //! A few exceptions are allowed as there's known bugs in rustdoc, but this
15 //! should catch the majority of "broken link" cases.
17 use std::cell::RefCell;
18 use std::collections::{HashMap, HashSet};
21 use std::io::ErrorKind;
22 use std::path::{Component, Path, PathBuf};
24 use std::time::Instant;
26 use once_cell::sync::Lazy;
29 // Add linkcheck exceptions here
30 // If at all possible you should use intra-doc links to avoid linkcheck issues. These
31 // are cases where that does not work
32 // [(generated_documentation_page, &[broken_links])]
33 const LINKCHECK_EXCEPTIONS: &[(&str, &[&str])] = &[
34 // These try to link to std::collections, but are defined in alloc
35 // https://github.com/rust-lang/rust/issues/74481
36 ("std/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
37 ("std/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
38 ("alloc/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
39 ("alloc/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
43 const INTRA_DOC_LINK_EXCEPTIONS: &[(&str, &[&str])] = &[
44 // This will never have links that are not in other pages.
45 // To avoid repeating the exceptions twice, an empty list means all broken links are allowed.
46 ("reference/print.html", &[]),
47 // All the reference 'links' are actually ENBF highlighted as code
48 ("reference/comments.html", &[
52 ("reference/identifiers.html", &[
53 "a</code>-<code>z</code> <code>A</code>-<code>Z",
54 "a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_",
55 "a</code>-<code>z</code> <code>A</code>-<code>Z</code>] [<code>a</code>-<code>z</code> <code>A</code>-<code>Z</code> <code>0</code>-<code>9</code> <code>_",
57 ("reference/tokens.html", &[
62 "0</code>-<code>9</code> <code>a</code>-<code>f</code> <code>A</code>-<code>F",
64 ("reference/notation.html", &[
68 // This is being used in the sense of 'inclusive range', not a markdown link
69 ("core/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
70 ("std/ops/struct.RangeInclusive.html", &["begin</code>, <code>end"]),
71 ("core/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
72 ("alloc/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
73 ("std/slice/trait.SliceIndex.html", &["begin</code>, <code>end"]),
77 static BROKEN_INTRA_DOC_LINK: Lazy<Regex> =
78 Lazy::new(|| Regex::new(r#"\[<code>(.*)</code>\]"#).unwrap());
84 Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
90 let docs = env::args_os().nth(1).expect("doc path should be first argument");
91 let docs = env::current_dir().unwrap().join(docs);
92 let mut checker = Checker { root: docs.clone(), cache: HashMap::new() };
93 let mut report = Report {
95 start: Instant::now(),
99 links_ignored_external: 0,
100 links_ignored_exception: 0,
101 intra_doc_exceptions: 0,
103 checker.walk(&docs, &mut report);
105 if report.errors != 0 {
106 println!("found some broken links");
107 std::process::exit(1);
122 links_ignored_external: u32,
123 links_ignored_exception: u32,
124 intra_doc_exceptions: u32,
131 /// This includes the contents of the HTML file, and an optional set of
132 /// HTML IDs. The IDs are used for checking fragments. They are computed
133 /// as-needed. The source is discarded (replaced with an empty string)
134 /// after the file has been checked, to conserve on memory.
135 HtmlFile { source: Rc<String>, ids: RefCell<HashSet<String>> },
136 /// This file is an HTML redirect to the given local path.
137 Redirect { target: PathBuf },
138 /// This is not an HTML file.
140 /// This is a directory.
142 /// The file doesn't exist.
146 /// A cache to speed up file access.
147 type Cache = HashMap<String, FileEntry>;
149 fn small_url_encode(s: &str) -> String {
150 s.replace("<", "%3C")
161 .replace("\"", "%22")
165 /// Primary entry point for walking the filesystem to find HTML files to check.
166 fn walk(&mut self, dir: &Path, report: &mut Report) {
167 for entry in t!(dir.read_dir()).map(|e| t!(e)) {
168 let path = entry.path();
169 let kind = t!(entry.file_type());
171 self.walk(&path, report);
173 self.check(&path, report);
178 /// Checks a single file.
179 fn check(&mut self, file: &Path, report: &mut Report) {
180 let (pretty_path, entry) = self.load_file(file, report);
181 let source = match entry {
182 FileEntry::Missing => panic!("missing file {:?} while walking", file),
183 FileEntry::Dir => unreachable!("never with `check` path"),
184 FileEntry::OtherFile => return,
185 FileEntry::Redirect { .. } => return,
186 FileEntry::HtmlFile { source, ids } => {
187 parse_ids(&mut ids.borrow_mut(), &pretty_path, source, report);
192 // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
193 with_attrs_in_source(&source, " href", |url, i, base| {
194 // Ignore external URLs
195 if url.starts_with("http:")
196 || url.starts_with("https:")
197 || url.starts_with("javascript:")
198 || url.starts_with("ftp:")
199 || url.starts_with("irc:")
200 || url.starts_with("data:")
202 report.links_ignored_external += 1;
205 report.links_checked += 1;
206 let (url, fragment) = match url.split_once('#') {
208 Some((url, fragment)) => (url, Some(fragment)),
210 // NB: the `splitn` always succeeds, even if the delimiter is not present.
211 let url = url.splitn(2, '?').next().unwrap();
213 // Once we've plucked out the URL, parse it using our base url and
214 // then try to extract a file path.
215 let mut path = file.to_path_buf();
216 if !base.is_empty() || !url.is_empty() {
218 for part in Path::new(base).join(url).components() {
220 Component::Prefix(_) | Component::RootDir => {
221 // Avoid absolute paths as they make the docs not
222 // relocatable by making assumptions on where the docs
223 // are hosted relative to the site root.
226 "{}:{}: absolute path - {}",
229 Path::new(base).join(url).display()
233 Component::CurDir => {}
234 Component::ParentDir => {
237 Component::Normal(s) => {
244 let (target_pretty_path, target_entry) = self.load_file(&path, report);
245 let (target_source, target_ids) = match target_entry {
246 FileEntry::Missing => {
247 if is_exception(file, &target_pretty_path) {
248 report.links_ignored_exception += 1;
252 "{}:{}: broken link - `{}`",
261 // Links to directories show as directory listings when viewing
262 // the docs offline so it's best to avoid them.
265 "{}:{}: directory link to `{}` \
266 (directory links should use index.html instead)",
273 FileEntry::OtherFile => return,
274 FileEntry::Redirect { target } => {
275 let t = target.clone();
277 let (target, redir_entry) = self.load_file(&t, report);
279 FileEntry::Missing => {
282 "{}:{}: broken redirect from `{}` to `{}`",
290 FileEntry::Redirect { target } => {
291 // Redirect to a redirect, this link checker
292 // currently doesn't support this, since it would
293 // require cycle checking, etc.
296 "{}:{}: redirect from `{}` to `{}` \
297 which is also a redirect (not supported)",
308 "{}:{}: redirect from `{}` to `{}` \
309 which is a directory \
310 (directory links should use index.html instead)",
318 FileEntry::OtherFile => return,
319 FileEntry::HtmlFile { source, ids } => (source, ids),
322 FileEntry::HtmlFile { source, ids } => (source, ids),
325 // Alright, if we've found an HTML file for the target link. If
326 // this is a fragment link, also check that the `id` exists.
327 if let Some(ref fragment) = fragment {
328 // Fragments like `#1-6` are most likely line numbers to be
329 // interpreted by javascript, so we're ignoring these
330 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
334 // These appear to be broken in mdbook right now?
335 if fragment.starts_with('-') {
339 parse_ids(&mut target_ids.borrow_mut(), &pretty_path, target_source, report);
341 if target_ids.borrow().contains(*fragment) {
345 if is_exception(file, &format!("#{}", fragment)) {
346 report.links_ignored_exception += 1;
349 print!("{}:{}: broken link fragment ", pretty_path, i + 1);
350 println!("`#{}` pointing to `{}`", fragment, target_pretty_path);
355 // Search for intra-doc links that rustdoc didn't warn about
356 // FIXME(#77199, 77200) Rustdoc should just warn about these directly.
357 // NOTE: only looks at one line at a time; in practice this should find most links
358 for (i, line) in source.lines().enumerate() {
359 for broken_link in BROKEN_INTRA_DOC_LINK.captures_iter(line) {
360 if is_intra_doc_exception(file, &broken_link[1]) {
361 report.intra_doc_exceptions += 1;
364 print!("{}:{}: broken intra-doc link - ", pretty_path, i + 1);
365 println!("{}", &broken_link[0]);
369 // we don't need the source anymore,
370 // so drop to reduce memory-usage
371 match self.cache.get_mut(&pretty_path).unwrap() {
372 FileEntry::HtmlFile { source, .. } => *source = Rc::new(String::new()),
373 _ => unreachable!("must be html file"),
377 /// Load a file from disk, or from the cache if available.
378 fn load_file(&mut self, file: &Path, report: &mut Report) -> (String, &FileEntry) {
380 file.strip_prefix(&self.root).unwrap_or(&file).to_str().unwrap().to_string();
383 self.cache.entry(pretty_path.clone()).or_insert_with(|| match fs::metadata(file) {
384 Ok(metadata) if metadata.is_dir() => FileEntry::Dir,
386 if file.extension().and_then(|s| s.to_str()) != Some("html") {
389 report.html_files += 1;
390 load_html_file(file, report)
393 Err(e) if e.kind() == ErrorKind::NotFound => FileEntry::Missing,
395 panic!("unexpected read error for {}: {}", file.display(), e);
404 println!("checked links in: {:.1}s", self.start.elapsed().as_secs_f64());
405 println!("number of HTML files scanned: {}", self.html_files);
406 println!("number of HTML redirects found: {}", self.html_redirects);
407 println!("number of links checked: {}", self.links_checked);
408 println!("number of links ignored due to external: {}", self.links_ignored_external);
409 println!("number of links ignored due to exceptions: {}", self.links_ignored_exception);
410 println!("number of intra doc links ignored: {}", self.intra_doc_exceptions);
411 println!("errors found: {}", self.errors);
415 fn load_html_file(file: &Path, report: &mut Report) -> FileEntry {
416 let source = match fs::read_to_string(file) {
419 // This usually should not fail since `metadata` was already
420 // called successfully on this file.
421 panic!("unexpected read error for {}: {}", file.display(), err);
424 match maybe_redirect(&source) {
426 report.html_redirects += 1;
427 let target = file.parent().unwrap().join(target);
428 FileEntry::Redirect { target }
430 None => FileEntry::HtmlFile { source: source.clone(), ids: RefCell::new(HashSet::new()) },
434 fn is_intra_doc_exception(file: &Path, link: &str) -> bool {
435 if let Some(entry) = INTRA_DOC_LINK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
436 entry.1.is_empty() || entry.1.contains(&link)
442 fn is_exception(file: &Path, link: &str) -> bool {
443 if let Some(entry) = LINKCHECK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
444 entry.1.contains(&link)
446 // FIXME(#63351): Concat trait in alloc/slice reexported in primitive page
448 // NOTE: This cannot be added to `LINKCHECK_EXCEPTIONS` because the resolved path
449 // calculated in `check` function is outside `build/<triple>/doc` dir.
450 // So the `strip_prefix` method just returns the old absolute broken path.
451 if file.ends_with("std/primitive.slice.html") {
452 if link.ends_with("primitive.slice.html") {
460 /// If the given HTML file contents is an HTML redirect, this returns the
461 /// destination path given in the redirect.
462 fn maybe_redirect(source: &str) -> Option<String> {
463 const REDIRECT: &str = "<p>Redirecting to <a href=";
465 let mut lines = source.lines();
466 let redirect_line = lines.nth(7)?;
468 redirect_line.find(REDIRECT).map(|i| {
469 let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
470 let pos_quote = rest.find('"').unwrap();
471 rest[..pos_quote].to_owned()
475 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(source: &str, attr: &str, mut f: F) {
477 for (i, mut line) in source.lines().enumerate() {
478 while let Some(j) = line.find(attr) {
479 let rest = &line[j + attr.len()..];
480 // The base tag should always be the first link in the document so
481 // we can get away with using one pass.
482 let is_base = line[..j].ends_with("<base");
484 let pos_equals = match rest.find('=') {
488 if rest[..pos_equals].trim_start_matches(' ') != "" {
492 let rest = &rest[pos_equals + 1..];
494 let pos_quote = match rest.find(&['"', '\''][..]) {
498 let quote_delim = rest.as_bytes()[pos_quote] as char;
500 if rest[..pos_quote].trim_start_matches(' ') != "" {
503 let rest = &rest[pos_quote + 1..];
504 let url = match rest.find(quote_delim) {
505 Some(i) => &rest[..i],
517 fn parse_ids(ids: &mut HashSet<String>, file: &str, source: &str, report: &mut Report) {
519 with_attrs_in_source(source, " id", |fragment, i, _| {
520 let frag = fragment.trim_start_matches("#").to_owned();
521 let encoded = small_url_encode(&frag);
522 if !ids.insert(frag) {
524 println!("{}:{}: id is not unique: `{}`", file, i, fragment);
526 // Just in case, we also add the encoded id.