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.

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