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.

497 lines
17KB

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