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.

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