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