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