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 whitelisted exceptions are allowed as there's known bugs in rustdoc,
15 //! but this 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::{Path, PathBuf, Component};
27 ($e:expr) => (match $e {
29 Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
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);
39 panic!("found some broken links");
45 IOError(std::io::Error),
46 BrokenRedirect(PathBuf, std::io::Error),
60 type Cache = HashMap<PathBuf, FileEntry>;
62 fn small_url_encode(s: &str) -> String {
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_left_matches("#").to_owned();
82 let encoded = small_url_encode(&frag);
83 if !self.ids.insert(frag) {
85 println!("{}:{}: id is not unique: `{}`", file.display(), i, fragment);
87 // Just in case, we also add the encoded id.
88 self.ids.insert(encoded);
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());
99 walk(cache, root, &path, errors);
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());
112 fn check(cache: &mut Cache,
117 // Ignore none HTML files.
118 if file.extension().and_then(|s| s.to_str()) != Some("html") {
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.
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") {
139 if file.ends_with("string/struct.String.html") {
143 if file.ends_with("btree_set/struct.BTreeSet.html") ||
144 file.ends_with("struct.BTreeSet.html") ||
145 file.ends_with("btree_map/struct.BTreeMap.html") ||
146 file.ends_with("hash_map/struct.HashMap.html") ||
147 file.ends_with("hash_set/struct.HashSet.html") ||
148 file.ends_with("sync/struct.Lrc.html") ||
149 file.ends_with("sync/struct.RwLock.html") {
153 let res = load_file(cache, root, file, SkipRedirect);
154 let (pretty_file, contents) = match res {
156 Err(_) => return None,
159 cache.get_mut(&pretty_file)
161 .parse_ids(&pretty_file, &contents, errors);
164 // Search for anything that's the regex 'href[ ]*=[ ]*".*?"'
165 with_attrs_in_source(&contents, " href", |url, i, base| {
166 // Ignore external URLs
167 if url.starts_with("http:") || url.starts_with("https:") ||
168 url.starts_with("javascript:") || url.starts_with("ftp:") ||
169 url.starts_with("irc:") || url.starts_with("data:") {
172 let mut parts = url.splitn(2, "#");
173 let url = parts.next().unwrap();
174 let fragment = parts.next();
175 let mut parts = url.splitn(2, "?");
176 let url = parts.next().unwrap();
178 // Once we've plucked out the URL, parse it using our base url and
179 // then try to extract a file path.
180 let mut path = file.to_path_buf();
181 if !base.is_empty() || !url.is_empty() {
183 for part in Path::new(base).join(url).components() {
185 Component::Prefix(_) |
186 Component::RootDir => {
187 // Avoid absolute paths as they make the docs not
188 // relocatable by making assumptions on where the docs
189 // are hosted relative to the site root.
191 println!("{}:{}: absolute path - {}",
192 pretty_file.display(),
194 Path::new(base).join(url).display());
197 Component::CurDir => {}
198 Component::ParentDir => { path.pop(); }
199 Component::Normal(s) => { path.push(s); }
204 // Alright, if we've found a file name then this file had better
205 // exist! If it doesn't then we register and print an error.
208 // Links to directories show as directory listings when viewing
209 // the docs offline so it's best to avoid them.
211 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
212 println!("{}:{}: directory link - {}",
213 pretty_file.display(),
215 pretty_path.display());
218 if let Some(extension) = path.extension() {
219 // Ignore none HTML files.
220 if extension != "html" {
224 let res = load_file(cache, root, &path, FromRedirect(false));
225 let (pretty_path, contents) = match res {
227 Err(LoadError::IOError(err)) => {
228 panic!("error loading {}: {}", path.display(), err);
230 Err(LoadError::BrokenRedirect(target, _)) => {
232 println!("{}:{}: broken redirect to {}",
233 pretty_file.display(),
238 Err(LoadError::IsRedirect) => unreachable!(),
241 if let Some(ref fragment) = fragment {
242 // Fragments like `#1-6` are most likely line numbers to be
243 // interpreted by javascript, so we're ignoring these
244 if fragment.splitn(2, '-')
245 .all(|f| f.chars().all(|c| c.is_numeric())) {
249 // These appear to be broken in mdbook right now?
250 if fragment.starts_with("-") {
254 let entry = &mut cache.get_mut(&pretty_path).unwrap();
255 entry.parse_ids(&pretty_path, &contents, errors);
257 if !entry.ids.contains(*fragment) {
259 print!("{}:{}: broken link fragment ",
260 pretty_file.display(),
262 println!("`#{}` pointing to `{}`", fragment, pretty_path.display());
267 print!("{}:{}: broken link - ", pretty_file.display(), i + 1);
268 let pretty_path = path.strip_prefix(root).unwrap_or(&path);
269 println!("{}", pretty_path.display());
275 fn load_file(cache: &mut Cache,
279 -> Result<(PathBuf, Rc<String>), LoadError> {
280 let pretty_file = PathBuf::from(file.strip_prefix(root).unwrap_or(&file));
282 let (maybe_redirect, contents) = match cache.entry(pretty_file.clone()) {
283 Entry::Occupied(entry) => {
284 (None, entry.get().source.clone())
286 Entry::Vacant(entry) => {
287 let contents = match fs::read_to_string(file) {
290 return Err(if let FromRedirect(true) = redirect {
291 LoadError::BrokenRedirect(file.to_path_buf(), err)
293 LoadError::IOError(err)
298 let maybe = maybe_redirect(&contents);
300 if let SkipRedirect = redirect {
301 return Err(LoadError::IsRedirect);
304 entry.insert(FileEntry {
305 source: contents.clone(),
312 match maybe_redirect.map(|url| file.parent().unwrap().join(url)) {
313 Some(redirect_file) => {
314 load_file(cache, root, &redirect_file, FromRedirect(true))
316 None => Ok((pretty_file, contents)),
320 fn maybe_redirect(source: &str) -> Option<String> {
321 const REDIRECT: &'static str = "<p>Redirecting to <a href=";
323 let mut lines = source.lines();
324 let redirect_line = lines.nth(6)?;
326 redirect_line.find(REDIRECT).map(|i| {
327 let rest = &redirect_line[(i + REDIRECT.len() + 1)..];
328 let pos_quote = rest.find('"').unwrap();
329 rest[..pos_quote].to_owned()
333 fn with_attrs_in_source<F: FnMut(&str, usize, &str)>(contents: &str, attr: &str, mut f: F) {
335 for (i, mut line) in contents.lines().enumerate() {
336 while let Some(j) = line.find(attr) {
337 let rest = &line[j + attr.len()..];
338 // The base tag should always be the first link in the document so
339 // we can get away with using one pass.
340 let is_base = line[..j].ends_with("<base");
342 let pos_equals = match rest.find("=") {
346 if rest[..pos_equals].trim_left_matches(" ") != "" {
350 let rest = &rest[pos_equals + 1..];
352 let pos_quote = match rest.find(&['"', '\''][..]) {
356 let quote_delim = rest.as_bytes()[pos_quote] as char;
358 if rest[..pos_quote].trim_left_matches(" ") != "" {
361 let rest = &rest[pos_quote + 1..];
362 let url = match rest.find(quote_delim) {
363 Some(i) => &rest[..i],