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.

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