]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
Rollup merge of #82037 - calavera:strip_debuginfo_osx, r=petrochenkov
[rust.git] / src / tools / linkchecker / main.rs
1 //! Script to check the validity of `href` links in our HTML documentation.
2 //!
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.
8 //!
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.
13 //!
14 //! A few exceptions are allowed as there's known bugs in rustdoc, but this
15 //! should catch the majority of "broken link" cases.
16
17 use std::cell::RefCell;
18 use std::collections::{HashMap, HashSet};
19 use std::env;
20 use std::fs;
21 use std::io::ErrorKind;
22 use std::path::{Component, Path, PathBuf};
23 use std::rc::Rc;
24 use std::time::Instant;
25
26 use once_cell::sync::Lazy;
27 use regex::Regex;
28
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"]),
40 ];
41
42 #[rustfmt::skip]
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", &[
49          "/</code> <code>!",
50          "*</code> <code>!",
51     ]),
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>_",
56     ]),
57     ("reference/tokens.html", &[
58          "0</code>-<code>1",
59          "0</code>-<code>7",
60          "0</code>-<code>9",
61          "0</code>-<code>9",
62          "0</code>-<code>9</code> <code>a</code>-<code>f</code> <code>A</code>-<code>F",
63     ]),
64     ("reference/notation.html", &[
65          "b</code> <code>B",
66          "a</code>-<code>z",
67     ]),
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"]),
74
75 ];
76
77 static BROKEN_INTRA_DOC_LINK: Lazy<Regex> =
78     Lazy::new(|| Regex::new(r#"\[<code>(.*)</code>\]"#).unwrap());
79
80 macro_rules! t {
81     ($e:expr) => {
82         match $e {
83             Ok(e) => e,
84             Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
85         }
86     };
87 }
88
89 fn main() {
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 {
94         errors: 0,
95         start: Instant::now(),
96         html_files: 0,
97         html_redirects: 0,
98         links_checked: 0,
99         links_ignored_external: 0,
100         links_ignored_exception: 0,
101         intra_doc_exceptions: 0,
102     };
103     checker.walk(&docs, &mut report);
104     report.report();
105     if report.errors != 0 {
106         println!("found some broken links");
107         std::process::exit(1);
108     }
109 }
110
111 struct Checker {
112     root: PathBuf,
113     cache: Cache,
114 }
115
116 struct Report {
117     errors: u32,
118     start: Instant,
119     html_files: u32,
120     html_redirects: u32,
121     links_checked: u32,
122     links_ignored_external: u32,
123     links_ignored_exception: u32,
124     intra_doc_exceptions: u32,
125 }
126
127 /// A cache entry.
128 enum FileEntry {
129     /// An HTML file.
130     ///
131     /// This includes the contents of the HTML file, and an optional set of
132     /// HTML IDs. The IDs are used for checking fragments. The 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.
139     OtherFile,
140     /// This is a directory.
141     Dir,
142     /// The file doesn't exist.
143     Missing,
144 }
145
146 /// A cache to speed up file access.
147 type Cache = HashMap<String, FileEntry>;
148
149 fn small_url_encode(s: &str) -> String {
150     s.replace("<", "%3C")
151         .replace(">", "%3E")
152         .replace(" ", "%20")
153         .replace("?", "%3F")
154         .replace("'", "%27")
155         .replace("&", "%26")
156         .replace(",", "%2C")
157         .replace(":", "%3A")
158         .replace(";", "%3B")
159         .replace("[", "%5B")
160         .replace("]", "%5D")
161         .replace("\"", "%22")
162 }
163
164 impl Checker {
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());
170             if kind.is_dir() {
171                 self.walk(&path, report);
172             } else {
173                 self.check(&path, report);
174             }
175         }
176     }
177
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);
188                 source.clone()
189             }
190         };
191
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:")
201             {
202                 report.links_ignored_external += 1;
203                 return;
204             }
205             report.links_checked += 1;
206             let (url, fragment) = match url.split_once('#') {
207                 None => (url, None),
208                 Some((url, fragment)) => (url, Some(fragment)),
209             };
210             // NB: the `splitn` always succeeds, even if the delimiter is not present.
211             let url = url.splitn(2, '?').next().unwrap();
212
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() {
217                 path.pop();
218                 for part in Path::new(base).join(url).components() {
219                     match part {
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.
224                             report.errors += 1;
225                             println!(
226                                 "{}:{}: absolute path - {}",
227                                 pretty_path,
228                                 i + 1,
229                                 Path::new(base).join(url).display()
230                             );
231                             return;
232                         }
233                         Component::CurDir => {}
234                         Component::ParentDir => {
235                             path.pop();
236                         }
237                         Component::Normal(s) => {
238                             path.push(s);
239                         }
240                     }
241                 }
242             }
243
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;
249                     } else {
250                         report.errors += 1;
251                         println!(
252                             "{}:{}: broken link - `{}`",
253                             pretty_path,
254                             i + 1,
255                             target_pretty_path
256                         );
257                     }
258                     return;
259                 }
260                 FileEntry::Dir => {
261                     // Links to directories show as directory listings when viewing
262                     // the docs offline so it's best to avoid them.
263                     report.errors += 1;
264                     println!(
265                         "{}:{}: directory link to `{}` \
266                          (directory links should use index.html instead)",
267                         pretty_path,
268                         i + 1,
269                         target_pretty_path
270                     );
271                     return;
272                 }
273                 FileEntry::OtherFile => return,
274                 FileEntry::Redirect { target } => {
275                     let t = target.clone();
276                     drop(target);
277                     let (target, redir_entry) = self.load_file(&t, report);
278                     match redir_entry {
279                         FileEntry::Missing => {
280                             report.errors += 1;
281                             println!(
282                                 "{}:{}: broken redirect from `{}` to `{}`",
283                                 pretty_path,
284                                 i + 1,
285                                 target_pretty_path,
286                                 target
287                             );
288                             return;
289                         }
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.
294                             report.errors += 1;
295                             println!(
296                                 "{}:{}: redirect from `{}` to `{}` \
297                                  which is also a redirect (not supported)",
298                                 pretty_path,
299                                 i + 1,
300                                 target_pretty_path,
301                                 target.display()
302                             );
303                             return;
304                         }
305                         FileEntry::Dir => {
306                             report.errors += 1;
307                             println!(
308                                 "{}:{}: redirect from `{}` to `{}` \
309                                  which is a directory \
310                                  (directory links should use index.html instead)",
311                                 pretty_path,
312                                 i + 1,
313                                 target_pretty_path,
314                                 target
315                             );
316                             return;
317                         }
318                         FileEntry::OtherFile => return,
319                         FileEntry::HtmlFile { source, ids } => (source, ids),
320                     }
321                 }
322                 FileEntry::HtmlFile { source, ids } => (source, ids),
323             };
324
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())) {
331                     return;
332                 }
333
334                 // These appear to be broken in mdbook right now?
335                 if fragment.starts_with('-') {
336                     return;
337                 }
338
339                 parse_ids(&mut target_ids.borrow_mut(), &pretty_path, target_source, report);
340
341                 if target_ids.borrow().contains(*fragment) {
342                     return;
343                 }
344
345                 if is_exception(file, &format!("#{}", fragment)) {
346                     report.links_ignored_exception += 1;
347                 } else {
348                     report.errors += 1;
349                     print!("{}:{}: broken link fragment ", pretty_path, i + 1);
350                     println!("`#{}` pointing to `{}`", fragment, pretty_path);
351                 };
352             }
353         });
354
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;
362                 } else {
363                     report.errors += 1;
364                     print!("{}:{}: broken intra-doc link - ", pretty_path, i + 1);
365                     println!("{}", &broken_link[0]);
366                 }
367             }
368         }
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"),
374         }
375     }
376
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) {
379         let pretty_path =
380             file.strip_prefix(&self.root).unwrap_or(&file).to_str().unwrap().to_string();
381
382         let entry =
383             self.cache.entry(pretty_path.clone()).or_insert_with(|| match fs::metadata(file) {
384                 Ok(metadata) if metadata.is_dir() => FileEntry::Dir,
385                 Ok(_) => {
386                     if file.extension().and_then(|s| s.to_str()) != Some("html") {
387                         FileEntry::OtherFile
388                     } else {
389                         report.html_files += 1;
390                         load_html_file(file, report)
391                     }
392                 }
393                 Err(e) if e.kind() == ErrorKind::NotFound => FileEntry::Missing,
394                 Err(e) => {
395                     panic!("unexpected read error for {}: {}", file.display(), e);
396                 }
397             });
398         (pretty_path, entry)
399     }
400 }
401
402 impl Report {
403     fn report(&self) {
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);
412     }
413 }
414
415 fn load_html_file(file: &Path, report: &mut Report) -> FileEntry {
416     let source = match fs::read_to_string(file) {
417         Ok(s) => Rc::new(s),
418         Err(err) => {
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);
422         }
423     };
424     match maybe_redirect(&source) {
425         Some(target) => {
426             report.html_redirects += 1;
427             let target = file.parent().unwrap().join(target);
428             FileEntry::Redirect { target }
429         }
430         None => FileEntry::HtmlFile { source: source.clone(), ids: RefCell::new(HashSet::new()) },
431     }
432 }
433
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)
437     } else {
438         false
439     }
440 }
441
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)
445     } else {
446         // FIXME(#63351): Concat trait in alloc/slice reexported in primitive page
447         //
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") {
453                 return true;
454             }
455         }
456         false
457     }
458 }
459
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=";
464
465     let mut lines = source.lines();
466     let redirect_line = lines.nth(7)?;
467
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()
472     })
473 }
474
475 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(source: &str, attr: &str, mut f: F) {
476     let mut base = "";
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");
483             line = rest;
484             let pos_equals = match rest.find('=') {
485                 Some(i) => i,
486                 None => continue,
487             };
488             if rest[..pos_equals].trim_start_matches(' ') != "" {
489                 continue;
490             }
491
492             let rest = &rest[pos_equals + 1..];
493
494             let pos_quote = match rest.find(&['"', '\''][..]) {
495                 Some(i) => i,
496                 None => continue,
497             };
498             let quote_delim = rest.as_bytes()[pos_quote] as char;
499
500             if rest[..pos_quote].trim_start_matches(' ') != "" {
501                 continue;
502             }
503             let rest = &rest[pos_quote + 1..];
504             let url = match rest.find(quote_delim) {
505                 Some(i) => &rest[..i],
506                 None => continue,
507             };
508             if is_base {
509                 base = url;
510                 continue;
511             }
512             f(url, i, base)
513         }
514     }
515 }
516
517 fn parse_ids(ids: &mut HashSet<String>, file: &str, source: &str, report: &mut Report) {
518     if ids.is_empty() {
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) {
523                 report.errors += 1;
524                 println!("{}:{}: id is not unique: `{}`", file, i, fragment);
525             }
526             // Just in case, we also add the encoded id.
527             ids.insert(encoded);
528         });
529     }
530 }