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