]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
194318d7a59b5ec5c9ed56fd8df5f6ae4310084a
[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::collections::hash_map::Entry;
18 use std::collections::{HashMap, HashSet};
19 use std::env;
20 use std::fs;
21 use std::path::{Component, Path, PathBuf};
22 use std::rc::Rc;
23
24 use crate::Redirect::*;
25
26 // Add linkcheck exceptions here
27 // If at all possible you should use intra-doc links to avoid linkcheck issues. These
28 // are cases where that does not work
29 // [(generated_documentation_page, &[broken_links])]
30 const LINKCHECK_EXCEPTIONS: &[(&str, &[&str])] = &[
31     // These are methods on slice, and `Self` does not work on primitive impls
32     // in intra-doc links (primitive impls are weird)
33     // https://github.com/rust-lang/rust/issues/62834 is necessary to be
34     // able to link to slices
35     (
36         "std/io/struct.IoSlice.html",
37         &[
38             "#method.as_mut_ptr",
39             "#method.sort_by_key",
40             "#method.make_ascii_uppercase",
41             "#method.make_ascii_lowercase",
42         ],
43     ),
44     // These try to link to std::collections, but are defined in alloc
45     // https://github.com/rust-lang/rust/issues/74481
46     ("std/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
47     ("std/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
48     ("alloc/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
49     ("alloc/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
50 ];
51
52 macro_rules! t {
53     ($e:expr) => {
54         match $e {
55             Ok(e) => e,
56             Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
57         }
58     };
59 }
60
61 fn main() {
62     let docs = env::args_os().nth(1).unwrap();
63     let docs = env::current_dir().unwrap().join(docs);
64     let mut errors = false;
65     walk(&mut HashMap::new(), &docs, &docs, &mut errors);
66     if errors {
67         panic!("found some broken links");
68     }
69 }
70
71 #[derive(Debug)]
72 pub enum LoadError {
73     IOError(std::io::Error),
74     BrokenRedirect(PathBuf, std::io::Error),
75     IsRedirect,
76 }
77
78 enum Redirect {
79     SkipRedirect,
80     FromRedirect(bool),
81 }
82
83 struct FileEntry {
84     source: Rc<String>,
85     ids: HashSet<String>,
86 }
87
88 type Cache = HashMap<PathBuf, FileEntry>;
89
90 fn small_url_encode(s: &str) -> String {
91     s.replace("<", "%3C")
92         .replace(">", "%3E")
93         .replace(" ", "%20")
94         .replace("?", "%3F")
95         .replace("'", "%27")
96         .replace("&", "%26")
97         .replace(",", "%2C")
98         .replace(":", "%3A")
99         .replace(";", "%3B")
100         .replace("[", "%5B")
101         .replace("]", "%5D")
102         .replace("\"", "%22")
103 }
104
105 impl FileEntry {
106     fn parse_ids(&mut self, file: &Path, contents: &str, errors: &mut bool) {
107         if self.ids.is_empty() {
108             with_attrs_in_source(contents, " id", |fragment, i, _| {
109                 let frag = fragment.trim_start_matches("#").to_owned();
110                 let encoded = small_url_encode(&frag);
111                 if !self.ids.insert(frag) {
112                     *errors = true;
113                     println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
114                 }
115                 // Just in case, we also add the encoded id.
116                 self.ids.insert(encoded);
117             });
118         }
119     }
120 }
121
122 fn walk(cache: &mut Cache, root: &Path, dir: &Path, errors: &mut bool) {
123     for entry in t!(dir.read_dir()).map(|e| t!(e)) {
124         let path = entry.path();
125         let kind = t!(entry.file_type());
126         if kind.is_dir() {
127             walk(cache, root, &path, errors);
128         } else {
129             let pretty_path = check(cache, root, &path, errors);
130             if let Some(pretty_path) = pretty_path {
131                 let entry = cache.get_mut(&pretty_path).unwrap();
132                 // we don't need the source anymore,
133                 // so drop to reduce memory-usage
134                 entry.source = Rc::new(String::new());
135             }
136         }
137     }
138 }
139
140 fn is_exception(file: &Path, link: &str) -> bool {
141     if let Some(entry) = LINKCHECK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
142         entry.1.contains(&link)
143     } else {
144         false
145     }
146 }
147
148 fn check(cache: &mut Cache, root: &Path, file: &Path, errors: &mut bool) -> Option<PathBuf> {
149     // Ignore non-HTML files.
150     if file.extension().and_then(|s| s.to_str()) != Some("html") {
151         return None;
152     }
153
154     let res = load_file(cache, root, file, SkipRedirect);
155     let (pretty_file, contents) = match res {
156         Ok(res) => res,
157         Err(_) => return None,
158     };
159     {
160         cache.get_mut(&pretty_file).unwrap().parse_ids(&pretty_file, &contents, errors);
161     }
162
163     // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
164     with_attrs_in_source(&contents, " href", |url, i, base| {
165         // Ignore external URLs
166         if url.starts_with("http:")
167             || url.starts_with("https:")
168             || url.starts_with("javascript:")
169             || url.starts_with("ftp:")
170             || url.starts_with("irc:")
171             || url.starts_with("data:")
172         {
173             return;
174         }
175         let mut parts = url.splitn(2, "#");
176         let url = parts.next().unwrap();
177         let fragment = parts.next();
178         let mut parts = url.splitn(2, "?");
179         let url = parts.next().unwrap();
180
181         // Once we've plucked out the URL, parse it using our base url and
182         // then try to extract a file path.
183         let mut path = file.to_path_buf();
184         if !base.is_empty() || !url.is_empty() {
185             path.pop();
186             for part in Path::new(base).join(url).components() {
187                 match part {
188                     Component::Prefix(_) | Component::RootDir => {
189                         // Avoid absolute paths as they make the docs not
190                         // relocatable by making assumptions on where the docs
191                         // are hosted relative to the site root.
192                         *errors = true;
193                         println!(
194                             "{}:{}: absolute path - {}",
195                             pretty_file.display(),
196                             i + 1,
197                             Path::new(base).join(url).display()
198                         );
199                         return;
200                     }
201                     Component::CurDir => {}
202                     Component::ParentDir => {
203                         path.pop();
204                     }
205                     Component::Normal(s) => {
206                         path.push(s);
207                     }
208                 }
209             }
210         }
211
212         // Alright, if we've found a file name then this file had better
213         // exist! If it doesn't then we register and print an error.
214         if path.exists() {
215             if path.is_dir() {
216                 // Links to directories show as directory listings when viewing
217                 // the docs offline so it's best to avoid them.
218                 *errors = true;
219                 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
220                 println!(
221                     "{}:{}: directory link - {}",
222                     pretty_file.display(),
223                     i + 1,
224                     pretty_path.display()
225                 );
226                 return;
227             }
228             if let Some(extension) = path.extension() {
229                 // Ignore none HTML files.
230                 if extension != "html" {
231                     return;
232                 }
233             }
234             let res = load_file(cache, root, &path, FromRedirect(false));
235             let (pretty_path, contents) = match res {
236                 Ok(res) => res,
237                 Err(LoadError::IOError(err)) => {
238                     panic!("error loading {}: {}", path.display(), err);
239                 }
240                 Err(LoadError::BrokenRedirect(target, _)) => {
241                     *errors = true;
242                     println!(
243                         "{}:{}: broken redirect to {}",
244                         pretty_file.display(),
245                         i + 1,
246                         target.display()
247                     );
248                     return;
249                 }
250                 Err(LoadError::IsRedirect) => unreachable!(),
251             };
252
253             if let Some(ref fragment) = fragment {
254                 // Fragments like `#1-6` are most likely line numbers to be
255                 // interpreted by javascript, so we're ignoring these
256                 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
257                     return;
258                 }
259
260                 // These appear to be broken in mdbook right now?
261                 if fragment.starts_with("-") {
262                     return;
263                 }
264
265                 let entry = &mut cache.get_mut(&pretty_path).unwrap();
266                 entry.parse_ids(&pretty_path, &contents, errors);
267
268                 if !entry.ids.contains(*fragment) && !is_exception(file, &format!("#{}", fragment))
269                 {
270                     *errors = true;
271                     print!("{}:{}: broken link fragment ", pretty_file.display(), i + 1);
272                     println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
273                 };
274             }
275         } else {
276             let pretty_path = path.strip_prefix(root).unwrap_or(&path);
277             if !is_exception(file, pretty_path.to_str().unwrap()) {
278                 *errors = true;
279                 print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
280                 println!("{}", pretty_path.display());
281             }
282         }
283     });
284     Some(pretty_file)
285 }
286
287 fn load_file(
288     cache: &mut Cache,
289     root: &Path,
290     file: &Path,
291     redirect: Redirect,
292 ) -> Result<(PathBuf, Rc<String>), LoadError> {
293     let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
294
295     let (maybe_redirect, contents) = match cache.entry(pretty_file.clone()) {
296         Entry::Occupied(entry) => (None, entry.get().source.clone()),
297         Entry::Vacant(entry) => {
298             let contents = match fs::read_to_string(file) {
299                 Ok(s) => Rc::new(s),
300                 Err(err) => {
301                     return Err(if let FromRedirect(true) = redirect {
302                         LoadError::BrokenRedirect(file.to_path_buf(), err)
303                     } else {
304                         LoadError::IOError(err)
305                     });
306                 }
307             };
308
309             let maybe = maybe_redirect(&contents);
310             if maybe.is_some() {
311                 if let SkipRedirect = redirect {
312                     return Err(LoadError::IsRedirect);
313                 }
314             } else {
315                 entry.insert(FileEntry { source: contents.clone(), ids: HashSet::new() });
316             }
317             (maybe, contents)
318         }
319     };
320     match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
321         Some(redirect_file) => load_file(cache, root, &redirect_file, FromRedirect(true)),
322         None => Ok((pretty_file, contents)),
323     }
324 }
325
326 fn maybe_redirect(source: &str) -> Option<String> {
327     const REDIRECT: &'static str = "<p>Redirecting to <a href=";
328
329     let mut lines = source.lines();
330     let redirect_line = lines.nth(6)?;
331
332     redirect_line.find(REDIRECT).map(|i| {
333         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
334         let pos_quote = rest.find('"').unwrap();
335         rest[..pos_quote].to_owned()
336     })
337 }
338
339 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
340     let mut base = "";
341     for (i, mut line) in contents.lines().enumerate() {
342         while let Some(j) = line.find(attr) {
343             let rest = &line[j + attr.len()..];
344             // The base tag should always be the first link in the document so
345             // we can get away with using one pass.
346             let is_base = line[..j].ends_with("<base");
347             line = rest;
348             let pos_equals = match rest.find("=") {
349                 Some(i) => i,
350                 None => continue,
351             };
352             if rest[..pos_equals].trim_start_matches(" ") != "" {
353                 continue;
354             }
355
356             let rest = &rest[pos_equals + 1..];
357
358             let pos_quote = match rest.find(&['"', '\''][..]) {
359                 Some(i) => i,
360                 None => continue,
361             };
362             let quote_delim = rest.as_bytes()[pos_quote] as char;
363
364             if rest[..pos_quote].trim_start_matches(" ") != "" {
365                 continue;
366             }
367             let rest = &rest[pos_quote + 1..];
368             let url = match rest.find(quote_delim) {
369                 Some(i) => &rest[..i],
370                 None => continue,
371             };
372             if is_base {
373                 base = url;
374                 continue;
375             }
376             f(url, i, base)
377         }
378     }
379 }