1 //! Script to check the validity of `href` links in our HTML documentation.
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.
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.
14 //! A few exceptions are allowed as there's known bugs in rustdoc, but this
15 //! should catch the majority of "broken link" cases.
17 use std::collections::hash_map::Entry;
18 use std::collections::{HashMap, HashSet};
21 use std::path::{Component, Path, PathBuf};
24 use crate::Redirect::*;
30 Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
36 let docs = env::args_os().nth(1).unwrap();
37 let docs = env::current_dir().unwrap().join(docs);
38 let mut errors = false;
39 walk(&mut HashMap::new(), &docs, &docs, &mut errors);
41 panic!("found some broken links");
47 IOError(std::io::Error),
48 BrokenRedirect(PathBuf, std::io::Error),
62 type Cache = HashMap<PathBuf, FileEntry>;
64 fn small_url_encode(s: &str) -> String {
80 fn parse_ids(&mut self, file: &Path, contents: &str, errors: &mut bool) {
81 if self.ids.is_empty() {
82 with_attrs_in_source(contents, " id", |fragment, i, _| {
83 let frag = fragment.trim_start_matches("#").to_owned();
84 let encoded = small_url_encode(&frag);
85 if !self.ids.insert(frag) {
87 println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
89 // Just in case, we also add the encoded id.
90 self.ids.insert(encoded);
96 fn walk(cache: &mut Cache, root: &Path, dir: &Path, errors: &mut bool) {
97 for entry in t!(dir.read_dir()).map(|e| t!(e)) {
98 let path = entry.path();
99 let kind = t!(entry.file_type());
101 walk(cache, root, &path, errors);
103 let pretty_path = check(cache, root, &path, errors);
104 if let Some(pretty_path) = pretty_path {
105 let entry = cache.get_mut(&pretty_path).unwrap();
106 // we don't need the source anymore,
107 // so drop to reduce memory-usage
108 entry.source = Rc::new(String::new());
114 fn check(cache: &mut Cache, root: &Path, file: &Path, errors: &mut bool) -> Option<PathBuf> {
115 // Ignore non-HTML files.
116 if file.extension().and_then(|s| s.to_str()) != Some("html") {
120 // Unfortunately we're not 100% full of valid links today to we need a few
121 // exceptions to get this past `make check` today.
123 if file.ends_with("std/io/struct.IoSlice.html")
129 if file.ends_with("alloc/collections/btree_map/struct.BTreeMap.html")
130 || file.ends_with("alloc/collections/btree_set/struct.BTreeSet.html")
131 || file.ends_with("std/collections/btree_map/struct.BTreeMap.html")
132 || file.ends_with("std/collections/btree_set/struct.BTreeSet.html")
133 || file.ends_with("std/collections/hash_map/struct.HashMap.html")
134 || file.ends_with("std/collections/hash_set/struct.HashSet.html")
139 let res = load_file(cache, root, file, SkipRedirect);
140 let (pretty_file, contents) = match res {
142 Err(_) => return None,
145 cache.get_mut(&pretty_file).unwrap().parse_ids(&pretty_file, &contents, errors);
148 // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
149 with_attrs_in_source(&contents, " href", |url, i, base| {
150 // Ignore external URLs
151 if url.starts_with("http:")
152 || url.starts_with("https:")
153 || url.starts_with("javascript:")
154 || url.starts_with("ftp:")
155 || url.starts_with("irc:")
156 || url.starts_with("data:")
160 let mut parts = url.splitn(2, "#");
161 let url = parts.next().unwrap();
162 let fragment = parts.next();
163 let mut parts = url.splitn(2, "?");
164 let url = parts.next().unwrap();
166 // Once we've plucked out the URL, parse it using our base url and
167 // then try to extract a file path.
168 let mut path = file.to_path_buf();
169 if !base.is_empty() || !url.is_empty() {
171 for part in Path::new(base).join(url).components() {
173 Component::Prefix(_) | Component::RootDir => {
174 // Avoid absolute paths as they make the docs not
175 // relocatable by making assumptions on where the docs
176 // are hosted relative to the site root.
179 "{}:{}: absolute path - {}",
180 pretty_file.display(),
182 Path::new(base).join(url).display()
186 Component::CurDir => {}
187 Component::ParentDir => {
190 Component::Normal(s) => {
197 // Alright, if we've found a file name then this file had better
198 // exist! If it doesn't then we register and print an error.
201 // Links to directories show as directory listings when viewing
202 // the docs offline so it's best to avoid them.
204 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
206 "{}:{}: directory link - {}",
207 pretty_file.display(),
209 pretty_path.display()
213 if let Some(extension) = path.extension() {
214 // Ignore none HTML files.
215 if extension != "html" {
219 let res = load_file(cache, root, &path, FromRedirect(false));
220 let (pretty_path, contents) = match res {
222 Err(LoadError::IOError(err)) => {
223 panic!("error loading {}: {}", path.display(), err);
225 Err(LoadError::BrokenRedirect(target, _)) => {
228 "{}:{}: broken redirect to {}",
229 pretty_file.display(),
235 Err(LoadError::IsRedirect) => unreachable!(),
238 if let Some(ref fragment) = fragment {
239 // Fragments like `#1-6` are most likely line numbers to be
240 // interpreted by javascript, so we're ignoring these
241 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
245 // These appear to be broken in mdbook right now?
246 if fragment.starts_with("-") {
250 let entry = &mut cache.get_mut(&pretty_path).unwrap();
251 entry.parse_ids(&pretty_path, &contents, errors);
253 if !entry.ids.contains(*fragment) {
255 print!("{}:{}: broken link fragment ", pretty_file.display(), i + 1);
256 println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
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());
274 ) -> Result<(PathBuf, Rc<String>), LoadError> {
275 let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
277 let (maybe_redirect, contents) = match cache.entry(pretty_file.clone()) {
278 Entry::Occupied(entry) => (None, entry.get().source.clone()),
279 Entry::Vacant(entry) => {
280 let contents = match fs::read_to_string(file) {
283 return Err(if let FromRedirect(true) = redirect {
284 LoadError::BrokenRedirect(file.to_path_buf(), err)
286 LoadError::IOError(err)
291 let maybe = maybe_redirect(&contents);
293 if let SkipRedirect = redirect {
294 return Err(LoadError::IsRedirect);
297 entry.insert(FileEntry { source: contents.clone(), ids: HashSet::new() });
302 match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
303 Some(redirect_file) => load_file(cache, root, &redirect_file, FromRedirect(true)),
304 None => Ok((pretty_file, contents)),
308 fn maybe_redirect(source: &str) -> Option<String> {
309 const REDIRECT: &'static str = "<p>Redirecting to <a href=";
311 let mut lines = source.lines();
312 let redirect_line = lines.nth(6)?;
314 redirect_line.find(REDIRECT).map(|i| {
315 let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
316 let pos_quote = rest.find('"').unwrap();
317 rest[..pos_quote].to_owned()
321 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
323 for (i, mut line) in contents.lines().enumerate() {
324 while let Some(j) = line.find(attr) {
325 let rest = &line[j + attr.len()..];
326 // The base tag should always be the first link in the document so
327 // we can get away with using one pass.
328 let is_base = line[..j].ends_with("<base");
330 let pos_equals = match rest.find("=") {
334 if rest[..pos_equals].trim_start_matches(" ") != "" {
338 let rest = &rest[pos_equals + 1..];
340 let pos_quote = match rest.find(&['"', '\''][..]) {
344 let quote_delim = rest.as_bytes()[pos_quote] as char;
346 if rest[..pos_quote].trim_start_matches(" ") != "" {
349 let rest = &rest[pos_quote + 1..];
350 let url = match rest.find(quote_delim) {
351 Some(i) => &rest[..i],