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.

605 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. #[derive(Clone, Debug, PartialEq, Serialize)]
  17. pub struct SerializingPage<'a> {
  18. content: &'a str,
  19. permalink: &'a str,
  20. slug: &'a str,
  21. title: &'a Option<String>,
  22. description: &'a Option<String>,
  23. date: &'a Option<String>,
  24. year: Option<i32>,
  25. month: Option<u32>,
  26. day: Option<u32>,
  27. taxonomies: &'a HashMap<String, Vec<String>>,
  28. extra: &'a Map<String, Value>,
  29. path: &'a str,
  30. components: &'a [String],
  31. summary: &'a Option<String>,
  32. word_count: Option<usize>,
  33. reading_time: Option<usize>,
  34. toc: &'a [Header],
  35. assets: Vec<String>,
  36. draft: bool,
  37. lighter: Option<Box<SerializingPage<'a>>>,
  38. heavier: Option<Box<SerializingPage<'a>>>,
  39. earlier: Option<Box<SerializingPage<'a>>>,
  40. later: Option<Box<SerializingPage<'a>>>,
  41. }
  42. impl<'a> SerializingPage<'a> {
  43. // We only want to fill one level of prev/next, otherwise it is going to overflow.
  44. // `stop` is there for that
  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. base_path: &Path,
  269. anchor_insert: InsertAnchor,
  270. ) -> Result<()> {
  271. let mut context = RenderContext::new(
  272. tera,
  273. config,
  274. &self.permalink,
  275. permalinks,
  276. base_path,
  277. anchor_insert,
  278. );
  279. context.tera_context.insert("page", &SerializingPage::from_page_basic(self));
  280. let res = render_content(&self.raw_content, &context)
  281. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  282. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  283. self.content = res.body;
  284. self.toc = res.toc;
  285. Ok(())
  286. }
  287. /// Renders the page using the default layout, unless specified in front-matter
  288. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  289. let tpl_name = match self.meta.template {
  290. Some(ref l) => l.to_string(),
  291. None => "page.html".to_string()
  292. };
  293. let mut context = TeraContext::new();
  294. context.insert("config", config);
  295. context.insert("page", &library.get_cached_page_value(&self.file.path));
  296. context.insert("current_url", &self.permalink);
  297. context.insert("current_path", &self.path);
  298. render_template(&tpl_name, tera, &context, &config.theme)
  299. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  300. }
  301. /// Creates a vectors of asset URLs.
  302. fn serialize_assets(&self) -> Vec<String> {
  303. self.assets.iter()
  304. .filter_map(|asset| asset.file_name())
  305. .filter_map(|filename| filename.to_str())
  306. .map(|filename| self.path.clone() + filename)
  307. .collect()
  308. }
  309. pub fn to_serialized<'a>(&'a self, pages: &'a DenseSlotMap<Page>) -> SerializingPage<'a> {
  310. SerializingPage::from_page(self, pages)
  311. }
  312. pub fn to_serialized_basic<'a>(&'a self) -> SerializingPage<'a> {
  313. SerializingPage::from_page_basic(self)
  314. }
  315. }
  316. impl Default for Page {
  317. fn default() -> Page {
  318. Page {
  319. file: FileInfo::default(),
  320. meta: PageFrontMatter::default(),
  321. raw_content: "".to_string(),
  322. assets: vec![],
  323. content: "".to_string(),
  324. slug: "".to_string(),
  325. path: "".to_string(),
  326. components: vec![],
  327. permalink: "".to_string(),
  328. summary: None,
  329. earlier: None,
  330. later: None,
  331. lighter: None,
  332. heavier: None,
  333. toc: vec![],
  334. word_count: None,
  335. reading_time: None,
  336. }
  337. }
  338. }
  339. #[cfg(test)]
  340. mod tests {
  341. use std::collections::HashMap;
  342. use std::io::Write;
  343. use std::fs::{File, create_dir};
  344. use std::path::Path;
  345. use tera::Tera;
  346. use tempfile::tempdir;
  347. use globset::{Glob, GlobSetBuilder};
  348. use config::Config;
  349. use super::Page;
  350. use front_matter::InsertAnchor;
  351. #[test]
  352. fn test_can_parse_a_valid_page() {
  353. let content = r#"
  354. +++
  355. title = "Hello"
  356. description = "hey there"
  357. slug = "hello-world"
  358. +++
  359. Hello world"#;
  360. let res = Page::parse(Path::new("post.md"), content, &Config::default());
  361. assert!(res.is_ok());
  362. let mut page = res.unwrap();
  363. page.render_markdown(
  364. &HashMap::default(),
  365. &Tera::default(),
  366. &Config::default(),
  367. Path::new("something"),
  368. InsertAnchor::None,
  369. ).unwrap();
  370. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  371. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  372. assert_eq!(page.raw_content, "Hello world".to_string());
  373. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  374. }
  375. #[test]
  376. fn test_can_make_url_from_sections_and_slug() {
  377. let content = r#"
  378. +++
  379. slug = "hello-world"
  380. +++
  381. Hello world"#;
  382. let mut conf = Config::default();
  383. conf.base_url = "http://hello.com/".to_string();
  384. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &conf);
  385. assert!(res.is_ok());
  386. let page = res.unwrap();
  387. assert_eq!(page.path, "posts/intro/hello-world/");
  388. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  389. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  390. }
  391. #[test]
  392. fn can_make_url_from_slug_only() {
  393. let content = r#"
  394. +++
  395. slug = "hello-world"
  396. +++
  397. Hello world"#;
  398. let config = Config::default();
  399. let res = Page::parse(Path::new("start.md"), content, &config);
  400. assert!(res.is_ok());
  401. let page = res.unwrap();
  402. assert_eq!(page.path, "hello-world/");
  403. assert_eq!(page.components, vec!["hello-world"]);
  404. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  405. }
  406. #[test]
  407. fn can_make_url_from_path() {
  408. let content = r#"
  409. +++
  410. path = "hello-world"
  411. +++
  412. Hello world"#;
  413. let config = Config::default();
  414. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  415. assert!(res.is_ok());
  416. let page = res.unwrap();
  417. assert_eq!(page.path, "hello-world/");
  418. assert_eq!(page.components, vec!["hello-world"]);
  419. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  420. }
  421. #[test]
  422. fn can_make_url_from_path_starting_slash() {
  423. let content = r#"
  424. +++
  425. path = "/hello-world"
  426. +++
  427. Hello world"#;
  428. let config = Config::default();
  429. let res = Page::parse(Path::new("content/posts/intro/start.md"), content, &config);
  430. assert!(res.is_ok());
  431. let page = res.unwrap();
  432. assert_eq!(page.path, "hello-world/");
  433. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  434. }
  435. #[test]
  436. fn errors_on_invalid_front_matter_format() {
  437. // missing starting +++
  438. let content = r#"
  439. title = "Hello"
  440. description = "hey there"
  441. slug = "hello-world"
  442. +++
  443. Hello world"#;
  444. let res = Page::parse(Path::new("start.md"), content, &Config::default());
  445. assert!(res.is_err());
  446. }
  447. #[test]
  448. fn can_make_slug_from_non_slug_filename() {
  449. let config = Config::default();
  450. let res = Page::parse(Path::new(" file with space.md"), "+++\n+++", &config);
  451. assert!(res.is_ok());
  452. let page = res.unwrap();
  453. assert_eq!(page.slug, "file-with-space");
  454. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  455. }
  456. #[test]
  457. fn can_specify_summary() {
  458. let config = Config::default();
  459. let content = r#"
  460. +++
  461. +++
  462. Hello world
  463. <!-- more -->"#.to_string();
  464. let res = Page::parse(Path::new("hello.md"), &content, &config);
  465. assert!(res.is_ok());
  466. let mut page = res.unwrap();
  467. page.render_markdown(
  468. &HashMap::default(),
  469. &Tera::default(),
  470. &config,
  471. Path::new("something"),
  472. InsertAnchor::None,
  473. ).unwrap();
  474. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  475. }
  476. #[test]
  477. fn page_with_assets_gets_right_info() {
  478. let tmp_dir = tempdir().expect("create temp dir");
  479. let path = tmp_dir.path();
  480. create_dir(&path.join("content")).expect("create content temp dir");
  481. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  482. let nested_path = path.join("content").join("posts").join("with-assets");
  483. create_dir(&nested_path).expect("create nested temp dir");
  484. let mut f = File::create(nested_path.join("index.md")).unwrap();
  485. f.write_all(b"+++\n+++\n").unwrap();
  486. File::create(nested_path.join("example.js")).unwrap();
  487. File::create(nested_path.join("graph.jpg")).unwrap();
  488. File::create(nested_path.join("fail.png")).unwrap();
  489. let res = Page::from_file(
  490. nested_path.join("index.md").as_path(),
  491. &Config::default(),
  492. );
  493. assert!(res.is_ok());
  494. let page = res.unwrap();
  495. assert_eq!(page.file.parent, path.join("content").join("posts"));
  496. assert_eq!(page.slug, "with-assets");
  497. assert_eq!(page.assets.len(), 3);
  498. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  499. }
  500. #[test]
  501. fn page_with_assets_and_slug_overrides_path() {
  502. let tmp_dir = tempdir().expect("create temp dir");
  503. let path = tmp_dir.path();
  504. create_dir(&path.join("content")).expect("create content temp dir");
  505. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  506. let nested_path = path.join("content").join("posts").join("with-assets");
  507. create_dir(&nested_path).expect("create nested temp dir");
  508. let mut f = File::create(nested_path.join("index.md")).unwrap();
  509. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  510. File::create(nested_path.join("example.js")).unwrap();
  511. File::create(nested_path.join("graph.jpg")).unwrap();
  512. File::create(nested_path.join("fail.png")).unwrap();
  513. let res = Page::from_file(
  514. nested_path.join("index.md").as_path(),
  515. &Config::default(),
  516. );
  517. assert!(res.is_ok());
  518. let page = res.unwrap();
  519. assert_eq!(page.file.parent, path.join("content").join("posts"));
  520. assert_eq!(page.slug, "hey");
  521. assert_eq!(page.assets.len(), 3);
  522. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  523. }
  524. #[test]
  525. fn page_with_ignored_assets_filters_out_correct_files() {
  526. let tmp_dir = tempdir().expect("create temp dir");
  527. let path = tmp_dir.path();
  528. create_dir(&path.join("content")).expect("create content temp dir");
  529. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  530. let nested_path = path.join("content").join("posts").join("with-assets");
  531. create_dir(&nested_path).expect("create nested temp dir");
  532. let mut f = File::create(nested_path.join("index.md")).unwrap();
  533. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  534. File::create(nested_path.join("example.js")).unwrap();
  535. File::create(nested_path.join("graph.jpg")).unwrap();
  536. File::create(nested_path.join("fail.png")).unwrap();
  537. let mut gsb = GlobSetBuilder::new();
  538. gsb.add(Glob::new("*.{js,png}").unwrap());
  539. let mut config = Config::default();
  540. config.ignored_content_globset = Some(gsb.build().unwrap());
  541. let res = Page::from_file(
  542. nested_path.join("index.md").as_path(),
  543. &config,
  544. );
  545. assert!(res.is_ok());
  546. let page = res.unwrap();
  547. assert_eq!(page.assets.len(), 1);
  548. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  549. }
  550. }