]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
rustbuild: Tweak for vendored dependencies
[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().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 js files as they are not prone to errors as the rest of the
110     // documentation is and they otherwise bring up false positives.
111     if file.extension().and_then(|s| s.to_str()) == Some("js") {
112         return None;
113     }
114
115     // Unfortunately we're not 100% full of valid links today to we need a few
116     // whitelists to get this past `make check` today.
117     // FIXME(#32129)
118     if file.ends_with("std/string/struct.String.html") {
119         return None;
120     }
121     // FIXME(#32553)
122     if file.ends_with("collections/string/struct.String.html") {
123         return None;
124     }
125     // FIXME(#32130)
126     if file.ends_with("btree_set/struct.BTreeSet.html") ||
127        file.ends_with("collections/struct.BTreeSet.html") ||
128        file.ends_with("collections/btree_map/struct.BTreeMap.html") ||
129        file.ends_with("collections/hash_map/struct.HashMap.html") {
130         return None;
131     }
132
133     let res = load_file(cache, root, PathBuf::from(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| {
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         if url.is_empty() {
155             return
156         }
157         let fragment = parts.next();
158         let mut parts = url.splitn(2, "?");
159         let url = parts.next().unwrap();
160
161         // Once we've plucked out the URL, parse it using our base url and
162         // then try to extract a file path.
163         let mut path = file.to_path_buf();
164         path.pop();
165         for part in Path::new(url).components() {
166             match part {
167                 Component::Prefix(_) |
168                 Component::RootDir => panic!(),
169                 Component::CurDir => {}
170                 Component::ParentDir => { path.pop(); }
171                 Component::Normal(s) => { path.push(s); }
172             }
173         }
174
175         // Alright, if we've found a file name then this file had better
176         // exist! If it doesn't then we register and print an error.
177         if path.exists() {
178             if path.is_dir() {
179                 // Links to directories show as directory listings when viewing
180                 // the docs offline so it's best to avoid them.
181                 *errors = true;
182                 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
183                 println!("{}:{}: directory link - {}",
184                          pretty_file.display(),
185                          i + 1,
186                          pretty_path.display());
187                 return;
188             }
189             let res = load_file(cache, root, path.clone(), FromRedirect(false));
190             let (pretty_path, contents) = match res {
191                 Ok(res) => res,
192                 Err(LoadError::IOError(err)) => panic!(format!("{}", err)),
193                 Err(LoadError::BrokenRedirect(target, _)) => {
194                     *errors = true;
195                     println!("{}:{}: broken redirect to {}",
196                              pretty_file.display(),
197                              i + 1,
198                              target.display());
199                     return;
200                 }
201                 Err(LoadError::IsRedirect) => unreachable!(),
202             };
203
204             if let Some(ref fragment) = fragment {
205                 // Fragments like `#1-6` are most likely line numbers to be
206                 // interpreted by javascript, so we're ignoring these
207                 if fragment.splitn(2, '-')
208                            .all(|f| f.chars().all(|c| c.is_numeric())) {
209                     return;
210                 }
211
212                 let entry = &mut cache.get_mut(&pretty_path).unwrap();
213                 entry.parse_ids(&pretty_path, &contents, errors);
214
215                 if !entry.ids.contains(*fragment) {
216                     *errors = true;
217                     print!("{}:{}: broken link fragment  ",
218                            pretty_file.display(),
219                            i + 1);
220                     println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
221                 };
222             }
223         } else {
224             *errors = true;
225             print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
226             let pretty_path = path.strip_prefix(root).unwrap_or(&path);
227             println!("{}", pretty_path.display());
228         }
229     });
230     Some(pretty_file)
231 }
232
233 fn load_file(cache: &mut Cache,
234              root: &Path,
235              mut file: PathBuf,
236              redirect: Redirect)
237              -> Result<(PathBuf, String), LoadError> {
238     let mut contents = String::new();
239     let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
240
241     let maybe_redirect = match cache.entry(pretty_file.clone()) {
242         Entry::Occupied(entry) => {
243             contents = entry.get().source.clone();
244             None
245         }
246         Entry::Vacant(entry) => {
247             let mut fp = File::open(file.clone()).map_err(|err| {
248                 if let FromRedirect(true) = redirect {
249                     LoadError::BrokenRedirect(file.clone(), err)
250                 } else {
251                     LoadError::IOError(err)
252                 }
253             })?;
254             fp.read_to_string(&mut contents).map_err(|err| LoadError::IOError(err))?;
255
256             let maybe = maybe_redirect(&contents);
257             if maybe.is_some() {
258                 if let SkipRedirect = redirect {
259                     return Err(LoadError::IsRedirect);
260                 }
261             } else {
262                 entry.insert(FileEntry {
263                     source: contents.clone(),
264                     ids: HashSet::new(),
265                 });
266             }
267             maybe
268         }
269     };
270     file.pop();
271     match maybe_redirect.map(|url| file.join(url)) {
272         Some(redirect_file) => {
273             let path = PathBuf::from(redirect_file);
274             load_file(cache, root, path, FromRedirect(true))
275         }
276         None => Ok((pretty_file, contents)),
277     }
278 }
279
280 fn maybe_redirect(source: &str) -> Option<String> {
281     const REDIRECT: &'static str = "<p>Redirecting to <a href=";
282
283     let mut lines = source.lines();
284     let redirect_line = match lines.nth(6) {
285         Some(l) => l,
286         None => return None,
287     };
288
289     redirect_line.find(REDIRECT).map(|i| {
290         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
291         let pos_quote = rest.find('"').unwrap();
292         rest[..pos_quote].to_owned()
293     })
294 }
295
296 fn with_attrs_in_source<F: FnMut(&str, usize)>(contents: &str, attr: &str, mut f: F) {
297     for (i, mut line) in contents.lines().enumerate() {
298         while let Some(j) = line.find(attr) {
299             let rest = &line[j + attr.len()..];
300             line = rest;
301             let pos_equals = match rest.find("=") {
302                 Some(i) => i,
303                 None => continue,
304             };
305             if rest[..pos_equals].trim_left_matches(" ") != "" {
306                 continue;
307             }
308
309             let rest = &rest[pos_equals + 1..];
310
311             let pos_quote = match rest.find(&['"', '\''][..]) {
312                 Some(i) => i,
313                 None => continue,
314             };
315             let quote_delim = rest.as_bytes()[pos_quote] as char;
316
317             if rest[..pos_quote].trim_left_matches(" ") != "" {
318                 continue;
319             }
320             let rest = &rest[pos_quote + 1..];
321             let url = match rest.find(quote_delim) {
322                 Some(i) => &rest[..i],
323                 None => continue,
324             };
325             f(url, i)
326         }
327     }
328 }