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::*;
26 // Add linkcheck exceptions here
27 // If at all possible you should use intra-doc links to avoid linkcheck issues. These
28 // are cases where that does not work
29 // [(generated_documentation_page, &[broken_links])]
30 const LINKCHECK_EXCEPTIONS: &[(&str, &[&str])] = &[
31 // These are methods on slice, and `Self` does not work on primitive impls
32 // in intra-doc links (primitive impls are weird)
33 // https://github.com/rust-lang/rust/issues/62834 is necessary to be
34 // able to link to slices
36 "std/io/struct.IoSlice.html",
39 "#method.sort_by_key",
40 "#method.make_ascii_uppercase",
41 "#method.make_ascii_lowercase",
44 // These try to link to std::collections, but are defined in alloc
45 // https://github.com/rust-lang/rust/issues/74481
46 ("std/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
47 ("std/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
48 ("alloc/collections/btree_map/struct.BTreeMap.html", &["#insert-and-complex-keys"]),
49 ("alloc/collections/btree_set/struct.BTreeSet.html", &["#insert-and-complex-keys"]),
56 Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
62 let docs = env::args_os().nth(1).unwrap();
63 let docs = env::current_dir().unwrap().join(docs);
64 let mut errors = false;
65 walk(&mut HashMap::new(), &docs, &docs, &mut errors);
67 panic!("found some broken links");
73 IOError(std::io::Error),
74 BrokenRedirect(PathBuf, std::io::Error),
88 type Cache = HashMap<PathBuf, FileEntry>;
90 fn small_url_encode(s: &str) -> String {
102 .replace("\"", "%22")
106 fn parse_ids(&mut self, file: &Path, contents: &str, errors: &mut bool) {
107 if self.ids.is_empty() {
108 with_attrs_in_source(contents, " id", |fragment, i, _| {
109 let frag = fragment.trim_start_matches("#").to_owned();
110 let encoded = small_url_encode(&frag);
111 if !self.ids.insert(frag) {
113 println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
115 // Just in case, we also add the encoded id.
116 self.ids.insert(encoded);
122 fn walk(cache: &mut Cache, root: &Path, dir: &Path, errors: &mut bool) {
123 for entry in t!(dir.read_dir()).map(|e| t!(e)) {
124 let path = entry.path();
125 let kind = t!(entry.file_type());
127 walk(cache, root, &path, errors);
129 let pretty_path = check(cache, root, &path, errors);
130 if let Some(pretty_path) = pretty_path {
131 let entry = cache.get_mut(&pretty_path).unwrap();
132 // we don't need the source anymore,
133 // so drop to reduce memory-usage
134 entry.source = Rc::new(String::new());
140 fn is_exception(file: &Path, link: &str) -> bool {
141 if let Some(entry) = LINKCHECK_EXCEPTIONS.iter().find(|&(f, _)| file.ends_with(f)) {
142 entry.1.contains(&link)
148 fn check(cache: &mut Cache, root: &Path, file: &Path, errors: &mut bool) -> Option<PathBuf> {
149 // Ignore non-HTML files.
150 if file.extension().and_then(|s| s.to_str()) != Some("html") {
154 let res = load_file(cache, root, file, SkipRedirect);
155 let (pretty_file, contents) = match res {
157 Err(_) => return None,
160 cache.get_mut(&pretty_file).unwrap().parse_ids(&pretty_file, &contents, errors);
163 // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
164 with_attrs_in_source(&contents, " href", |url, i, base| {
165 // Ignore external URLs
166 if url.starts_with("http:")
167 || url.starts_with("https:")
168 || url.starts_with("javascript:")
169 || url.starts_with("ftp:")
170 || url.starts_with("irc:")
171 || url.starts_with("data:")
175 let mut parts = url.splitn(2, "#");
176 let url = parts.next().unwrap();
177 let fragment = parts.next();
178 let mut parts = url.splitn(2, "?");
179 let url = parts.next().unwrap();
181 // Once we've plucked out the URL, parse it using our base url and
182 // then try to extract a file path.
183 let mut path = file.to_path_buf();
184 if !base.is_empty() || !url.is_empty() {
186 for part in Path::new(base).join(url).components() {
188 Component::Prefix(_) | 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.
194 "{}:{}: absolute path - {}",
195 pretty_file.display(),
197 Path::new(base).join(url).display()
201 Component::CurDir => {}
202 Component::ParentDir => {
205 Component::Normal(s) => {
212 // Alright, if we've found a file name then this file had better
213 // exist! If it doesn't then we register and print an error.
216 // Links to directories show as directory listings when viewing
217 // the docs offline so it's best to avoid them.
219 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
221 "{}:{}: directory link - {}",
222 pretty_file.display(),
224 pretty_path.display()
228 if let Some(extension) = path.extension() {
229 // Ignore none HTML files.
230 if extension != "html" {
234 let res = load_file(cache, root, &path, FromRedirect(false));
235 let (pretty_path, contents) = match res {
237 Err(LoadError::IOError(err)) => {
238 panic!("error loading {}: {}", path.display(), err);
240 Err(LoadError::BrokenRedirect(target, _)) => {
243 "{}:{}: broken redirect to {}",
244 pretty_file.display(),
250 Err(LoadError::IsRedirect) => unreachable!(),
253 if let Some(ref fragment) = fragment {
254 // Fragments like `#1-6` are most likely line numbers to be
255 // interpreted by javascript, so we're ignoring these
256 if fragment.splitn(2, '-').all(|f| f.chars().all(|c| c.is_numeric())) {
260 // These appear to be broken in mdbook right now?
261 if fragment.starts_with("-") {
265 let entry = &mut cache.get_mut(&pretty_path).unwrap();
266 entry.parse_ids(&pretty_path, &contents, errors);
268 if !entry.ids.contains(*fragment) && !is_exception(file, &format!("#{}", fragment))
271 print!("{}:{}: broken link fragment ", pretty_file.display(), i + 1);
272 println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
276 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
277 if !is_exception(file, pretty_path.to_str().unwrap()) {
279 print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
280 println!("{}", pretty_path.display());
292 ) -> Result<(PathBuf, Rc<String>), LoadError> {
293 let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
295 let (maybe_redirect, contents) = match cache.entry(pretty_file.clone()) {
296 Entry::Occupied(entry) => (None, entry.get().source.clone()),
297 Entry::Vacant(entry) => {
298 let contents = match fs::read_to_string(file) {
301 return Err(if let FromRedirect(true) = redirect {
302 LoadError::BrokenRedirect(file.to_path_buf(), err)
304 LoadError::IOError(err)
309 let maybe = maybe_redirect(&contents);
311 if let SkipRedirect = redirect {
312 return Err(LoadError::IsRedirect);
315 entry.insert(FileEntry { source: contents.clone(), ids: HashSet::new() });
320 match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
321 Some(redirect_file) => load_file(cache, root, &redirect_file, FromRedirect(true)),
322 None => Ok((pretty_file, contents)),
326 fn maybe_redirect(source: &str) -> Option<String> {
327 const REDIRECT: &'static str = "<p>Redirecting to <a href=";
329 let mut lines = source.lines();
330 let redirect_line = lines.nth(6)?;
332 redirect_line.find(REDIRECT).map(|i| {
333 let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
334 let pos_quote = rest.find('"').unwrap();
335 rest[..pos_quote].to_owned()
339 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
341 for (i, mut line) in contents.lines().enumerate() {
342 while let Some(j) = line.find(attr) {
343 let rest = &line[j + attr.len()..];
344 // The base tag should always be the first link in the document so
345 // we can get away with using one pass.
346 let is_base = line[..j].ends_with("<base");
348 let pos_equals = match rest.find("=") {
352 if rest[..pos_equals].trim_start_matches(" ") != "" {
356 let rest = &rest[pos_equals + 1..];
358 let pos_quote = match rest.find(&['"', '\''][..]) {
362 let quote_delim = rest.as_bytes()[pos_quote] as char;
364 if rest[..pos_quote].trim_start_matches(" ") != "" {
367 let rest = &rest[pos_quote + 1..];
368 let url = match rest.find(quote_delim) {
369 Some(i) => &rest[..i],