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, base_path: &Path, anchor_insert: InsertAnchor) -> Result<()> {
  152. let mut context = RenderContext::new(
  153. tera,
  154. config,
  155. &self.permalink,
  156. permalinks,
  157. base_path,
  158. anchor_insert,
  159. );
  160. context.tera_context.add("page", self);
  161. let res = render_content(
  162. &self.raw_content.replacen("<!-- more -->", "<a name=\"continue-reading\"></a>", 1),
  163. &context,
  164. ).chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  165. self.content = res.0;
  166. self.toc = res.1;
  167. if self.raw_content.contains("<!-- more -->") {
  168. self.summary = Some({
  169. let summary = self.raw_content.splitn(2, "<!-- more -->").collect::<Vec<&str>>()[0];
  170. render_content(summary, &context)
  171. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?.0
  172. })
  173. }
  174. Ok(())
  175. }
  176. /// Renders the page using the default layout, unless specified in front-matter
  177. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  178. let tpl_name = match self.meta.template {
  179. Some(ref l) => l.to_string(),
  180. None => "page.html".to_string()
  181. };
  182. let mut context = TeraContext::new();
  183. context.add("config", config);
  184. context.add("page", self);
  185. context.add("current_url", &self.permalink);
  186. context.add("current_path", &self.path);
  187. render_template(&tpl_name, tera, &context, &config.theme)
  188. .chain_err(|| format!("Failed to render page '{}'", self.file.path.display()))
  189. }
  190. /// Creates a vectors of asset URLs.
  191. fn serialize_assets(&self) -> Vec<String> {
  192. self.assets.iter()
  193. .filter_map(|asset| asset.file_name())
  194. .filter_map(|filename| filename.to_str())
  195. .map(|filename| self.path.clone() + filename)
  196. .collect()
  197. }
  198. }
  199. impl Default for Page {
  200. fn default() -> Page {
  201. Page {
  202. file: FileInfo::default(),
  203. meta: PageFrontMatter::default(),
  204. raw_content: "".to_string(),
  205. assets: vec![],
  206. content: "".to_string(),
  207. slug: "".to_string(),
  208. path: "".to_string(),
  209. components: vec![],
  210. permalink: "".to_string(),
  211. summary: None,
  212. earlier: None,
  213. later: None,
  214. lighter: None,
  215. heavier: 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", 20)?;
  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("taxonomies", &self.meta.taxonomies)?;
  243. state.serialize_field("extra", &self.meta.extra)?;
  244. let (word_count, reading_time) = get_reading_analytics(&self.raw_content);
  245. state.serialize_field("word_count", &word_count)?;
  246. state.serialize_field("reading_time", &reading_time)?;
  247. state.serialize_field("earlier", &self.earlier)?;
  248. state.serialize_field("later", &self.later)?;
  249. state.serialize_field("lighter", &self.lighter)?;
  250. state.serialize_field("heavier", &self.heavier)?;
  251. state.serialize_field("toc", &self.toc)?;
  252. state.serialize_field("draft", &self.is_draft())?;
  253. let assets = self.serialize_assets();
  254. state.serialize_field("assets", &assets)?;
  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. }