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.

page.rs 17KB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /// A page, can be a blog post or a basic page
  2. use std::collections::HashMap;
  3. use std::path::{Path, PathBuf};
  4. use std::result::Result as StdResult;
  5. use tera::{Tera, Context as TeraContext};
  6. use serde::ser::{SerializeStruct, self};
  7. use slug::slugify;
  8. use errors::{Result, ResultExt};
  9. use config::Config;
  10. use utils::fs::{read_file, find_related_assets};
  11. use utils::site::get_reading_analytics;
  12. use utils::templates::render_template;
  13. use front_matter::{PageFrontMatter, InsertAnchor, split_page_content};
  14. use rendering::{Context, Header, markdown_to_html};
  15. use file_info::FileInfo;
  16. #[derive(Clone, Debug, PartialEq)]
  17. pub struct Page {
  18. /// All info about the actual file
  19. pub file: FileInfo,
  20. /// The front matter meta-data
  21. pub meta: PageFrontMatter,
  22. /// The actual content of the page, in markdown
  23. pub raw_content: String,
  24. /// All the non-md files we found next to the .md file
  25. pub assets: Vec<PathBuf>,
  26. /// The HTML rendered of the page
  27. pub content: String,
  28. /// The slug of that page.
  29. /// First tries to find the slug in the meta and defaults to filename otherwise
  30. pub slug: String,
  31. /// The URL path of the page
  32. pub path: String,
  33. /// The components of the path of the page
  34. pub components: Vec<String>,
  35. /// The full URL for that page
  36. pub permalink: String,
  37. /// The summary for the article, defaults to None
  38. /// When <!-- more --> is found in the text, will take the content up to that part
  39. /// as summary
  40. pub summary: Option<String>,
  41. /// The previous page, by whatever sorting is used for the index/section
  42. pub previous: Option<Box<Page>>,
  43. /// The next page, by whatever sorting is used for the index/section
  44. pub next: Option<Box<Page>>,
  45. /// Toc made from the headers of the markdown file
  46. pub toc: Vec<Header>,
  47. }
  48. impl Page {
  49. pub fn new<P: AsRef<Path>>(file_path: P, meta: PageFrontMatter) -> Page {
  50. let file_path = file_path.as_ref();
  51. Page {
  52. file: FileInfo::new_page(file_path),
  53. meta,
  54. raw_content: "".to_string(),
  55. assets: vec![],
  56. content: "".to_string(),
  57. slug: "".to_string(),
  58. path: "".to_string(),
  59. components: vec![],
  60. permalink: "".to_string(),
  61. summary: None,
  62. previous: None,
  63. next: None,
  64. toc: vec![],
  65. }
  66. }
  67. pub fn is_draft(&self) -> bool {
  68. self.meta.draft.unwrap_or(false)
  69. }
  70. /// Parse a page given the content of the .md file
  71. /// Files without front matter or with invalid front matter are considered
  72. /// erroneous
  73. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Page> {
  74. let (meta, content) = split_page_content(file_path, content)?;
  75. let mut page = Page::new(file_path, meta);
  76. page.raw_content = content;
  77. page.slug = {
  78. if let Some(ref slug) = page.meta.slug {
  79. slug.trim().to_string()
  80. } else {
  81. if page.file.name == "index" {
  82. if let Some(parent) = page.file.path.parent() {
  83. slugify(parent.file_name().unwrap().to_str().unwrap())
  84. } else {
  85. slugify(page.file.name.clone())
  86. }
  87. } else {
  88. slugify(page.file.name.clone())
  89. }
  90. }
  91. };
  92. if let Some(ref p) = page.meta.path {
  93. page.path = p.trim().trim_left_matches('/').to_string();
  94. } else {
  95. page.path = if page.file.components.is_empty() {
  96. page.slug.clone()
  97. } else {
  98. format!("{}/{}", page.file.components.join("/"), page.slug)
  99. };
  100. }
  101. if !page.path.ends_with('/') {
  102. page.path = format!("{}/", page.path);
  103. }
  104. page.components = page.path.split('/')
  105. .map(|p| p.to_string())
  106. .filter(|p| !p.is_empty())
  107. .collect::<Vec<_>>();
  108. page.permalink = config.make_permalink(&page.path);
  109. Ok(page)
  110. }
  111. /// Read and parse a .md file into a Page struct
  112. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  113. let path = path.as_ref();
  114. let content = read_file(path)?;
  115. let mut page = Page::parse(path, &content, config)?;
  116. if page.file.name == "index" {
  117. let parent_dir = path.parent().unwrap();
  118. let assets = find_related_assets(parent_dir);
  119. if let Some(ref globset) = config.ignored_content_globset {
  120. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  121. // filtering only needs to work against the file_name component, not the full suffix. If
  122. // `find_related_assets` was changed to also return files in subdirectories, we could
  123. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  124. // against the remaining path. Note that the current behaviour effectively means that
  125. // the `ignored_content` setting in the config file is limited to single-file glob
  126. // patterns (no "**" patterns).
  127. page.assets = assets.into_iter()
  128. .filter(|path|
  129. match path.file_name() {
  130. None => true,
  131. Some(file) => !globset.is_match(file)
  132. }
  133. ).collect();
  134. } else {
  135. page.assets = assets;
  136. }
  137. } else {
  138. page.assets = vec![];
  139. }
  140. Ok(page)
  141. }
  142. /// We need access to all pages url to render links relative to content
  143. /// so that can't happen at the same time as parsing
  144. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config, anchor_insert: InsertAnchor) -> Result<()> {
  145. let context = Context::new(
  146. tera,
  147. config.highlight_code,
  148. config.highlight_theme.clone(),
  149. &self.permalink,
  150. permalinks,
  151. anchor_insert
  152. );
  153. let res = markdown_to_html(&self.raw_content, &context)?;
  154. self.content = res.0;
  155. self.toc = res.1;
  156. if self.raw_content.contains("<!-- more -->") {
  157. self.summary = Some({
  158. let summary = self.raw_content.splitn(2, "<!-- more -->").collect::<Vec<&str>>()[0];
  159. markdown_to_html(summary, &context)?.0
  160. })
  161. }
  162. Ok(())
  163. }
  164. /// Renders the page using the default layout, unless specified in front-matter
  165. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  166. let tpl_name = match self.meta.template {
  167. Some(ref l) => l.to_string(),
  168. None => "page.html".to_string()
  169. };
  170. let mut context = TeraContext::new();
  171. context.add("config", config);
  172. context.add("page", self);
  173. context.add("current_url", &self.permalink);
  174. context.add("current_path", &self.path);
  175. render_template(&tpl_name, tera, &context, config.theme.clone())
  176. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  177. }
  178. }
  179. impl Default for Page {
  180. fn default() -> Page {
  181. Page {
  182. file: FileInfo::default(),
  183. meta: PageFrontMatter::default(),
  184. raw_content: "".to_string(),
  185. assets: vec![],
  186. content: "".to_string(),
  187. slug: "".to_string(),
  188. path: "".to_string(),
  189. components: vec![],
  190. permalink: "".to_string(),
  191. summary: None,
  192. previous: None,
  193. next: None,
  194. toc: vec![],
  195. }
  196. }
  197. }
  198. impl ser::Serialize for Page {
  199. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  200. let mut state = serializer.serialize_struct("page", 18)?;
  201. state.serialize_field("content", &self.content)?;
  202. state.serialize_field("title", &self.meta.title)?;
  203. state.serialize_field("description", &self.meta.description)?;
  204. state.serialize_field("date", &self.meta.date)?;
  205. state.serialize_field("slug", &self.slug)?;
  206. state.serialize_field("path", &self.path)?;
  207. state.serialize_field("components", &self.components)?;
  208. state.serialize_field("permalink", &self.permalink)?;
  209. state.serialize_field("summary", &self.summary)?;
  210. state.serialize_field("tags", &self.meta.tags)?;
  211. state.serialize_field("category", &self.meta.category)?;
  212. state.serialize_field("extra", &self.meta.extra)?;
  213. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  214. state.serialize_field("word_count", &word_count)?;
  215. state.serialize_field("reading_time", &reading_time)?;
  216. state.serialize_field("previous", &self.previous)?;
  217. state.serialize_field("next", &self.next)?;
  218. state.serialize_field("toc", &self.toc)?;
  219. state.serialize_field("draft", &self.is_draft())?;
  220. state.end()
  221. }
  222. }
  223. #[cfg(test)]
  224. mod tests {
  225. use std::collections::HashMap;
  226. use std::io::Write;
  227. use std::fs::{File, create_dir};
  228. use std::path::Path;
  229. use tera::Tera;
  230. use tempdir::TempDir;
  231. use globset::{Glob, GlobSetBuilder};
  232. use config::Config;
  233. use super::Page;
  234. use front_matter::InsertAnchor;
  235. #[test]
  236. fn test_can_parse_a_valid_page() {
  237. let content = r#"
  238. +++
  239. title = "Hello"
  240. description = "hey there"
  241. slug = "hello-world"
  242. +++
  243. Hello world"#;
  244. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  245. assert!(res.is_ok());
  246. let mut page = res.unwrap();
  247. page.render_markdown(&HashMap::default(), &Tera::default(), &Config::default(), InsertAnchor::None).unwrap();
  248. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  249. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  250. assert_eq!(page.raw_content, "Hello world".to_string());
  251. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  252. }
  253. #[test]
  254. fn test_can_make_url_from_sections_and_slug() {
  255. let content = r#"
  256. +++
  257. slug = "hello-world"
  258. +++
  259. Hello world"#;
  260. let mut conf = Config::default();
  261. conf.base_url = "http://hello.com/".to_string();
  262. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  263. assert!(res.is_ok());
  264. let page = res.unwrap();
  265. assert_eq!(page.path, "posts/intro/hello-world/");
  266. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  267. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  268. }
  269. #[test]
  270. fn can_make_url_from_slug_only() {
  271. let content = r#"
  272. +++
  273. slug = "hello-world"
  274. +++
  275. Hello world"#;
  276. let config = Config::default();
  277. let res = Page::parse(Path::new("start.md"), content, &config);
  278. assert!(res.is_ok());
  279. let page = res.unwrap();
  280. assert_eq!(page.path, "hello-world/");
  281. assert_eq!(page.components, vec!["hello-world"]);
  282. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  283. }
  284. #[test]
  285. fn can_make_url_from_path() {
  286. let content = r#"
  287. +++
  288. path = "hello-world"
  289. +++
  290. Hello world"#;
  291. let config = Config::default();
  292. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  293. assert!(res.is_ok());
  294. let page = res.unwrap();
  295. assert_eq!(page.path, "hello-world/");
  296. assert_eq!(page.components, vec!["hello-world"]);
  297. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  298. }
  299. #[test]
  300. fn can_make_url_from_path_starting_slash() {
  301. let content = r#"
  302. +++
  303. path = "/hello-world"
  304. +++
  305. Hello world"#;
  306. let config = Config::default();
  307. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  308. assert!(res.is_ok());
  309. let page = res.unwrap();
  310. assert_eq!(page.path, "hello-world/");
  311. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  312. }
  313. #[test]
  314. fn errors_on_invalid_front_matter_format() {
  315. // missing starting +++
  316. let content = r#"
  317. title = "Hello"
  318. description = "hey there"
  319. slug = "hello-world"
  320. +++
  321. Hello world"#;
  322. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  323. assert!(res.is_err());
  324. }
  325. #[test]
  326. fn can_make_slug_from_non_slug_filename() {
  327. let config = Config::default();
  328. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  329. assert!(res.is_ok());
  330. let page = res.unwrap();
  331. assert_eq!(page.slug, "file-with-space");
  332. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  333. }
  334. #[test]
  335. fn can_specify_summary() {
  336. let config = Config::default();
  337. let content = r#"
  338. +++
  339. +++
  340. Hello world
  341. <!-- more -->"#.to_string();
  342. let res = Page::parse(Path::new("hello.md"), &content, &config);
  343. assert!(res.is_ok());
  344. let mut page = res.unwrap();
  345. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None).unwrap();
  346. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  347. }
  348. #[test]
  349. fn page_with_assets_gets_right_info() {
  350. let tmp_dir = TempDir::new("example").expect("create temp dir");
  351. let path = tmp_dir.path();
  352. create_dir(&path.join("content")).expect("create content temp dir");
  353. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  354. let nested_path = path.join("content").join("posts").join("with-assets");
  355. create_dir(&nested_path).expect("create nested temp dir");
  356. let mut f = File::create(nested_path.join("index.md")).unwrap();
  357. f.write_all(b"+++\n+++\n").unwrap();
  358. File::create(nested_path.join("example.js")).unwrap();
  359. File::create(nested_path.join("graph.jpg")).unwrap();
  360. File::create(nested_path.join("fail.png")).unwrap();
  361. let res = Page::from_file(
  362. nested_path.join("index.md").as_path(),
  363. &Config::default()
  364. );
  365. assert!(res.is_ok());
  366. let page = res.unwrap();
  367. assert_eq!(page.file.parent, path.join("content").join("posts"));
  368. assert_eq!(page.slug, "with-assets");
  369. assert_eq!(page.assets.len(), 3);
  370. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  371. }
  372. #[test]
  373. fn page_with_assets_and_slug_overrides_path() {
  374. let tmp_dir = TempDir::new("example").expect("create temp dir");
  375. let path = tmp_dir.path();
  376. create_dir(&path.join("content")).expect("create content temp dir");
  377. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  378. let nested_path = path.join("content").join("posts").join("with-assets");
  379. create_dir(&nested_path).expect("create nested temp dir");
  380. let mut f = File::create(nested_path.join("index.md")).unwrap();
  381. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  382. File::create(nested_path.join("example.js")).unwrap();
  383. File::create(nested_path.join("graph.jpg")).unwrap();
  384. File::create(nested_path.join("fail.png")).unwrap();
  385. let res = Page::from_file(
  386. nested_path.join("index.md").as_path(),
  387. &Config::default()
  388. );
  389. assert!(res.is_ok());
  390. let page = res.unwrap();
  391. assert_eq!(page.file.parent, path.join("content").join("posts"));
  392. assert_eq!(page.slug, "hey");
  393. assert_eq!(page.assets.len(), 3);
  394. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  395. }
  396. #[test]
  397. fn page_with_ignored_assets_filters_out_correct_files() {
  398. let tmp_dir = TempDir::new("example").expect("create temp dir");
  399. let path = tmp_dir.path();
  400. create_dir(&path.join("content")).expect("create content temp dir");
  401. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  402. let nested_path = path.join("content").join("posts").join("with-assets");
  403. create_dir(&nested_path).expect("create nested temp dir");
  404. let mut f = File::create(nested_path.join("index.md")).unwrap();
  405. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  406. File::create(nested_path.join("example.js")).unwrap();
  407. File::create(nested_path.join("graph.jpg")).unwrap();
  408. File::create(nested_path.join("fail.png")).unwrap();
  409. let mut gsb = GlobSetBuilder::new();
  410. gsb.add(Glob::new("*.{js,png}").unwrap());
  411. let mut config = Config::default();
  412. config.ignored_content_globset = Some(gsb.build().unwrap());
  413. let res = Page::from_file(
  414. nested_path.join("index.md").as_path(),
  415. &config
  416. );
  417. assert!(res.is_ok());
  418. let page = res.unwrap();
  419. assert_eq!(page.assets.len(), 1);
  420. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  421. }
  422. }