You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

242 lines
7.8KB

  1. use lazy_static::lazy_static;
  2. use reqwest::header::{HeaderMap, ACCEPT};
  3. use reqwest::StatusCode;
  4. use config::LinkChecker;
  5. use errors::Result;
  6. use std::collections::HashMap;
  7. use std::error::Error;
  8. use std::sync::{Arc, RwLock};
  9. #[derive(Clone, Debug, PartialEq)]
  10. pub struct LinkResult {
  11. pub code: Option<StatusCode>,
  12. /// Whether the HTTP request didn't make it to getting a HTTP code
  13. pub error: Option<String>,
  14. }
  15. impl LinkResult {
  16. pub fn is_valid(&self) -> bool {
  17. if self.error.is_some() {
  18. return false;
  19. }
  20. if let Some(c) = self.code {
  21. return c.is_success();
  22. }
  23. true
  24. }
  25. pub fn message(&self) -> String {
  26. if let Some(ref e) = self.error {
  27. return e.clone();
  28. }
  29. if let Some(c) = self.code {
  30. return format!("{}", c);
  31. }
  32. "Unknown error".to_string()
  33. }
  34. }
  35. lazy_static! {
  36. // Keep history of link checks so a rebuild doesn't have to check again
  37. static ref LINKS: Arc<RwLock<HashMap<String, LinkResult>>> = Arc::new(RwLock::new(HashMap::new()));
  38. }
  39. pub fn check_url(url: &str, config: &LinkChecker) -> LinkResult {
  40. {
  41. let guard = LINKS.read().unwrap();
  42. if let Some(res) = guard.get(url) {
  43. return res.clone();
  44. }
  45. }
  46. let mut headers = HeaderMap::new();
  47. headers.insert(ACCEPT, "text/html".parse().unwrap());
  48. headers.append(ACCEPT, "*/*".parse().unwrap());
  49. let client = reqwest::Client::new();
  50. let check_anchor = !config.skip_anchor_prefixes.iter().any(|prefix| url.starts_with(prefix));
  51. // Need to actually do the link checking
  52. let res = match client.get(url).headers(headers).send() {
  53. Ok(ref mut response) if check_anchor && has_anchor(url) => {
  54. match check_page_for_anchor(url, response.text()) {
  55. Ok(_) => LinkResult { code: Some(response.status()), error: None },
  56. Err(e) => LinkResult { code: None, error: Some(e.to_string()) },
  57. }
  58. }
  59. Ok(response) => {
  60. if response.status().is_success() {
  61. LinkResult { code: Some(response.status()), error: None }
  62. } else {
  63. let error_string = if response.status().is_informational() {
  64. String::from(format!(
  65. "Informational status code ({}) received",
  66. response.status()
  67. ))
  68. } else if response.status().is_redirection() {
  69. String::from(format!(
  70. "Redirection status code ({}) received",
  71. response.status()
  72. ))
  73. } else if response.status().is_client_error() {
  74. String::from(format!(
  75. "Client error status code ({}) received",
  76. response.status()
  77. ))
  78. } else if response.status().is_server_error() {
  79. String::from(format!(
  80. "Server error status code ({}) received",
  81. response.status()
  82. ))
  83. } else {
  84. String::from("Non-success status code received")
  85. };
  86. LinkResult { code: None, error: Some(error_string) }
  87. }
  88. }
  89. Err(e) => LinkResult { code: None, error: Some(e.description().to_string()) },
  90. };
  91. LINKS.write().unwrap().insert(url.to_string(), res.clone());
  92. res
  93. }
  94. fn has_anchor(url: &str) -> bool {
  95. match url.find('#') {
  96. Some(index) => match url.get(index..=index + 1) {
  97. Some("#/") | Some("#!") | None => false,
  98. Some(_) => true,
  99. },
  100. None => false,
  101. }
  102. }
  103. fn check_page_for_anchor(url: &str, body: reqwest::Result<String>) -> Result<()> {
  104. let body = body.unwrap();
  105. let index = url.find('#').unwrap();
  106. let anchor = url.get(index + 1..).unwrap();
  107. let checks: [String; 4] = [
  108. format!(" id='{}'", anchor),
  109. format!(r#" id="{}""#, anchor),
  110. format!(" name='{}'", anchor),
  111. format!(r#" name="{}""#, anchor),
  112. ];
  113. if checks.iter().any(|check| body[..].contains(&check[..])) {
  114. Ok(())
  115. } else {
  116. Err(errors::Error::from(format!("Anchor `#{}` not found on page", anchor)))
  117. }
  118. }
  119. #[cfg(test)]
  120. mod tests {
  121. use super::{check_page_for_anchor, check_url, has_anchor, LinkChecker, LINKS};
  122. #[test]
  123. fn can_validate_ok_links() {
  124. let url = "https://google.com";
  125. let res = check_url(url, &LinkChecker::default());
  126. assert!(res.is_valid());
  127. assert!(LINKS.read().unwrap().get(url).is_some());
  128. let res = check_url(url, &LinkChecker::default());
  129. assert!(res.is_valid());
  130. }
  131. #[test]
  132. fn can_fail_404_links() {
  133. let res = check_url("https://google.comys", &LinkChecker::default());
  134. assert_eq!(res.is_valid(), false);
  135. assert!(res.code.is_none());
  136. assert!(res.error.is_some());
  137. }
  138. #[test]
  139. fn can_validate_anchors() {
  140. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect";
  141. let body = "<body><h3 id='method.collect'>collect</h3></body>".to_string();
  142. let res = check_page_for_anchor(url, Ok(body));
  143. assert!(res.is_ok());
  144. }
  145. #[test]
  146. fn can_validate_anchors_with_other_quotes() {
  147. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect";
  148. let body = r#"<body><h3 id="method.collect">collect</h3></body>"#.to_string();
  149. let res = check_page_for_anchor(url, Ok(body));
  150. assert!(res.is_ok());
  151. }
  152. #[test]
  153. fn can_validate_anchors_with_name_attr() {
  154. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect";
  155. let body = r#"<body><h3 name="method.collect">collect</h3></body>"#.to_string();
  156. let res = check_page_for_anchor(url, Ok(body));
  157. assert!(res.is_ok());
  158. }
  159. #[test]
  160. fn can_fail_when_anchor_not_found() {
  161. let url = "https://doc.rust-lang.org/std/iter/trait.Iterator.html#me";
  162. let body = "<body><h3 id='method.collect'>collect</h3></body>".to_string();
  163. let res = check_page_for_anchor(url, Ok(body));
  164. assert!(res.is_err());
  165. }
  166. #[test]
  167. fn can_check_url_for_anchor() {
  168. let url = "https://doc.rust-lang.org/std/index.html#the-rust-standard-library";
  169. let res = has_anchor(url);
  170. assert_eq!(res, true);
  171. }
  172. #[test]
  173. fn will_return_false_when_no_anchor() {
  174. let url = "https://doc.rust-lang.org/std/index.html";
  175. let res = has_anchor(url);
  176. assert_eq!(res, false);
  177. }
  178. #[test]
  179. fn will_return_false_when_has_router_url() {
  180. let url = "https://doc.rust-lang.org/#/std";
  181. let res = has_anchor(url);
  182. assert_eq!(res, false);
  183. }
  184. #[test]
  185. fn will_return_false_when_has_router_url_alt() {
  186. let url = "https://doc.rust-lang.org/#!/std";
  187. let res = has_anchor(url);
  188. assert_eq!(res, false);
  189. }
  190. #[test]
  191. fn skip_anchor_prefixes() {
  192. let config = LinkChecker {
  193. skip_prefixes: vec![],
  194. skip_anchor_prefixes: vec!["https://github.com/rust-lang/rust/blob/".to_owned()],
  195. };
  196. // anchor check is ignored because the url matches the prefix
  197. let permalink = "https://github.com/rust-lang/rust/blob/c772948b687488a087356cb91432425662e034b9/src/librustc_back/target/mod.rs#L194-L214";
  198. assert!(check_url(&permalink, &config).is_valid());
  199. // other anchors are checked
  200. let glossary = "https://help.github.com/en/articles/github-glossary#blame";
  201. assert!(check_url(&glossary, &config).is_valid());
  202. let glossary_invalid =
  203. "https://help.github.com/en/articles/github-glossary#anchor-does-not-exist";
  204. assert_eq!(check_url(&glossary_invalid, &config).is_valid(), false);
  205. }
  206. }