]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
Rollup merge of #42006 - jseyfried:fix_include_regression, r=nrc
[rust.git] / src / tools / linkchecker / main.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Script to check the validity of `href` links in our HTML documentation.
12 //!
13 //! In the past we've been quite error prone to writing in broken links as most
14 //! of them are manually rather than automatically added. As files move over
15 //! time or apis change old links become stale or broken. The purpose of this
16 //! script is to check all relative links in our documentation to make sure they
17 //! actually point to a valid place.
18 //!
19 //! Currently this doesn't actually do any HTML parsing or anything fancy like
20 //! that, it just has a simple "regex" to search for `href` and `id` tags.
21 //! These values are then translated to file URLs if possible and then the
22 //! destination is asserted to exist.
23 //!
24 //! A few whitelisted exceptions are allowed as there's known bugs in rustdoc,
25 //! but this should catch the majority of "broken link" cases.
26
27 use std::env;
28 use std::fs::File;
29 use std::io::prelude::*;
30 use std::path::{Path, PathBuf, Component};
31 use std::collections::{HashMap, HashSet};
32 use std::collections::hash_map::Entry;
33
34 use Redirect::*;
35
36 macro_rules! t {
37     ($e:expr) => (match $e {
38         Ok(e) => e,
39         Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
40     })
41 }
42
43 fn main() {
44     let docs = env::args_os().nth(1).unwrap();
45     let docs = env::current_dir().unwrap().join(docs);
46     let mut errors = false;
47     walk(&mut HashMap::new(), &docs, &docs, &mut errors);
48     if errors {
49         panic!("found some broken links");
50     }
51 }
52
53 #[derive(Debug)]
54 pub enum LoadError {
55     IOError(std::io::Error),
56     BrokenRedirect(PathBuf, std::io::Error),
57     IsRedirect,
58 }
59
60 enum Redirect {
61     SkipRedirect,
62     FromRedirect(bool),
63 }
64
65 struct FileEntry {
66     source: String,
67     ids: HashSet<String>,
68 }
69
70 type Cache = HashMap<PathBuf, FileEntry>;
71
72 impl FileEntry {
73     fn parse_ids(&mut self, file: &Path, contents: &str, errors: &mut bool) {
74         if self.ids.is_empty() {
75             with_attrs_in_source(contents, " id", |fragment, i, _| {
76                 let frag = fragment.trim_left_matches("#").to_owned();
77                 if !self.ids.insert(frag) {
78                     *errors = true;
79                     println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
80                 }
81             });
82         }
83     }
84 }
85
86 fn walk(cache: &mut Cache, root: &Path, dir: &Path, errors: &mut bool) {
87     for entry in t!(dir.read_dir()).map(|e| t!(e)) {
88         let path = entry.path();
89         let kind = t!(entry.file_type());
90         if kind.is_dir() {
91             walk(cache, root, &path, errors);
92         } else {
93             let pretty_path = check(cache, root, &path, errors);
94             if let Some(pretty_path) = pretty_path {
95                 let entry = cache.get_mut(&pretty_path).unwrap();
96                 // we don't need the source anymore,
97                 // so drop to reduce memory-usage
98                 entry.source = String::new();
99             }
100         }
101     }
102 }
103
104 fn check(cache: &mut Cache,
105          root: &Path,
106          file: &Path,
107          errors: &mut bool)
108          -> Option<PathBuf> {
109     // Ignore none HTML files.
110     if file.extension().and_then(|s| s.to_str()) != Some("html") {
111         return None;
112     }
113
114     // Unfortunately we're not 100% full of valid links today to we need a few
115     // whitelists to get this past `make check` today.
116     // FIXME(#32129)
117     if file.ends_with("std/string/struct.String.html") {
118         return None;
119     }
120     // FIXME(#32553)
121     if file.ends_with("collections/string/struct.String.html") {
122         return None;
123     }
124     // FIXME(#32130)
125     if file.ends_with("btree_set/struct.BTreeSet.html") ||
126        file.ends_with("collections/struct.BTreeSet.html") ||
127        file.ends_with("collections/btree_map/struct.BTreeMap.html") ||
128        file.ends_with("collections/hash_map/struct.HashMap.html") ||
129        file.ends_with("collections/hash_set/struct.HashSet.html") {
130         return None;
131     }
132
133     let res = load_file(cache, root, file, SkipRedirect);
134     let (pretty_file, contents) = match res {
135         Ok(res) => res,
136         Err(_) => return None,
137     };
138     {
139         cache.get_mut(&pretty_file)
140              .unwrap()
141              .parse_ids(&pretty_file, &contents, errors);
142     }
143
144     // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
145     with_attrs_in_source(&contents, " href", |url, i, base| {
146         // Ignore external URLs
147         if url.starts_with("http:") || url.starts_with("https:") ||
148            url.starts_with("javascript:") || url.starts_with("ftp:") ||
149            url.starts_with("irc:") || url.starts_with("data:") {
150             return;
151         }
152         let mut parts = url.splitn(2, "#");
153         let url = parts.next().unwrap();
154         let fragment = parts.next();
155         let mut parts = url.splitn(2, "?");
156         let url = parts.next().unwrap();
157
158         // Once we've plucked out the URL, parse it using our base url and
159         // then try to extract a file path.
160         let mut path = file.to_path_buf();
161         if !base.is_empty() || !url.is_empty() {
162             path.pop();
163             for part in Path::new(base).join(url).components() {
164                 match part {
165                     Component::Prefix(_) |
166                     Component::RootDir => panic!(),
167                     Component::CurDir => {}
168                     Component::ParentDir => { path.pop(); }
169                     Component::Normal(s) => { path.push(s); }
170                 }
171             }
172         }
173
174         // Alright, if we've found a file name then this file had better
175         // exist! If it doesn't then we register and print an error.
176         if path.exists() {
177             if path.is_dir() {
178                 // Links to directories show as directory listings when viewing
179                 // the docs offline so it's best to avoid them.
180                 *errors = true;
181                 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
182                 println!("{}:{}: directory link - {}",
183                          pretty_file.display(),
184                          i + 1,
185                          pretty_path.display());
186                 return;
187             }
188             if let Some(extension) = path.extension() {
189                 // Ignore none HTML files.
190                 if extension != "html" {
191                     return;
192                 }
193             }
194             let res = load_file(cache, root, &path, FromRedirect(false));
195             let (pretty_path, contents) = match res {
196                 Ok(res) => res,
197                 Err(LoadError::IOError(err)) => {
198                     panic!("error loading {}: {}", path.display(), err);
199                 }
200                 Err(LoadError::BrokenRedirect(target, _)) => {
201                     *errors = true;
202                     println!("{}:{}: broken redirect to {}",
203                              pretty_file.display(),
204                              i + 1,
205                              target.display());
206                     return;
207                 }
208                 Err(LoadError::IsRedirect) => unreachable!(),
209             };
210
211             if let Some(ref fragment) = fragment {
212                 // Fragments like `#1-6` are most likely line numbers to be
213                 // interpreted by javascript, so we're ignoring these
214                 if fragment.splitn(2, '-')
215                            .all(|f| f.chars().all(|c| c.is_numeric())) {
216                     return;
217                 }
218
219                 let entry = &mut cache.get_mut(&pretty_path).unwrap();
220                 entry.parse_ids(&pretty_path, &contents, errors);
221
222                 if !entry.ids.contains(*fragment) {
223                     *errors = true;
224                     print!("{}:{}: broken link fragment ",
225                            pretty_file.display(),
226                            i + 1);
227                     println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
228                 };
229             }
230         } else {
231             *errors = true;
232             print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
233             let pretty_path = path.strip_prefix(root).unwrap_or(&path);
234             println!("{}", pretty_path.display());
235         }
236     });
237     Some(pretty_file)
238 }
239
240 fn load_file(cache: &mut Cache,
241              root: &Path,
242              file: &Path,
243              redirect: Redirect)
244              -> Result<(PathBuf, String), LoadError> {
245     let mut contents = String::new();
246     let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
247
248     let maybe_redirect = match cache.entry(pretty_file.clone()) {
249         Entry::Occupied(entry) => {
250             contents = entry.get().source.clone();
251             None
252         }
253         Entry::Vacant(entry) => {
254             let mut fp = File::open(file).map_err(|err| {
255                 if let FromRedirect(true) = redirect {
256                     LoadError::BrokenRedirect(file.to_path_buf(), err)
257                 } else {
258                     LoadError::IOError(err)
259                 }
260             })?;
261             fp.read_to_string(&mut contents).map_err(|err| LoadError::IOError(err))?;
262
263             let maybe = maybe_redirect(&contents);
264             if maybe.is_some() {
265                 if let SkipRedirect = redirect {
266                     return Err(LoadError::IsRedirect);
267                 }
268             } else {
269                 entry.insert(FileEntry {
270                     source: contents.clone(),
271                     ids: HashSet::new(),
272                 });
273             }
274             maybe
275         }
276     };
277     match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
278         Some(redirect_file) => {
279             load_file(cache, root, &redirect_file, FromRedirect(true))
280         }
281         None => Ok((pretty_file, contents)),
282     }
283 }
284
285 fn maybe_redirect(source: &str) -> Option<String> {
286     const REDIRECT: &'static str = "<p>Redirecting to <a href=";
287
288     let mut lines = source.lines();
289     let redirect_line = match lines.nth(6) {
290         Some(l) => l,
291         None => return None,
292     };
293
294     redirect_line.find(REDIRECT).map(|i| {
295         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
296         let pos_quote = rest.find('"').unwrap();
297         rest[..pos_quote].to_owned()
298     })
299 }
300
301 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
302     let mut base = "";
303     for (i, mut line) in contents.lines().enumerate() {
304         while let Some(j) = line.find(attr) {
305             let rest = &line[j + attr.len()..];
306             // The base tag should always be the first link in the document so
307             // we can get away with using one pass.
308             let is_base = line[..j].ends_with("<base");
309             line = rest;
310             let pos_equals = match rest.find("=") {
311                 Some(i) => i,
312                 None => continue,
313             };
314             if rest[..pos_equals].trim_left_matches(" ") != "" {
315                 continue;
316             }
317
318             let rest = &rest[pos_equals + 1..];
319
320             let pos_quote = match rest.find(&['"', '\''][..]) {
321                 Some(i) => i,
322                 None => continue,
323             };
324             let quote_delim = rest.as_bytes()[pos_quote] as char;
325
326             if rest[..pos_quote].trim_left_matches(" ") != "" {
327                 continue;
328             }
329             let rest = &rest[pos_quote + 1..];
330             let url = match rest.find(quote_delim) {
331                 Some(i) => &rest[..i],
332                 None => continue,
333             };
334             if is_base {
335                 base = url;
336                 continue;
337             }
338             f(url, i, base)
339         }
340     }
341 }