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.

506 lines
18KB

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