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.
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.
11 //! Script to check the validity of `href` links in our HTML documentation.
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.
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.
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.
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;
37 ($e:expr) => (match $e {
39 Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
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);
49 panic!("found some broken links");
55 IOError(std::io::Error),
56 BrokenRedirect(PathBuf, std::io::Error),
70 type Cache = HashMap<PathBuf, 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) {
79 println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
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());
91 walk(cache, root, &path, errors);
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();
104 fn check(cache: &mut Cache,
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") {
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.
118 if file.ends_with("std/string/struct.String.html") {
122 if file.ends_with("collections/string/struct.String.html") {
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") {
133 let res = load_file(cache, root, PathBuf::from(file), SkipRedirect);
134 let (pretty_file, contents) = match res {
136 Err(_) => return None,
139 cache.get_mut(&pretty_file)
141 .parse_ids(&pretty_file, &contents, errors);
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:") {
152 let mut parts = url.splitn(2, "#");
153 let url = parts.next().unwrap();
157 let fragment = parts.next();
158 let mut parts = url.splitn(2, "?");
159 let url = parts.next().unwrap();
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();
165 for part in Path::new(url).components() {
167 Component::Prefix(_) |
168 Component::RootDir => panic!(),
169 Component::CurDir => {}
170 Component::ParentDir => { path.pop(); }
171 Component::Normal(s) => { path.push(s); }
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.
179 // Links to directories show as directory listings when viewing
180 // the docs offline so it's best to avoid them.
182 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
183 println!("{}:{}: directory link - {}",
184 pretty_file.display(),
186 pretty_path.display());
189 let res = load_file(cache, root, path.clone(), FromRedirect(false));
190 let (pretty_path, contents) = match res {
192 Err(LoadError::IOError(err)) => panic!(format!("{}", err)),
193 Err(LoadError::BrokenRedirect(target, _)) => {
195 println!("{}:{}: broken redirect to {}",
196 pretty_file.display(),
201 Err(LoadError::IsRedirect) => unreachable!(),
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())) {
212 let entry = &mut cache.get_mut(&pretty_path).unwrap();
213 entry.parse_ids(&pretty_path, &contents, errors);
215 if !entry.ids.contains(*fragment) {
217 print!("{}:{}: broken link fragment ",
218 pretty_file.display(),
220 println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
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());
233 fn load_file(cache: &mut Cache,
237 -> Result<(PathBuf, String), LoadError> {
238 let mut contents = String::new();
239 let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
241 let maybe_redirect = match cache.entry(pretty_file.clone()) {
242 Entry::Occupied(entry) => {
243 contents = entry.get().source.clone();
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)
251 LoadError::IOError(err)
254 fp.read_to_string(&mut contents).map_err(|err| LoadError::IOError(err))?;
256 let maybe = maybe_redirect(&contents);
258 if let SkipRedirect = redirect {
259 return Err(LoadError::IsRedirect);
262 entry.insert(FileEntry {
263 source: contents.clone(),
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))
276 None => Ok((pretty_file, contents)),
280 fn maybe_redirect(source: &str) -> Option<String> {
281 const REDIRECT: &'static str = "<p>Redirecting to <a href=";
283 let mut lines = source.lines();
284 let redirect_line = match lines.nth(6) {
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()
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()..];
301 let pos_equals = match rest.find("=") {
305 if rest[..pos_equals].trim_left_matches(" ") != "" {
309 let rest = &rest[pos_equals + 1..];
311 let pos_quote = match rest.find(&['"', '\''][..]) {
315 let quote_delim = rest.as_bytes()[pos_quote] as char;
317 if rest[..pos_quote].trim_left_matches(" ") != "" {
320 let rest = &rest[pos_quote + 1..];
321 let url = match rest.find(quote_delim) {
322 Some(i) => &rest[..i],