]> git.lizzy.rs Git - rust.git/blob - src/tools/linkchecker/main.rs
Auto merge of #67445 - llogiq:todo, r=dtolnay
[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/string/struct.String.html")
126         || file.ends_with("interpret/struct.ImmTy.html")
127         || file.ends_with("ast/struct.ThinVec.html")
128         || file.ends_with("util/struct.ThinVec.html")
129         || file.ends_with("layout/struct.TyLayout.html")
130         || file.ends_with("humantime/struct.Timestamp.html")
131         || file.ends_with("log/index.html")
132         || file.ends_with("ty/struct.Slice.html")
133         || file.ends_with("ty/enum.Attributes.html")
134         || file.ends_with("ty/struct.SymbolName.html")
135         || file.ends_with("io/struct.IoSlice.html")
136         || file.ends_with("io/struct.IoSliceMut.html")
137     {
138         return None;
139     }
140     // FIXME(#32553)
141     if file.ends_with("string/struct.String.html") {
142         return None;
143     }
144     // FIXME(#32130)
145     if file.ends_with("btree_set/struct.BTreeSet.html")
146         || file.ends_with("struct.BTreeSet.html")
147         || file.ends_with("btree_map/struct.BTreeMap.html")
148         || file.ends_with("hash_map/struct.HashMap.html")
149         || file.ends_with("hash_set/struct.HashSet.html")
150         || file.ends_with("sync/struct.Lrc.html")
151         || file.ends_with("sync/struct.RwLock.html")
152     {
153         return None;
154     }
155
156     let res = load_file(cache, root, file, SkipRedirect);
157     let (pretty_file, contents) = match res {
158         Ok(res) => res,
159         Err(_) => return None,
160     };
161     {
162         cache.get_mut(&pretty_file).unwrap().parse_ids(&pretty_file, &contents, errors);
163     }
164
165     // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
166     with_attrs_in_source(&contents, " href", |url, i, base| {
167         // Ignore external URLs
168         if url.starts_with("http:")
169             || url.starts_with("https:")
170             || url.starts_with("javascript:")
171             || url.starts_with("ftp:")
172             || url.starts_with("irc:")
173             || url.starts_with("data:")
174         {
175             return;
176         }
177         let mut parts = url.splitn(2, "#");
178         let url = parts.next().unwrap();
179         let fragment = parts.next();
180         let mut parts = url.splitn(2, "?");
181         let url = parts.next().unwrap();
182
183         // Once we've plucked out the URL, parse it using our base url and
184         // then try to extract a file path.
185         let mut path = file.to_path_buf();
186         if !base.is_empty() || !url.is_empty() {
187             path.pop();
188             for part in Path::new(base).join(url).components() {
189                 match part {
190                     Component::Prefix(_) | 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!(
196                             "{}:{}: absolute path - {}",
197                             pretty_file.display(),
198                             i + 1,
199                             Path::new(base).join(url).display()
200                         );
201                         return;
202                     }
203                     Component::CurDir => {}
204                     Component::ParentDir => {
205                         path.pop();
206                     }
207                     Component::Normal(s) => {
208                         path.push(s);
209                     }
210                 }
211             }
212         }
213
214         // Alright, if we've found a file name then this file had better
215         // exist! If it doesn't then we register and print an error.
216         if path.exists() {
217             if path.is_dir() {
218                 // Links to directories show as directory listings when viewing
219                 // the docs offline so it's best to avoid them.
220                 *errors = true;
221                 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
222                 println!(
223                     "{}:{}: directory link - {}",
224                     pretty_file.display(),
225                     i + 1,
226                     pretty_path.display()
227                 );
228                 return;
229             }
230             if let Some(extension) = path.extension() {
231                 // Ignore none HTML files.
232                 if extension != "html" {
233                     return;
234                 }
235             }
236             let res = load_file(cache, root, &path, FromRedirect(false));
237             let (pretty_path, contents) = match res {
238                 Ok(res) => res,
239                 Err(LoadError::IOError(err)) => {
240                     panic!("error loading {}: {}", path.display(), err);
241                 }
242                 Err(LoadError::BrokenRedirect(target, _)) => {
243                     *errors = true;
244                     println!(
245                         "{}:{}: broken redirect to {}",
246                         pretty_file.display(),
247                         i + 1,
248                         target.display()
249                     );
250                     return;
251                 }
252                 Err(LoadError::IsRedirect) => unreachable!(),
253             };
254
255             if let Some(ref fragment) = fragment {
256                 // Fragments like `#1-6` are most likely line numbers to be
257                 // interpreted by javascript, so we're ignoring these
258                 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
259                     return;
260                 }
261
262                 // These appear to be broken in mdbook right now?
263                 if fragment.starts_with("-") {
264                     return;
265                 }
266
267                 let entry = &mut cache.get_mut(&pretty_path).unwrap();
268                 entry.parse_ids(&pretty_path, &contents, errors);
269
270                 if !entry.ids.contains(*fragment) {
271                     *errors = true;
272                     print!("{}:{}: broken link fragment ", pretty_file.display(), i + 1);
273                     println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
274                 };
275             }
276         } else {
277             *errors = true;
278             print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
279             let pretty_path = path.strip_prefix(root).unwrap_or(&path);
280             println!("{}", pretty_path.display());
281         }
282     });
283     Some(pretty_file)
284 }
285
286 fn load_file(
287     cache: &mut Cache,
288     root: &Path,
289     file: &Path,
290     redirect: Redirect,
291 ) -> Result<(PathBuf, Rc<String>), LoadError> {
292     let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
293
294     let (maybe_redirect, contents) = match cache.entry(pretty_file.clone()) {
295         Entry::Occupied(entry) => (None, entry.get().source.clone()),
296         Entry::Vacant(entry) => {
297             let contents = match fs::read_to_string(file) {
298                 Ok(s) => Rc::new(s),
299                 Err(err) => {
300                     return Err(if let FromRedirect(true) = redirect {
301                         LoadError::BrokenRedirect(file.to_path_buf(), err)
302                     } else {
303                         LoadError::IOError(err)
304                     });
305                 }
306             };
307
308             let maybe = maybe_redirect(&contents);
309             if maybe.is_some() {
310                 if let SkipRedirect = redirect {
311                     return Err(LoadError::IsRedirect);
312                 }
313             } else {
314                 entry.insert(FileEntry { source: contents.clone(), ids: HashSet::new() });
315             }
316             (maybe, contents)
317         }
318     };
319     match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
320         Some(redirect_file) => load_file(cache, root, &redirect_file, FromRedirect(true)),
321         None => Ok((pretty_file, contents)),
322     }
323 }
324
325 fn maybe_redirect(source: &str) -> Option<String> {
326     const REDIRECT: &'static str = "<p>Redirecting to <a href=";
327
328     let mut lines = source.lines();
329     let redirect_line = lines.nth(6)?;
330
331     redirect_line.find(REDIRECT).map(|i| {
332         let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
333         let pos_quote = rest.find('"').unwrap();
334         rest[..pos_quote].to_owned()
335     })
336 }
337
338 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
339     let mut base = "";
340     for (i, mut line) in contents.lines().enumerate() {
341         while let Some(j) = line.find(attr) {
342             let rest = &line[j + attr.len()..];
343             // The base tag should always be the first link in the document so
344             // we can get away with using one pass.
345             let is_base = line[..j].ends_with("<base");
346             line = rest;
347             let pos_equals = match rest.find("=") {
348                 Some(i) => i,
349                 None => continue,
350             };
351             if rest[..pos_equals].trim_start_matches(" ") != "" {
352                 continue;
353             }
354
355             let rest = &rest[pos_equals + 1..];
356
357             let pos_quote = match rest.find(&['"', '\''][..]) {
358                 Some(i) => i,
359                 None => continue,
360             };
361             let quote_delim = rest.as_bytes()[pos_quote] as char;
362
363             if rest[..pos_quote].trim_start_matches(" ") != "" {
364                 continue;
365             }
366             let rest = &rest[pos_quote + 1..];
367             let url = match rest.find(quote_delim) {
368                 Some(i) => &rest[..i],
369                 None => continue,
370             };
371             if is_base {
372                 base = url;
373                 continue;
374             }
375             f(url, i, base)
376         }
377     }
378 }