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.

763 lines
27KB

  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 regex::Regex;
  5. use slotmap::Key;
  6. use slug::slugify;
  7. use tera::{Context as TeraContext, Tera};
  8. use config::Config;
  9. use errors::{Error, Result};
  10. use front_matter::{split_page_content, InsertAnchor, PageFrontMatter};
  11. use library::Library;
  12. use rendering::{render_content, Header, RenderContext};
  13. use utils::fs::{find_related_assets, read_file};
  14. use utils::site::get_reading_analytics;
  15. use utils::templates::render_template;
  16. use content::file_info::FileInfo;
  17. use content::ser::SerializingPage;
  18. lazy_static! {
  19. // Based on https://regex101.com/r/H2n38Z/1/tests
  20. // A regex parsing RFC3339 date followed by {_,-}, some characters and ended by .md
  21. static ref RFC3339_DATE: Regex = Regex::new(
  22. r"^(?P<datetime>(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])(T([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(Z|(\+|-)([01][0-9]|2[0-3]):([0-5][0-9])))?)(_|-)(?P<slug>.+$)"
  23. ).unwrap();
  24. }
  25. #[derive(Clone, Debug, PartialEq)]
  26. pub struct Page {
  27. /// All info about the actual file
  28. pub file: FileInfo,
  29. /// The front matter meta-data
  30. pub meta: PageFrontMatter,
  31. /// The list of parent sections
  32. pub ancestors: Vec<Key>,
  33. /// The actual content of the page, in markdown
  34. pub raw_content: String,
  35. /// All the non-md files we found next to the .md file
  36. pub assets: Vec<PathBuf>,
  37. /// All the non-md files we found next to the .md file as string for use in templates
  38. pub serialized_assets: Vec<String>,
  39. /// The HTML rendered of the page
  40. pub content: String,
  41. /// The slug of that page.
  42. /// First tries to find the slug in the meta and defaults to filename otherwise
  43. pub slug: String,
  44. /// The URL path of the page
  45. pub path: String,
  46. /// The components of the path of the page
  47. pub components: Vec<String>,
  48. /// The full URL for that page
  49. pub permalink: String,
  50. /// The summary for the article, defaults to None
  51. /// When <!-- more --> is found in the text, will take the content up to that part
  52. /// as summary
  53. pub summary: Option<String>,
  54. /// The earlier page, for pages sorted by date
  55. pub earlier: Option<Key>,
  56. /// The later page, for pages sorted by date
  57. pub later: Option<Key>,
  58. /// The lighter page, for pages sorted by weight
  59. pub lighter: Option<Key>,
  60. /// The heavier page, for pages sorted by weight
  61. pub heavier: Option<Key>,
  62. /// Toc made from the headers of the markdown file
  63. pub toc: Vec<Header>,
  64. /// How many words in the raw content
  65. pub word_count: Option<usize>,
  66. /// How long would it take to read the raw content.
  67. /// See `get_reading_analytics` on how it is calculated
  68. pub reading_time: Option<usize>,
  69. /// The language of that page. Equal to the default lang if the user doesn't setup `languages` in config.
  70. /// Corresponds to the lang in the {slug}.{lang}.md file scheme
  71. pub lang: String,
  72. /// Contains all the translated version of that page
  73. pub translations: Vec<Key>,
  74. /// Contains the external links that need to be checked
  75. pub external_links: Vec<String>,
  76. }
  77. impl Page {
  78. pub fn new<P: AsRef<Path>>(file_path: P, meta: PageFrontMatter, base_path: &PathBuf) -> Page {
  79. let file_path = file_path.as_ref();
  80. Page {
  81. file: FileInfo::new_page(file_path, base_path),
  82. meta,
  83. ancestors: vec![],
  84. raw_content: "".to_string(),
  85. assets: vec![],
  86. serialized_assets: vec![],
  87. content: "".to_string(),
  88. slug: "".to_string(),
  89. path: "".to_string(),
  90. components: vec![],
  91. permalink: "".to_string(),
  92. summary: None,
  93. earlier: None,
  94. later: None,
  95. lighter: None,
  96. heavier: None,
  97. toc: vec![],
  98. word_count: None,
  99. reading_time: None,
  100. lang: String::new(),
  101. translations: Vec::new(),
  102. external_links: Vec::new(),
  103. }
  104. }
  105. pub fn is_draft(&self) -> bool {
  106. self.meta.draft
  107. }
  108. /// Parse a page given the content of the .md file
  109. /// Files without front matter or with invalid front matter are considered
  110. /// erroneous
  111. pub fn parse(
  112. file_path: &Path,
  113. content: &str,
  114. config: &Config,
  115. base_path: &PathBuf,
  116. ) -> Result<Page> {
  117. let (meta, content) = split_page_content(file_path, content)?;
  118. let mut page = Page::new(file_path, meta, base_path);
  119. page.lang = page.file.find_language(config)?;
  120. page.raw_content = content;
  121. let (word_count, reading_time) = get_reading_analytics(&page.raw_content);
  122. page.word_count = Some(word_count);
  123. page.reading_time = Some(reading_time);
  124. let mut slug_from_dated_filename = None;
  125. let file_path = if page.file.name == "index" {
  126. if let Some(parent) = page.file.path.parent() {
  127. parent.file_name().unwrap().to_str().unwrap().to_string()
  128. } else {
  129. page.file.name.replace(".md", "")
  130. }
  131. } else {
  132. page.file.name.replace(".md", "")
  133. };
  134. if let Some(ref caps) = RFC3339_DATE.captures(&file_path) {
  135. slug_from_dated_filename = Some(caps.name("slug").unwrap().as_str().to_string());
  136. if page.meta.date.is_none() {
  137. page.meta.date = Some(caps.name("datetime").unwrap().as_str().to_string());
  138. page.meta.date_to_datetime();
  139. }
  140. }
  141. page.slug = {
  142. if let Some(ref slug) = page.meta.slug {
  143. slug.trim().to_string()
  144. } else if page.file.name == "index" {
  145. if let Some(parent) = page.file.path.parent() {
  146. if let Some(slug) = slug_from_dated_filename {
  147. slugify(&slug)
  148. } else {
  149. slugify(parent.file_name().unwrap().to_str().unwrap())
  150. }
  151. } else {
  152. slugify(&page.file.name)
  153. }
  154. } else {
  155. if let Some(slug) = slug_from_dated_filename {
  156. slugify(&slug)
  157. } else {
  158. slugify(&page.file.name)
  159. }
  160. }
  161. };
  162. if let Some(ref p) = page.meta.path {
  163. page.path = p.trim().trim_start_matches('/').to_string();
  164. } else {
  165. let mut path = if page.file.components.is_empty() {
  166. page.slug.clone()
  167. } else {
  168. format!("{}/{}", page.file.components.join("/"), page.slug)
  169. };
  170. if page.lang != config.default_language {
  171. path = format!("{}/{}", page.lang, path);
  172. }
  173. page.path = path;
  174. }
  175. if !page.path.ends_with('/') {
  176. page.path = format!("{}/", page.path);
  177. }
  178. page.components = page
  179. .path
  180. .split('/')
  181. .map(|p| p.to_string())
  182. .filter(|p| !p.is_empty())
  183. .collect::<Vec<_>>();
  184. page.permalink = config.make_permalink(&page.path);
  185. Ok(page)
  186. }
  187. /// Read and parse a .md file into a Page struct
  188. pub fn from_file<P: AsRef<Path>>(
  189. path: P,
  190. config: &Config,
  191. base_path: &PathBuf,
  192. ) -> Result<Page> {
  193. let path = path.as_ref();
  194. let content = read_file(path)?;
  195. let mut page = Page::parse(path, &content, config, base_path)?;
  196. if page.file.name == "index" {
  197. let parent_dir = path.parent().unwrap();
  198. let assets = find_related_assets(parent_dir);
  199. if let Some(ref globset) = config.ignored_content_globset {
  200. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  201. // filtering only needs to work against the file_name component, not the full suffix. If
  202. // `find_related_assets` was changed to also return files in subdirectories, we could
  203. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  204. // against the remaining path. Note that the current behaviour effectively means that
  205. // the `ignored_content` setting in the config file is limited to single-file glob
  206. // patterns (no "**" patterns).
  207. page.assets = assets
  208. .into_iter()
  209. .filter(|path| match path.file_name() {
  210. None => true,
  211. Some(file) => !globset.is_match(file),
  212. })
  213. .collect();
  214. } else {
  215. page.assets = assets;
  216. }
  217. page.serialized_assets = page.serialize_assets(&base_path);
  218. } else {
  219. page.assets = vec![];
  220. }
  221. Ok(page)
  222. }
  223. /// We need access to all pages url to render links relative to content
  224. /// so that can't happen at the same time as parsing
  225. pub fn render_markdown(
  226. &mut self,
  227. permalinks: &HashMap<String, String>,
  228. tera: &Tera,
  229. config: &Config,
  230. anchor_insert: InsertAnchor,
  231. ) -> Result<()> {
  232. let mut context =
  233. RenderContext::new(tera, config, &self.permalink, permalinks, anchor_insert);
  234. context.tera_context.insert("page", &SerializingPage::from_page_basic(self, None));
  235. let res = render_content(&self.raw_content, &context).map_err(|e| {
  236. Error::chain(format!("Failed to render content of {}", self.file.path.display()), e)
  237. })?;
  238. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  239. self.content = res.body;
  240. self.toc = res.toc;
  241. self.external_links = res.external_links;
  242. Ok(())
  243. }
  244. /// Renders the page using the default layout, unless specified in front-matter
  245. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  246. let tpl_name = match self.meta.template {
  247. Some(ref l) => l,
  248. None => "page.html",
  249. };
  250. let mut context = TeraContext::new();
  251. context.insert("config", config);
  252. context.insert("current_url", &self.permalink);
  253. context.insert("current_path", &self.path);
  254. context.insert("page", &self.to_serialized(library));
  255. context.insert("lang", &self.lang);
  256. context.insert("toc", &self.toc);
  257. render_template(&tpl_name, tera, context, &config.theme).map_err(|e| {
  258. Error::chain(format!("Failed to render page '{}'", self.file.path.display()), e)
  259. })
  260. }
  261. /// Creates a vectors of asset URLs.
  262. fn serialize_assets(&self, base_path: &PathBuf) -> Vec<String> {
  263. self.assets
  264. .iter()
  265. .filter_map(|asset| asset.file_name())
  266. .filter_map(|filename| filename.to_str())
  267. .map(|filename| {
  268. let mut path = self.file.path.clone();
  269. // Popping the index.md from the path since file.parent would be one level too high
  270. // for our need here
  271. path.pop();
  272. path.push(filename);
  273. path = path
  274. .strip_prefix(&base_path.join("content"))
  275. .expect("Should be able to stripe prefix")
  276. .to_path_buf();
  277. path
  278. })
  279. .map(|path| path.to_string_lossy().to_string())
  280. .collect()
  281. }
  282. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  283. SerializingPage::from_page(self, library)
  284. }
  285. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  286. SerializingPage::from_page_basic(self, Some(library))
  287. }
  288. }
  289. impl Default for Page {
  290. fn default() -> Page {
  291. Page {
  292. file: FileInfo::default(),
  293. meta: PageFrontMatter::default(),
  294. ancestors: vec![],
  295. raw_content: "".to_string(),
  296. assets: vec![],
  297. serialized_assets: vec![],
  298. content: "".to_string(),
  299. slug: "".to_string(),
  300. path: "".to_string(),
  301. components: vec![],
  302. permalink: "".to_string(),
  303. summary: None,
  304. earlier: None,
  305. later: None,
  306. lighter: None,
  307. heavier: None,
  308. toc: vec![],
  309. word_count: None,
  310. reading_time: None,
  311. lang: String::new(),
  312. translations: Vec::new(),
  313. external_links: Vec::new(),
  314. }
  315. }
  316. }
  317. #[cfg(test)]
  318. mod tests {
  319. use std::collections::HashMap;
  320. use std::fs::{create_dir, File};
  321. use std::io::Write;
  322. use std::path::{Path, PathBuf};
  323. use globset::{Glob, GlobSetBuilder};
  324. use tempfile::tempdir;
  325. use tera::Tera;
  326. use super::Page;
  327. use config::{Config, Language};
  328. use front_matter::InsertAnchor;
  329. #[test]
  330. fn test_can_parse_a_valid_page() {
  331. let content = r#"
  332. +++
  333. title = "Hello"
  334. description = "hey there"
  335. slug = "hello-world"
  336. +++
  337. Hello world"#;
  338. let res = Page::parse(Path::new("post.md"), content, &Config::default(), &PathBuf::new());
  339. assert!(res.is_ok());
  340. let mut page = res.unwrap();
  341. page.render_markdown(
  342. &HashMap::default(),
  343. &Tera::default(),
  344. &Config::default(),
  345. InsertAnchor::None,
  346. )
  347. .unwrap();
  348. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  349. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  350. assert_eq!(page.raw_content, "Hello world".to_string());
  351. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  352. }
  353. #[test]
  354. fn test_can_make_url_from_sections_and_slug() {
  355. let content = r#"
  356. +++
  357. slug = "hello-world"
  358. +++
  359. Hello world"#;
  360. let mut conf = Config::default();
  361. conf.base_url = "http://hello.com/".to_string();
  362. let res =
  363. Page::parse(Path::new("content/posts/intro/start.md"), content, &conf, &PathBuf::new());
  364. assert!(res.is_ok());
  365. let page = res.unwrap();
  366. assert_eq!(page.path, "posts/intro/hello-world/");
  367. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  368. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  369. }
  370. #[test]
  371. fn can_make_url_from_slug_only() {
  372. let content = r#"
  373. +++
  374. slug = "hello-world"
  375. +++
  376. Hello world"#;
  377. let config = Config::default();
  378. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  379. assert!(res.is_ok());
  380. let page = res.unwrap();
  381. assert_eq!(page.path, "hello-world/");
  382. assert_eq!(page.components, vec!["hello-world"]);
  383. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  384. }
  385. #[test]
  386. fn can_make_url_from_path() {
  387. let content = r#"
  388. +++
  389. path = "hello-world"
  390. +++
  391. Hello world"#;
  392. let config = Config::default();
  393. let res = Page::parse(
  394. Path::new("content/posts/intro/start.md"),
  395. content,
  396. &config,
  397. &PathBuf::new(),
  398. );
  399. assert!(res.is_ok());
  400. let page = res.unwrap();
  401. assert_eq!(page.path, "hello-world/");
  402. assert_eq!(page.components, vec!["hello-world"]);
  403. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  404. }
  405. #[test]
  406. fn can_make_url_from_path_starting_slash() {
  407. let content = r#"
  408. +++
  409. path = "/hello-world"
  410. +++
  411. Hello world"#;
  412. let config = Config::default();
  413. let res = Page::parse(
  414. Path::new("content/posts/intro/start.md"),
  415. content,
  416. &config,
  417. &PathBuf::new(),
  418. );
  419. assert!(res.is_ok());
  420. let page = res.unwrap();
  421. assert_eq!(page.path, "hello-world/");
  422. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  423. }
  424. #[test]
  425. fn errors_on_invalid_front_matter_format() {
  426. // missing starting +++
  427. let content = r#"
  428. title = "Hello"
  429. description = "hey there"
  430. slug = "hello-world"
  431. +++
  432. Hello world"#;
  433. let res = Page::parse(Path::new("start.md"), content, &Config::default(), &PathBuf::new());
  434. assert!(res.is_err());
  435. }
  436. #[test]
  437. fn can_make_slug_from_non_slug_filename() {
  438. let config = Config::default();
  439. let res =
  440. Page::parse(Path::new(" file with space.md"), "+++\n+++", &config, &PathBuf::new());
  441. assert!(res.is_ok());
  442. let page = res.unwrap();
  443. assert_eq!(page.slug, "file-with-space");
  444. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  445. }
  446. #[test]
  447. fn can_specify_summary() {
  448. let config = Config::default();
  449. let content = r#"
  450. +++
  451. +++
  452. Hello world
  453. <!-- more -->"#
  454. .to_string();
  455. let res = Page::parse(Path::new("hello.md"), &content, &config, &PathBuf::new());
  456. assert!(res.is_ok());
  457. let mut page = res.unwrap();
  458. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  459. .unwrap();
  460. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  461. }
  462. #[test]
  463. fn page_with_assets_gets_right_info() {
  464. let tmp_dir = tempdir().expect("create temp dir");
  465. let path = tmp_dir.path();
  466. create_dir(&path.join("content")).expect("create content temp dir");
  467. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  468. let nested_path = path.join("content").join("posts").join("with-assets");
  469. create_dir(&nested_path).expect("create nested temp dir");
  470. let mut f = File::create(nested_path.join("index.md")).unwrap();
  471. f.write_all(b"+++\n+++\n").unwrap();
  472. File::create(nested_path.join("example.js")).unwrap();
  473. File::create(nested_path.join("graph.jpg")).unwrap();
  474. File::create(nested_path.join("fail.png")).unwrap();
  475. let res = Page::from_file(
  476. nested_path.join("index.md").as_path(),
  477. &Config::default(),
  478. &path.to_path_buf(),
  479. );
  480. assert!(res.is_ok());
  481. let page = res.unwrap();
  482. assert_eq!(page.file.parent, path.join("content").join("posts"));
  483. assert_eq!(page.slug, "with-assets");
  484. assert_eq!(page.assets.len(), 3);
  485. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  486. }
  487. #[test]
  488. fn page_with_assets_and_slug_overrides_path() {
  489. let tmp_dir = tempdir().expect("create temp dir");
  490. let path = tmp_dir.path();
  491. create_dir(&path.join("content")).expect("create content temp dir");
  492. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  493. let nested_path = path.join("content").join("posts").join("with-assets");
  494. create_dir(&nested_path).expect("create nested temp dir");
  495. let mut f = File::create(nested_path.join("index.md")).unwrap();
  496. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  497. File::create(nested_path.join("example.js")).unwrap();
  498. File::create(nested_path.join("graph.jpg")).unwrap();
  499. File::create(nested_path.join("fail.png")).unwrap();
  500. let res = Page::from_file(
  501. nested_path.join("index.md").as_path(),
  502. &Config::default(),
  503. &path.to_path_buf(),
  504. );
  505. assert!(res.is_ok());
  506. let page = res.unwrap();
  507. assert_eq!(page.file.parent, path.join("content").join("posts"));
  508. assert_eq!(page.slug, "hey");
  509. assert_eq!(page.assets.len(), 3);
  510. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  511. }
  512. // https://github.com/getzola/zola/issues/674
  513. #[test]
  514. fn page_with_assets_uses_filepath_for_assets() {
  515. let tmp_dir = tempdir().expect("create temp dir");
  516. let path = tmp_dir.path();
  517. create_dir(&path.join("content")).expect("create content temp dir");
  518. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  519. let nested_path = path.join("content").join("posts").join("with_assets");
  520. create_dir(&nested_path).expect("create nested temp dir");
  521. let mut f = File::create(nested_path.join("index.md")).unwrap();
  522. f.write_all(b"+++\n+++\n").unwrap();
  523. File::create(nested_path.join("example.js")).unwrap();
  524. File::create(nested_path.join("graph.jpg")).unwrap();
  525. File::create(nested_path.join("fail.png")).unwrap();
  526. let res = Page::from_file(
  527. nested_path.join("index.md").as_path(),
  528. &Config::default(),
  529. &path.to_path_buf(),
  530. );
  531. assert!(res.is_ok());
  532. let page = res.unwrap();
  533. assert_eq!(page.file.parent, path.join("content").join("posts"));
  534. assert_eq!(page.assets.len(), 3);
  535. assert_eq!(page.serialized_assets.len(), 3);
  536. // We should not get with-assets since that's the slugified version
  537. assert!(page.serialized_assets[0].contains("with_assets"));
  538. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  539. }
  540. // https://github.com/getzola/zola/issues/607
  541. #[test]
  542. fn page_with_assets_and_date_in_folder_name() {
  543. let tmp_dir = tempdir().expect("create temp dir");
  544. let path = tmp_dir.path();
  545. create_dir(&path.join("content")).expect("create content temp dir");
  546. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  547. let nested_path = path.join("content").join("posts").join("2013-06-02_with-assets");
  548. create_dir(&nested_path).expect("create nested temp dir");
  549. let mut f = File::create(nested_path.join("index.md")).unwrap();
  550. f.write_all(b"+++\n\n+++\n").unwrap();
  551. File::create(nested_path.join("example.js")).unwrap();
  552. File::create(nested_path.join("graph.jpg")).unwrap();
  553. File::create(nested_path.join("fail.png")).unwrap();
  554. let res = Page::from_file(
  555. nested_path.join("index.md").as_path(),
  556. &Config::default(),
  557. &path.to_path_buf(),
  558. );
  559. assert!(res.is_ok());
  560. let page = res.unwrap();
  561. assert_eq!(page.file.parent, path.join("content").join("posts"));
  562. assert_eq!(page.slug, "with-assets");
  563. assert_eq!(page.meta.date, Some("2013-06-02".to_string()));
  564. assert_eq!(page.assets.len(), 3);
  565. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  566. }
  567. #[test]
  568. fn page_with_ignored_assets_filters_out_correct_files() {
  569. let tmp_dir = tempdir().expect("create temp dir");
  570. let path = tmp_dir.path();
  571. create_dir(&path.join("content")).expect("create content temp dir");
  572. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  573. let nested_path = path.join("content").join("posts").join("with-assets");
  574. create_dir(&nested_path).expect("create nested temp dir");
  575. let mut f = File::create(nested_path.join("index.md")).unwrap();
  576. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  577. File::create(nested_path.join("example.js")).unwrap();
  578. File::create(nested_path.join("graph.jpg")).unwrap();
  579. File::create(nested_path.join("fail.png")).unwrap();
  580. let mut gsb = GlobSetBuilder::new();
  581. gsb.add(Glob::new("*.{js,png}").unwrap());
  582. let mut config = Config::default();
  583. config.ignored_content_globset = Some(gsb.build().unwrap());
  584. let res =
  585. Page::from_file(nested_path.join("index.md").as_path(), &config, &path.to_path_buf());
  586. assert!(res.is_ok());
  587. let page = res.unwrap();
  588. assert_eq!(page.assets.len(), 1);
  589. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  590. }
  591. #[test]
  592. fn can_get_date_from_short_date_in_filename() {
  593. let config = Config::default();
  594. let content = r#"
  595. +++
  596. +++
  597. Hello world
  598. <!-- more -->"#
  599. .to_string();
  600. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  601. assert!(res.is_ok());
  602. let page = res.unwrap();
  603. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  604. assert_eq!(page.slug, "hello");
  605. }
  606. #[test]
  607. fn can_get_date_from_full_rfc3339_date_in_filename() {
  608. let config = Config::default();
  609. let content = r#"
  610. +++
  611. +++
  612. Hello world
  613. <!-- more -->"#
  614. .to_string();
  615. let res = Page::parse(
  616. Path::new("2018-10-02T15:00:00Z-hello.md"),
  617. &content,
  618. &config,
  619. &PathBuf::new(),
  620. );
  621. assert!(res.is_ok());
  622. let page = res.unwrap();
  623. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  624. assert_eq!(page.slug, "hello");
  625. }
  626. #[test]
  627. fn frontmatter_date_override_filename_date() {
  628. let config = Config::default();
  629. let content = r#"
  630. +++
  631. date = 2018-09-09
  632. +++
  633. Hello world
  634. <!-- more -->"#
  635. .to_string();
  636. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  637. assert!(res.is_ok());
  638. let page = res.unwrap();
  639. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  640. assert_eq!(page.slug, "hello");
  641. }
  642. #[test]
  643. fn can_specify_language_in_filename() {
  644. let mut config = Config::default();
  645. config.languages.push(Language { code: String::from("fr"), rss: false });
  646. let content = r#"
  647. +++
  648. +++
  649. Bonjour le monde"#
  650. .to_string();
  651. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  652. assert!(res.is_ok());
  653. let page = res.unwrap();
  654. assert_eq!(page.lang, "fr".to_string());
  655. assert_eq!(page.slug, "hello");
  656. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  657. }
  658. #[test]
  659. fn can_specify_language_in_filename_with_date() {
  660. let mut config = Config::default();
  661. config.languages.push(Language { code: String::from("fr"), rss: false });
  662. let content = r#"
  663. +++
  664. +++
  665. Bonjour le monde"#
  666. .to_string();
  667. let res =
  668. Page::parse(Path::new("2018-10-08_hello.fr.md"), &content, &config, &PathBuf::new());
  669. assert!(res.is_ok());
  670. let page = res.unwrap();
  671. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  672. assert_eq!(page.lang, "fr".to_string());
  673. assert_eq!(page.slug, "hello");
  674. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  675. }
  676. #[test]
  677. fn i18n_frontmatter_path_overrides_default_permalink() {
  678. let mut config = Config::default();
  679. config.languages.push(Language { code: String::from("fr"), rss: false });
  680. let content = r#"
  681. +++
  682. path = "bonjour"
  683. +++
  684. Bonjour le monde"#
  685. .to_string();
  686. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  687. assert!(res.is_ok());
  688. let page = res.unwrap();
  689. assert_eq!(page.lang, "fr".to_string());
  690. assert_eq!(page.slug, "hello");
  691. assert_eq!(page.permalink, "http://a-website.com/bonjour/");
  692. }
  693. }