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.

601 lines
21KB

  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 tera::{Tera, Context as TeraContext, Value, Map};
  5. use slug::slugify;
  6. use slotmap::{Key, DenseSlotMap};
  7. use errors::{Result, ResultExt};
  8. use config::Config;
  9. use utils::fs::{read_file, find_related_assets};
  10. use utils::site::get_reading_analytics;
  11. use utils::templates::render_template;
  12. use front_matter::{PageFrontMatter, InsertAnchor, split_page_content};
  13. use rendering::{RenderContext, Header, render_content};
  14. use library::Library;
  15. use content::file_info::FileInfo;
  16. /// What we are sending to the templates when rendering them
  17. #[derive(Clone, Debug, PartialEq, Serialize)]
  18. pub struct SerializingPage<'a> {
  19. content: &'a str,
  20. permalink: &'a str,
  21. slug: &'a str,
  22. title: &'a Option<String>,
  23. description: &'a Option<String>,
  24. date: &'a Option<String>,
  25. year: Option<i32>,
  26. month: Option<u32>,
  27. day: Option<u32>,
  28. taxonomies: &'a HashMap<String, Vec<String>>,
  29. extra: &'a Map<String, Value>,
  30. path: &'a str,
  31. components: &'a [String],
  32. summary: &'a Option<String>,
  33. word_count: Option<usize>,
  34. reading_time: Option<usize>,
  35. toc: &'a [Header],
  36. assets: Vec<String>,
  37. draft: bool,
  38. lighter: Option<Box<SerializingPage<'a>>>,
  39. heavier: Option<Box<SerializingPage<'a>>>,
  40. earlier: Option<Box<SerializingPage<'a>>>,
  41. later: Option<Box<SerializingPage<'a>>>,
  42. }
  43. impl<'a> SerializingPage<'a> {
  44. /// Grabs all the data from a page, including sibling pages
  45. pub fn from_page(page: &'a Page, pages: &'a DenseSlotMap<Page>) -> Self {
  46. let mut year = None;
  47. let mut month = None;
  48. let mut day = None;
  49. if let Some(d) = page.meta.datetime_tuple {
  50. year = Some(d.0);
  51. month = Some(d.1);
  52. day = Some(d.2);
  53. }
  54. let lighter = page.lighter.map(|k| Box::new(SerializingPage::from_page_basic(pages.get(k).unwrap())));
  55. let heavier = page.heavier.map(|k| Box::new(SerializingPage::from_page_basic(pages.get(k).unwrap())));
  56. let earlier = page.earlier.map(|k| Box::new(SerializingPage::from_page_basic(pages.get(k).unwrap())));
  57. let later = page.later.map(|k| Box::new(SerializingPage::from_page_basic(pages.get(k).unwrap())));
  58. SerializingPage {
  59. content: &page.content,
  60. permalink: &page.permalink,
  61. slug: &page.slug,
  62. title: &page.meta.title,
  63. description: &page.meta.description,
  64. extra: &page.meta.extra,
  65. date: &page.meta.date,
  66. year,
  67. month,
  68. day,
  69. taxonomies: &page.meta.taxonomies,
  70. path: &page.path,
  71. components: &page.components,
  72. summary: &page.summary,
  73. word_count: page.word_count,
  74. reading_time: page.reading_time,
  75. toc: &page.toc,
  76. assets: page.serialize_assets(),
  77. draft: page.is_draft(),
  78. lighter,
  79. heavier,
  80. earlier,
  81. later,
  82. }
  83. }
  84. /// Same as from_page but does not fill sibling pages
  85. pub fn from_page_basic(page: &'a Page) -> Self {
  86. let mut year = None;
  87. let mut month = None;
  88. let mut day = None;
  89. if let Some(d) = page.meta.datetime_tuple {
  90. year = Some(d.0);
  91. month = Some(d.1);
  92. day = Some(d.2);
  93. }
  94. SerializingPage {
  95. content: &page.content,
  96. permalink: &page.permalink,
  97. slug: &page.slug,
  98. title: &page.meta.title,
  99. description: &page.meta.description,
  100. extra: &page.meta.extra,
  101. date: &page.meta.date,
  102. year,
  103. month,
  104. day,
  105. taxonomies: &page.meta.taxonomies,
  106. path: &page.path,
  107. components: &page.components,
  108. summary: &page.summary,
  109. word_count: page.word_count,
  110. reading_time: page.reading_time,
  111. toc: &page.toc,
  112. assets: page.serialize_assets(),
  113. draft: page.is_draft(),
  114. lighter: None,
  115. heavier: None,
  116. earlier: None,
  117. later: None,
  118. }
  119. }
  120. }
  121. #[derive(Clone, Debug, PartialEq)]
  122. pub struct Page {
  123. /// All info about the actual file
  124. pub file: FileInfo,
  125. /// The front matter meta-data
  126. pub meta: PageFrontMatter,
  127. /// The actual content of the page, in markdown
  128. pub raw_content: String,
  129. /// All the non-md files we found next to the .md file
  130. pub assets: Vec<PathBuf>,
  131. /// The HTML rendered of the page
  132. pub content: String,
  133. /// The slug of that page.
  134. /// First tries to find the slug in the meta and defaults to filename otherwise
  135. pub slug: String,
  136. /// The URL path of the page
  137. pub path: String,
  138. /// The components of the path of the page
  139. pub components: Vec<String>,
  140. /// The full URL for that page
  141. pub permalink: String,
  142. /// The summary for the article, defaults to None
  143. /// When <!-- more --> is found in the text, will take the content up to that part
  144. /// as summary
  145. pub summary: Option<String>,
  146. /// The earlier page, for pages sorted by date
  147. pub earlier: Option<Key>,
  148. /// The later page, for pages sorted by date
  149. pub later: Option<Key>,
  150. /// The lighter page, for pages sorted by weight
  151. pub lighter: Option<Key>,
  152. /// The heavier page, for pages sorted by weight
  153. pub heavier: Option<Key>,
  154. /// Toc made from the headers of the markdown file
  155. pub toc: Vec<Header>,
  156. /// How many words in the raw content
  157. pub word_count: Option<usize>,
  158. /// How long would it take to read the raw content.
  159. /// See `get_reading_analytics` on how it is calculated
  160. pub reading_time: Option<usize>,
  161. }
  162. impl Page {
  163. pub fn new<P: AsRef<Path>>(file_path: P, meta: PageFrontMatter) -> Page {
  164. let file_path = file_path.as_ref();
  165. Page {
  166. file: FileInfo::new_page(file_path),
  167. meta,
  168. raw_content: "".to_string(),
  169. assets: vec![],
  170. content: "".to_string(),
  171. slug: "".to_string(),
  172. path: "".to_string(),
  173. components: vec![],
  174. permalink: "".to_string(),
  175. summary: None,
  176. earlier: None,
  177. later: None,
  178. lighter: None,
  179. heavier: None,
  180. toc: vec![],
  181. word_count: None,
  182. reading_time: None,
  183. }
  184. }
  185. pub fn is_draft(&self) -> bool {
  186. self.meta.draft
  187. }
  188. /// Parse a page given the content of the .md file
  189. /// Files without front matter or with invalid front matter are considered
  190. /// erroneous
  191. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Page> {
  192. let (meta, content) = split_page_content(file_path, content)?;
  193. let mut page = Page::new(file_path, meta);
  194. page.raw_content = content;
  195. let (word_count, reading_time) = get_reading_analytics(&page.raw_content);
  196. page.word_count = Some(word_count);
  197. page.reading_time = Some(reading_time);
  198. page.slug = {
  199. if let Some(ref slug) = page.meta.slug {
  200. slug.trim().to_string()
  201. } else if page.file.name == "index" {
  202. if let Some(parent) = page.file.path.parent() {
  203. slugify(parent.file_name().unwrap().to_str().unwrap())
  204. } else {
  205. slugify(page.file.name.clone())
  206. }
  207. } else {
  208. slugify(page.file.name.clone())
  209. }
  210. };
  211. if let Some(ref p) = page.meta.path {
  212. page.path = p.trim().trim_left_matches('/').to_string();
  213. } else {
  214. page.path = if page.file.components.is_empty() {
  215. page.slug.clone()
  216. } else {
  217. format!("{}/{}", page.file.components.join("/"), page.slug)
  218. };
  219. }
  220. if !page.path.ends_with('/') {
  221. page.path = format!("{}/", page.path);
  222. }
  223. page.components = page.path.split('/')
  224. .map(|p| p.to_string())
  225. .filter(|p| !p.is_empty())
  226. .collect::<Vec<_>>();
  227. page.permalink = config.make_permalink(&page.path);
  228. Ok(page)
  229. }
  230. /// Read and parse a .md file into a Page struct
  231. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Page> {
  232. let path = path.as_ref();
  233. let content = read_file(path)?;
  234. let mut page = Page::parse(path, &content, config)?;
  235. if page.file.name == "index" {
  236. let parent_dir = path.parent().unwrap();
  237. let assets = find_related_assets(parent_dir);
  238. if let Some(ref globset) = config.ignored_content_globset {
  239. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  240. // filtering only needs to work against the file_name component, not the full suffix. If
  241. // `find_related_assets` was changed to also return files in subdirectories, we could
  242. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  243. // against the remaining path. Note that the current behaviour effectively means that
  244. // the `ignored_content` setting in the config file is limited to single-file glob
  245. // patterns (no "**" patterns).
  246. page.assets = assets.into_iter()
  247. .filter(|path|
  248. match path.file_name() {
  249. None => true,
  250. Some(file) => !globset.is_match(file)
  251. }
  252. ).collect();
  253. } else {
  254. page.assets = assets;
  255. }
  256. } else {
  257. page.assets = vec![];
  258. }
  259. Ok(page)
  260. }
  261. /// We need access to all pages url to render links relative to content
  262. /// so that can't happen at the same time as parsing
  263. pub fn render_markdown(
  264. &mut self,
  265. permalinks: &HashMap<String, String>,
  266. tera: &Tera,
  267. config: &Config,
  268. anchor_insert: InsertAnchor,
  269. ) -> Result<()> {
  270. let mut context = RenderContext::new(
  271. tera,
  272. config,
  273. &self.permalink,
  274. permalinks,
  275. anchor_insert,
  276. );
  277. context.tera_context.insert("page", &SerializingPage::from_page_basic(self));
  278. let res = render_content(&self.raw_content, &context)
  279. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  280. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  281. self.content = res.body;
  282. self.toc = res.toc;
  283. Ok(())
  284. }
  285. /// Renders the page using the default layout, unless specified in front-matter
  286. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  287. let tpl_name = match self.meta.template {
  288. Some(ref l) => l.to_string(),
  289. None => "page.html".to_string()
  290. };
  291. let mut context = TeraContext::new();
  292. context.insert("config", config);
  293. context.insert("current_url", &self.permalink);
  294. context.insert("current_path", &self.path);
  295. context.insert("page", &self.to_serialized(library.pages()));
  296. render_template(&tpl_name, tera, &context, &config.theme)
  297. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  298. }
  299. /// Creates a vectors of asset URLs.
  300. fn serialize_assets(&self) -> Vec<String> {
  301. self.assets.iter()
  302. .filter_map(|asset| asset.file_name())
  303. .filter_map(|filename| filename.to_str())
  304. .map(|filename| self.path.clone() + filename)
  305. .collect()
  306. }
  307. pub fn to_serialized<'a>(&'a self, pages: &'a DenseSlotMap<Page>) -> SerializingPage<'a> {
  308. SerializingPage::from_page(self, pages)
  309. }
  310. pub fn to_serialized_basic(&self) -> SerializingPage {
  311. SerializingPage::from_page_basic(self)
  312. }
  313. }
  314. impl Default for Page {
  315. fn default() -> Page {
  316. Page {
  317. file: FileInfo::default(),
  318. meta: PageFrontMatter::default(),
  319. raw_content: "".to_string(),
  320. assets: vec![],
  321. content: "".to_string(),
  322. slug: "".to_string(),
  323. path: "".to_string(),
  324. components: vec![],
  325. permalink: "".to_string(),
  326. summary: None,
  327. earlier: None,
  328. later: None,
  329. lighter: None,
  330. heavier: None,
  331. toc: vec![],
  332. word_count: None,
  333. reading_time: None,
  334. }
  335. }
  336. }
  337. #[cfg(test)]
  338. mod tests {
  339. use std::collections::HashMap;
  340. use std::io::Write;
  341. use std::fs::{File, create_dir};
  342. use std::path::Path;
  343. use tera::Tera;
  344. use tempfile::tempdir;
  345. use globset::{Glob, GlobSetBuilder};
  346. use config::Config;
  347. use super::Page;
  348. use front_matter::InsertAnchor;
  349. #[test]
  350. fn test_can_parse_a_valid_page() {
  351. let content = r#"
  352. +++
  353. title = "Hello"
  354. description = "hey there"
  355. slug = "hello-world"
  356. +++
  357. Hello world"#;
  358. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  359. assert!(res.is_ok());
  360. let mut page = res.unwrap();
  361. page.render_markdown(
  362. &HashMap::default(),
  363. &Tera::default(),
  364. &Config::default(),
  365. InsertAnchor::None,
  366. ).unwrap();
  367. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  368. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  369. assert_eq!(page.raw_content, "Hello world".to_string());
  370. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  371. }
  372. #[test]
  373. fn test_can_make_url_from_sections_and_slug() {
  374. let content = r#"
  375. +++
  376. slug = "hello-world"
  377. +++
  378. Hello world"#;
  379. let mut conf = Config::default();
  380. conf.base_url = "http://hello.com/".to_string();
  381. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  382. assert!(res.is_ok());
  383. let page = res.unwrap();
  384. assert_eq!(page.path, "posts/intro/hello-world/");
  385. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  386. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  387. }
  388. #[test]
  389. fn can_make_url_from_slug_only() {
  390. let content = r#"
  391. +++
  392. slug = "hello-world"
  393. +++
  394. Hello world"#;
  395. let config = Config::default();
  396. let res = Page::parse(Path::new("start.md"), content, &config);
  397. assert!(res.is_ok());
  398. let page = res.unwrap();
  399. assert_eq!(page.path, "hello-world/");
  400. assert_eq!(page.components, vec!["hello-world"]);
  401. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  402. }
  403. #[test]
  404. fn can_make_url_from_path() {
  405. let content = r#"
  406. +++
  407. path = "hello-world"
  408. +++
  409. Hello world"#;
  410. let config = Config::default();
  411. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  412. assert!(res.is_ok());
  413. let page = res.unwrap();
  414. assert_eq!(page.path, "hello-world/");
  415. assert_eq!(page.components, vec!["hello-world"]);
  416. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  417. }
  418. #[test]
  419. fn can_make_url_from_path_starting_slash() {
  420. let content = r#"
  421. +++
  422. path = "/hello-world"
  423. +++
  424. Hello world"#;
  425. let config = Config::default();
  426. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  427. assert!(res.is_ok());
  428. let page = res.unwrap();
  429. assert_eq!(page.path, "hello-world/");
  430. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  431. }
  432. #[test]
  433. fn errors_on_invalid_front_matter_format() {
  434. // missing starting +++
  435. let content = r#"
  436. title = "Hello"
  437. description = "hey there"
  438. slug = "hello-world"
  439. +++
  440. Hello world"#;
  441. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  442. assert!(res.is_err());
  443. }
  444. #[test]
  445. fn can_make_slug_from_non_slug_filename() {
  446. let config = Config::default();
  447. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  448. assert!(res.is_ok());
  449. let page = res.unwrap();
  450. assert_eq!(page.slug, "file-with-space");
  451. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  452. }
  453. #[test]
  454. fn can_specify_summary() {
  455. let config = Config::default();
  456. let content = r#"
  457. +++
  458. +++
  459. Hello world
  460. <!-- more -->"#.to_string();
  461. let res = Page::parse(Path::new("hello.md"), &content, &config);
  462. assert!(res.is_ok());
  463. let mut page = res.unwrap();
  464. page.render_markdown(
  465. &HashMap::default(),
  466. &Tera::default(),
  467. &config,
  468. InsertAnchor::None,
  469. ).unwrap();
  470. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  471. }
  472. #[test]
  473. fn page_with_assets_gets_right_info() {
  474. let tmp_dir = tempdir().expect("create temp dir");
  475. let path = tmp_dir.path();
  476. create_dir(&path.join("content")).expect("create content temp dir");
  477. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  478. let nested_path = path.join("content").join("posts").join("with-assets");
  479. create_dir(&nested_path).expect("create nested temp dir");
  480. let mut f = File::create(nested_path.join("index.md")).unwrap();
  481. f.write_all(b"+++\n+++\n").unwrap();
  482. File::create(nested_path.join("example.js")).unwrap();
  483. File::create(nested_path.join("graph.jpg")).unwrap();
  484. File::create(nested_path.join("fail.png")).unwrap();
  485. let res = Page::from_file(
  486. nested_path.join("index.md").as_path(),
  487. &Config::default(),
  488. );
  489. assert!(res.is_ok());
  490. let page = res.unwrap();
  491. assert_eq!(page.file.parent, path.join("content").join("posts"));
  492. assert_eq!(page.slug, "with-assets");
  493. assert_eq!(page.assets.len(), 3);
  494. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  495. }
  496. #[test]
  497. fn page_with_assets_and_slug_overrides_path() {
  498. let tmp_dir = tempdir().expect("create temp dir");
  499. let path = tmp_dir.path();
  500. create_dir(&path.join("content")).expect("create content temp dir");
  501. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  502. let nested_path = path.join("content").join("posts").join("with-assets");
  503. create_dir(&nested_path).expect("create nested temp dir");
  504. let mut f = File::create(nested_path.join("index.md")).unwrap();
  505. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  506. File::create(nested_path.join("example.js")).unwrap();
  507. File::create(nested_path.join("graph.jpg")).unwrap();
  508. File::create(nested_path.join("fail.png")).unwrap();
  509. let res = Page::from_file(
  510. nested_path.join("index.md").as_path(),
  511. &Config::default(),
  512. );
  513. assert!(res.is_ok());
  514. let page = res.unwrap();
  515. assert_eq!(page.file.parent, path.join("content").join("posts"));
  516. assert_eq!(page.slug, "hey");
  517. assert_eq!(page.assets.len(), 3);
  518. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  519. }
  520. #[test]
  521. fn page_with_ignored_assets_filters_out_correct_files() {
  522. let tmp_dir = tempdir().expect("create temp dir");
  523. let path = tmp_dir.path();
  524. create_dir(&path.join("content")).expect("create content temp dir");
  525. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  526. let nested_path = path.join("content").join("posts").join("with-assets");
  527. create_dir(&nested_path).expect("create nested temp dir");
  528. let mut f = File::create(nested_path.join("index.md")).unwrap();
  529. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  530. File::create(nested_path.join("example.js")).unwrap();
  531. File::create(nested_path.join("graph.jpg")).unwrap();
  532. File::create(nested_path.join("fail.png")).unwrap();
  533. let mut gsb = GlobSetBuilder::new();
  534. gsb.add(Glob::new("*.{js,png}").unwrap());
  535. let mut config = Config::default();
  536. config.ignored_content_globset = Some(gsb.build().unwrap());
  537. let res = Page::from_file(
  538. nested_path.join("index.md").as_path(),
  539. &config,
  540. );
  541. assert!(res.is_ok());
  542. let page = res.unwrap();
  543. assert_eq!(page.assets.len(), 1);
  544. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  545. }
  546. }