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_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);
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 none HTML files.
110 if file.extension().and_then(|s| s.to_str()) != Some("html") {
114 // Unfortunately we're not 100% full of valid links today to we need a few
115 // whitelists to get this past `make check` today.
117 if file.ends_with("std/string/struct.String.html") {
121 if file.ends_with("collections/string/struct.String.html") {
125 if file.ends_with("btree_set/struct.BTreeSet.html") ||
126 file.ends_with("collections/struct.BTreeSet.html") ||
127 file.ends_with("collections/btree_map/struct.BTreeMap.html") ||
128 file.ends_with("collections/hash_map/struct.HashMap.html") ||
129 file.ends_with("collections/hash_set/struct.HashSet.html") {
133 let res = load_file(cache, root, 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, base| {
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();
154 let fragment = parts.next();
155 let mut parts = url.splitn(2, "?");
156 let url = parts.next().unwrap();
158 // Once we've plucked out the URL, parse it using our base url and
159 // then try to extract a file path.
160 let mut path = file.to_path_buf();
161 if !base.is_empty() || !url.is_empty() {
163 for part in Path::new(base).join(url).components() {
165 Component::Prefix(_) |
166 Component::RootDir => panic!(),
167 Component::CurDir => {}
168 Component::ParentDir => { path.pop(); }
169 Component::Normal(s) => { path.push(s); }
174 // Alright, if we've found a file name then this file had better
175 // exist! If it doesn't then we register and print an error.
178 // Links to directories show as directory listings when viewing
179 // the docs offline so it's best to avoid them.
181 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
182 println!("{}:{}: directory link - {}",
183 pretty_file.display(),
185 pretty_path.display());
188 if let Some(extension) = path.extension() {
189 // Ignore none HTML files.
190 if extension != "html" {
194 let res = load_file(cache, root, &path, FromRedirect(false));
195 let (pretty_path, contents) = match res {
197 Err(LoadError::IOError(err)) => {
198 panic!("error loading {}: {}", path.display(), err);
200 Err(LoadError::BrokenRedirect(target, _)) => {
202 println!("{}:{}: broken redirect to {}",
203 pretty_file.display(),
208 Err(LoadError::IsRedirect) => unreachable!(),
211 if let Some(ref fragment) = fragment {
212 // Fragments like `#1-6` are most likely line numbers to be
213 // interpreted by javascript, so we're ignoring these
214 if fragment.splitn(2, '-')
215 .all(|f| f.chars().all(|c| c.is_numeric())) {
219 let entry = &mut cache.get_mut(&pretty_path).unwrap();
220 entry.parse_ids(&pretty_path, &contents, errors);
222 if !entry.ids.contains(*fragment) {
224 print!("{}:{}: broken link fragment ",
225 pretty_file.display(),
227 println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
232 print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
233 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
234 println!("{}", pretty_path.display());
240 fn load_file(cache: &mut Cache,
244 -> Result<(PathBuf, String), LoadError> {
245 let mut contents = String::new();
246 let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
248 let maybe_redirect = match cache.entry(pretty_file.clone()) {
249 Entry::Occupied(entry) => {
250 contents = entry.get().source.clone();
253 Entry::Vacant(entry) => {
254 let mut fp = File::open(file).map_err(|err| {
255 if let FromRedirect(true) = redirect {
256 LoadError::BrokenRedirect(file.to_path_buf(), err)
258 LoadError::IOError(err)
261 fp.read_to_string(&mut contents).map_err(|err| LoadError::IOError(err))?;
263 let maybe = maybe_redirect(&contents);
265 if let SkipRedirect = redirect {
266 return Err(LoadError::IsRedirect);
269 entry.insert(FileEntry {
270 source: contents.clone(),
277 match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
278 Some(redirect_file) => {
279 load_file(cache, root, &redirect_file, FromRedirect(true))
281 None => Ok((pretty_file, contents)),
285 fn maybe_redirect(source: &str) -> Option<String> {
286 const REDIRECT: &'static str = "<p>Redirecting to <a href=";
288 let mut lines = source.lines();
289 let redirect_line = match lines.nth(6) {
294 redirect_line.find(REDIRECT).map(|i| {
295 let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
296 let pos_quote = rest.find('"').unwrap();
297 rest[..pos_quote].to_owned()
301 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
303 for (i, mut line) in contents.lines().enumerate() {
304 while let Some(j) = line.find(attr) {
305 let rest = &line[j + attr.len()..];
306 // The base tag should always be the first link in the document so
307 // we can get away with using one pass.
308 let is_base = line[..j].ends_with("<base");
310 let pos_equals = match rest.find("=") {
314 if rest[..pos_equals].trim_left_matches(" ") != "" {
318 let rest = &rest[pos_equals + 1..];
320 let pos_quote = match rest.find(&['"', '\''][..]) {
324 let quote_delim = rest.as_bytes()[pos_quote] as char;
326 if rest[..pos_quote].trim_left_matches(" ") != "" {
329 let rest = &rest[pos_quote + 1..];
330 let url = match rest.find(quote_delim) {
331 Some(i) => &rest[..i],