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