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.

543 lines
19KB

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