]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
Rollup merge of #47277 - tspiteri:log-correctness, r=frewsxcv
[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 fn small_url_encode(s: &str) -> String {
73     s.replace("<", "%3C")
74      .replace(">", "%3E")
75      .replace(" ", "%20")
76      .replace("?", "%3F")
77      .replace("'", "%27")
78      .replace("&", "%26")
79      .replace(",", "%2C")
80      .replace(":", "%3A")
81      .replace(";", "%3B")
82      .replace("[", "%5B")
83      .replace("]", "%5D")
84      .replace("\"", "%22")
85 }
86
87 impl FileEntry {
88     fn parse_ids(&mut self, file: &Path, contents: &str, errors: &mut bool) {
89         if self.ids.is_empty() {
90             with_attrs_in_source(contents, " id", |fragment, i, _| {
91                 let frag = fragment.trim_left_matches("#").to_owned();
92                 let encoded = small_url_encode(&frag);
93                 if !self.ids.insert(frag) {
94                     *errors = true;
95                     println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
96                 }
97                 // Just in case, we also add the encoded id.
98                 self.ids.insert(encoded);
99             });
100         }
101     }
102 }
103
104 fn walk(cache: &mut Cache, root: &Path, dir: &Path, errors: &mut bool) {
105     for entry in t!(dir.read_dir()).map(|e| t!(e)) {
106         let path = entry.path();
107         let kind = t!(entry.file_type());
108         if kind.is_dir() {
109             walk(cache, root, &path, errors);
110         } else {
111             let pretty_path = check(cache, root, &path, errors);
112             if let Some(pretty_path) = pretty_path {
113                 let entry = cache.get_mut(&pretty_path).unwrap();
114                 // we don't need the source anymore,
115                 // so drop to reduce memory-usage
116                 entry.source = String::new();
117             }
118         }
119     }
120 }
121
122 fn check(cache: &mut Cache,
123          root: &Path,
124          file: &Path,
125          errors: &mut bool)
126          -> Option<PathBuf> {
127     // Ignore none HTML files.
128     if file.extension().and_then(|s| s.to_str()) != Some("html") {
129         return None;
130     }
131
132     // Unfortunately we're not 100% full of valid links today to we need a few
133     // whitelists to get this past `make check` today.
134     // FIXME(#32129)
135     if file.ends_with("std/string/struct.String.html") ||
136        file.ends_with("interpret/struct.ValTy.html") ||
137        file.ends_with("symbol/struct.InternedString.html") ||
138        file.ends_with("ast/struct.ThinVec.html") ||
139        file.ends_with("util/struct.ThinVec.html") ||
140        file.ends_with("util/struct.RcSlice.html") ||
141        file.ends_with("layout/struct.TyLayout.html") ||
142        file.ends_with("ty/struct.Slice.html") ||
143        file.ends_with("ty/enum.Attributes.html") ||
144        file.ends_with("ty/struct.SymbolName.html") {
145         return None;
146     }
147     // FIXME(#32553)
148     if file.ends_with("string/struct.String.html") {
149         return None;
150     }
151     // FIXME(#32130)
152     if file.ends_with("btree_set/struct.BTreeSet.html") ||
153        file.ends_with("struct.BTreeSet.html") ||
154        file.ends_with("btree_map/struct.BTreeMap.html") ||
155        file.ends_with("hash_map/struct.HashMap.html") ||
156        file.ends_with("hash_set/struct.HashSet.html") ||
157        file.ends_with("sync/struct.Lrc.html") ||
158        file.ends_with("sync/struct.RwLock.html") {
159         return None;
160     }
161
162     let res = load_file(cache, root, file, SkipRedirect);
163     let (pretty_file, contents) = match res {
164         Ok(res) => res,
165         Err(_) => return None,
166     };
167     {
168         cache.get_mut(&pretty_file)
169              .unwrap()
170              .parse_ids(&pretty_file, &contents, errors);
171     }
172
173     // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
174     with_attrs_in_source(&contents, " href", |url, i, base| {
175         // Ignore external URLs
176         if url.starts_with("http:") || url.starts_with("https:") ||
177            url.starts_with("javascript:") || url.starts_with("ftp:") ||
178            url.starts_with("irc:") || url.starts_with("data:") {
179             return;
180         }
181         let mut parts = url.splitn(2, "#");
182         let url = parts.next().unwrap();
183         let fragment = parts.next();
184         let mut parts = url.splitn(2, "?");
185         let url = parts.next().unwrap();
186
187         // Once we've plucked out the URL, parse it using our base url and
188         // then try to extract a file path.
189         let mut path = file.to_path_buf();
190         if !base.is_empty() || !url.is_empty() {
191             path.pop();
192             for part in Path::new(base).join(url).components() {
193                 match part {
194                     Component::Prefix(_) |
195                     Component::RootDir => panic!(),
196                     Component::CurDir => {}
197                     Component::ParentDir => { path.pop(); }
198                     Component::Normal(s) => { path.push(s); }
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!("{}:{}: directory link - {}",
212                          pretty_file.display(),
213                          i + 1,
214                          pretty_path.display());
215                 return;
216             }
217             if let Some(extension) = path.extension() {
218                 // Ignore none HTML files.
219                 if extension != "html" {
220                     return;
221                 }
222             }
223             let res = load_file(cache, root, &path, FromRedirect(false));
224             let (pretty_path, contents) = match res {
225                 Ok(res) => res,
226                 Err(LoadError::IOError(err)) => {
227                     panic!("error loading {}: {}", path.display(), err);
228                 }
229                 Err(LoadError::BrokenRedirect(target, _)) => {
230                     *errors = true;
231                     println!("{}:{}: broken redirect to {}",
232                              pretty_file.display(),
233                              i + 1,
234                              target.display());
235                     return;
236                 }
237                 Err(LoadError::IsRedirect) => unreachable!(),
238             };
239
240             if let Some(ref fragment) = fragment {
241                 // Fragments like `#1-6` are most likely line numbers to be
242                 // interpreted by javascript, so we're ignoring these
243                 if fragment.splitn(2, '-')
244                            .all(|f| f.chars().all(|c| c.is_numeric())) {
245                     return;
246                 }
247
248                 let entry = &mut cache.get_mut(&pretty_path).unwrap();
249                 entry.parse_ids(&pretty_path, &contents, errors);
250
251                 if !entry.ids.contains(*fragment) {
252                     *errors = true;
253                     print!("{}:{}: broken link fragment ",
254                            pretty_file.display(),
255                            i + 1);
256                     println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
257                 };
258             }
259         } else {
260             *errors = true;
261             print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
262             let pretty_path = path.strip_prefix(root).unwrap_or(&path);
263             println!("{}", pretty_path.display());
264         }
265     });
266     Some(pretty_file)
267 }
268
269 fn load_file(cache: &mut Cache,
270              root: &Path,
271              file: &Path,
272              redirect: Redirect)
273              -> Result<(PathBuf, String), LoadError> {
274     let mut contents = String::new();
275     let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
276
277     let maybe_redirect = match cache.entry(pretty_file.clone()) {
278         Entry::Occupied(entry) => {
279             contents = entry.get().source.clone();
280             None
281         }
282         Entry::Vacant(entry) => {
283             let mut fp = File::open(file).map_err(|err| {
284                 if let FromRedirect(true) = redirect {
285                     LoadError::BrokenRedirect(file.to_path_buf(), err)
286                 } else {
287                     LoadError::IOError(err)
288                 }
289             })?;
290             fp.read_to_string(&mut contents).map_err(|err| LoadError::IOError(err))?;
291
292             let maybe = maybe_redirect(&contents);
293             if maybe.is_some() {
294                 if let SkipRedirect = redirect {
295                     return Err(LoadError::IsRedirect);
296                 }
297             } else {
298                 entry.insert(FileEntry {
299                     source: contents.clone(),
300                     ids: HashSet::new(),
301                 });
302             }
303             maybe
304         }
305     };
306     match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
307         Some(redirect_file) => {
308             load_file(cache, root, &redirect_file, FromRedirect(true))
309         }
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 = match lines.nth(6) {
319         Some(l) => l,
320         None => return None,
321     };
322
323     redirect_line.find(REDIRECT).map(|i| {
324         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
325         let pos_quote = rest.find('"').unwrap();
326         rest[..pos_quote].to_owned()
327     })
328 }
329
330 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
331     let mut base = "";
332     for (i, mut line) in contents.lines().enumerate() {
333         while let Some(j) = line.find(attr) {
334             let rest = &line[j + attr.len()..];
335             // The base tag should always be the first link in the document so
336             // we can get away with using one pass.
337             let is_base = line[..j].ends_with("<base");
338             line = rest;
339             let pos_equals = match rest.find("=") {
340                 Some(i) => i,
341                 None => continue,
342             };
343             if rest[..pos_equals].trim_left_matches(" ") != "" {
344                 continue;
345             }
346
347             let rest = &rest[pos_equals + 1..];
348
349             let pos_quote = match rest.find(&['"', '\''][..]) {
350                 Some(i) => i,
351                 None => continue,
352             };
353             let quote_delim = rest.as_bytes()[pos_quote] as char;
354
355             if rest[..pos_quote].trim_left_matches(" ") != "" {
356                 continue;
357             }
358             let rest = &rest[pos_quote + 1..];
359             let url = match rest.find(quote_delim) {
360                 Some(i) => &rest[..i],
361                 None => continue,
362             };
363             if is_base {
364                 base = url;
365                 continue;
366             }
367             f(url, i, base)
368         }
369     }
370 }