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.

714 lines
25KB

  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();
  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) -> Vec<String> {
  259. self.assets
  260. .iter()
  261. .filter_map(|asset| asset.file_name())
  262. .filter_map(|filename| filename.to_str())
  263. .map(|filename| self.path.clone() + filename)
  264. .collect()
  265. }
  266. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  267. SerializingPage::from_page(self, library)
  268. }
  269. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingPage<'a> {
  270. SerializingPage::from_page_basic(self, Some(library))
  271. }
  272. }
  273. impl Default for Page {
  274. fn default() -> Page {
  275. Page {
  276. file: FileInfo::default(),
  277. meta: PageFrontMatter::default(),
  278. ancestors: vec![],
  279. raw_content: "".to_string(),
  280. assets: vec![],
  281. serialized_assets: vec![],
  282. content: "".to_string(),
  283. slug: "".to_string(),
  284. path: "".to_string(),
  285. components: vec![],
  286. permalink: "".to_string(),
  287. summary: None,
  288. earlier: None,
  289. later: None,
  290. lighter: None,
  291. heavier: None,
  292. toc: vec![],
  293. word_count: None,
  294. reading_time: None,
  295. lang: String::new(),
  296. translations: Vec::new(),
  297. }
  298. }
  299. }
  300. #[cfg(test)]
  301. mod tests {
  302. use std::collections::HashMap;
  303. use std::fs::{create_dir, File};
  304. use std::io::Write;
  305. use std::path::{Path, PathBuf};
  306. use globset::{Glob, GlobSetBuilder};
  307. use tempfile::tempdir;
  308. use tera::Tera;
  309. use super::Page;
  310. use config::{Config, Language};
  311. use front_matter::InsertAnchor;
  312. #[test]
  313. fn test_can_parse_a_valid_page() {
  314. let content = r#"
  315. +++
  316. title = "Hello"
  317. description = "hey there"
  318. slug = "hello-world"
  319. +++
  320. Hello world"#;
  321. let res = Page::parse(Path::new("post.md"), content, &Config::default(), &PathBuf::new());
  322. assert!(res.is_ok());
  323. let mut page = res.unwrap();
  324. page.render_markdown(
  325. &HashMap::default(),
  326. &Tera::default(),
  327. &Config::default(),
  328. InsertAnchor::None,
  329. )
  330. .unwrap();
  331. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  332. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  333. assert_eq!(page.raw_content, "Hello world".to_string());
  334. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  335. }
  336. #[test]
  337. fn test_can_make_url_from_sections_and_slug() {
  338. let content = r#"
  339. +++
  340. slug = "hello-world"
  341. +++
  342. Hello world"#;
  343. let mut conf = Config::default();
  344. conf.base_url = "http://hello.com/".to_string();
  345. let res =
  346. Page::parse(Path::new("content/posts/intro/start.md"), content, &conf, &PathBuf::new());
  347. assert!(res.is_ok());
  348. let page = res.unwrap();
  349. assert_eq!(page.path, "posts/intro/hello-world/");
  350. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  351. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  352. }
  353. #[test]
  354. fn can_make_url_from_slug_only() {
  355. let content = r#"
  356. +++
  357. slug = "hello-world"
  358. +++
  359. Hello world"#;
  360. let config = Config::default();
  361. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  362. assert!(res.is_ok());
  363. let page = res.unwrap();
  364. assert_eq!(page.path, "hello-world/");
  365. assert_eq!(page.components, vec!["hello-world"]);
  366. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  367. }
  368. #[test]
  369. fn can_make_url_from_path() {
  370. let content = r#"
  371. +++
  372. path = "hello-world"
  373. +++
  374. Hello world"#;
  375. let config = Config::default();
  376. let res = Page::parse(
  377. Path::new("content/posts/intro/start.md"),
  378. content,
  379. &config,
  380. &PathBuf::new(),
  381. );
  382. assert!(res.is_ok());
  383. let page = res.unwrap();
  384. assert_eq!(page.path, "hello-world/");
  385. assert_eq!(page.components, vec!["hello-world"]);
  386. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  387. }
  388. #[test]
  389. fn can_make_url_from_path_starting_slash() {
  390. let content = r#"
  391. +++
  392. path = "/hello-world"
  393. +++
  394. Hello world"#;
  395. let config = Config::default();
  396. let res = Page::parse(
  397. Path::new("content/posts/intro/start.md"),
  398. content,
  399. &config,
  400. &PathBuf::new(),
  401. );
  402. assert!(res.is_ok());
  403. let page = res.unwrap();
  404. assert_eq!(page.path, "hello-world/");
  405. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  406. }
  407. #[test]
  408. fn errors_on_invalid_front_matter_format() {
  409. // missing starting +++
  410. let content = r#"
  411. title = "Hello"
  412. description = "hey there"
  413. slug = "hello-world"
  414. +++
  415. Hello world"#;
  416. let res = Page::parse(Path::new("start.md"), content, &Config::default(), &PathBuf::new());
  417. assert!(res.is_err());
  418. }
  419. #[test]
  420. fn can_make_slug_from_non_slug_filename() {
  421. let config = Config::default();
  422. let res =
  423. Page::parse(Path::new(" file with space.md"), "+++\n+++", &config, &PathBuf::new());
  424. assert!(res.is_ok());
  425. let page = res.unwrap();
  426. assert_eq!(page.slug, "file-with-space");
  427. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  428. }
  429. #[test]
  430. fn can_specify_summary() {
  431. let config = Config::default();
  432. let content = r#"
  433. +++
  434. +++
  435. Hello world
  436. <!-- more -->"#
  437. .to_string();
  438. let res = Page::parse(Path::new("hello.md"), &content, &config, &PathBuf::new());
  439. assert!(res.is_ok());
  440. let mut page = res.unwrap();
  441. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  442. .unwrap();
  443. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  444. }
  445. #[test]
  446. fn page_with_assets_gets_right_info() {
  447. let tmp_dir = tempdir().expect("create temp dir");
  448. let path = tmp_dir.path();
  449. create_dir(&path.join("content")).expect("create content temp dir");
  450. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  451. let nested_path = path.join("content").join("posts").join("with-assets");
  452. create_dir(&nested_path).expect("create nested temp dir");
  453. let mut f = File::create(nested_path.join("index.md")).unwrap();
  454. f.write_all(b"+++\n+++\n").unwrap();
  455. File::create(nested_path.join("example.js")).unwrap();
  456. File::create(nested_path.join("graph.jpg")).unwrap();
  457. File::create(nested_path.join("fail.png")).unwrap();
  458. let res = Page::from_file(
  459. nested_path.join("index.md").as_path(),
  460. &Config::default(),
  461. &PathBuf::new(),
  462. );
  463. assert!(res.is_ok());
  464. let page = res.unwrap();
  465. assert_eq!(page.file.parent, path.join("content").join("posts"));
  466. assert_eq!(page.slug, "with-assets");
  467. assert_eq!(page.assets.len(), 3);
  468. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  469. }
  470. #[test]
  471. fn page_with_assets_and_slug_overrides_path() {
  472. let tmp_dir = tempdir().expect("create temp dir");
  473. let path = tmp_dir.path();
  474. create_dir(&path.join("content")).expect("create content temp dir");
  475. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  476. let nested_path = path.join("content").join("posts").join("with-assets");
  477. create_dir(&nested_path).expect("create nested temp dir");
  478. let mut f = File::create(nested_path.join("index.md")).unwrap();
  479. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  480. File::create(nested_path.join("example.js")).unwrap();
  481. File::create(nested_path.join("graph.jpg")).unwrap();
  482. File::create(nested_path.join("fail.png")).unwrap();
  483. let res = Page::from_file(
  484. nested_path.join("index.md").as_path(),
  485. &Config::default(),
  486. &PathBuf::new(),
  487. );
  488. assert!(res.is_ok());
  489. let page = res.unwrap();
  490. assert_eq!(page.file.parent, path.join("content").join("posts"));
  491. assert_eq!(page.slug, "hey");
  492. assert_eq!(page.assets.len(), 3);
  493. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  494. }
  495. // https://github.com/getzola/zola/issues/607
  496. #[test]
  497. fn page_with_assets_and_date_in_folder_name() {
  498. let tmp_dir = tempdir().expect("create temp dir");
  499. let path = tmp_dir.path();
  500. create_dir(&path.join("content")).expect("create content temp dir");
  501. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  502. let nested_path = path.join("content").join("posts").join("2013-06-02_with-assets");
  503. create_dir(&nested_path).expect("create nested temp dir");
  504. let mut f = File::create(nested_path.join("index.md")).unwrap();
  505. f.write_all(b"+++\n\n+++\n").unwrap();
  506. File::create(nested_path.join("example.js")).unwrap();
  507. File::create(nested_path.join("graph.jpg")).unwrap();
  508. File::create(nested_path.join("fail.png")).unwrap();
  509. let res = Page::from_file(
  510. nested_path.join("index.md").as_path(),
  511. &Config::default(),
  512. &PathBuf::new(),
  513. );
  514. assert!(res.is_ok());
  515. let page = res.unwrap();
  516. assert_eq!(page.file.parent, path.join("content").join("posts"));
  517. assert_eq!(page.slug, "with-assets");
  518. assert_eq!(page.meta.date, Some("2013-06-02".to_string()));
  519. assert_eq!(page.assets.len(), 3);
  520. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  521. }
  522. #[test]
  523. fn page_with_ignored_assets_filters_out_correct_files() {
  524. let tmp_dir = tempdir().expect("create temp dir");
  525. let path = tmp_dir.path();
  526. create_dir(&path.join("content")).expect("create content temp dir");
  527. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  528. let nested_path = path.join("content").join("posts").join("with-assets");
  529. create_dir(&nested_path).expect("create nested temp dir");
  530. let mut f = File::create(nested_path.join("index.md")).unwrap();
  531. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  532. File::create(nested_path.join("example.js")).unwrap();
  533. File::create(nested_path.join("graph.jpg")).unwrap();
  534. File::create(nested_path.join("fail.png")).unwrap();
  535. let mut gsb = GlobSetBuilder::new();
  536. gsb.add(Glob::new("*.{js,png}").unwrap());
  537. let mut config = Config::default();
  538. config.ignored_content_globset = Some(gsb.build().unwrap());
  539. let res = Page::from_file(nested_path.join("index.md").as_path(), &config, &PathBuf::new());
  540. assert!(res.is_ok());
  541. let page = res.unwrap();
  542. assert_eq!(page.assets.len(), 1);
  543. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  544. }
  545. #[test]
  546. fn can_get_date_from_short_date_in_filename() {
  547. let config = Config::default();
  548. let content = r#"
  549. +++
  550. +++
  551. Hello world
  552. <!-- more -->"#
  553. .to_string();
  554. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  555. assert!(res.is_ok());
  556. let page = res.unwrap();
  557. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  558. assert_eq!(page.slug, "hello");
  559. }
  560. #[test]
  561. fn can_get_date_from_full_rfc3339_date_in_filename() {
  562. let config = Config::default();
  563. let content = r#"
  564. +++
  565. +++
  566. Hello world
  567. <!-- more -->"#
  568. .to_string();
  569. let res = Page::parse(
  570. Path::new("2018-10-02T15:00:00Z-hello.md"),
  571. &content,
  572. &config,
  573. &PathBuf::new(),
  574. );
  575. assert!(res.is_ok());
  576. let page = res.unwrap();
  577. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  578. assert_eq!(page.slug, "hello");
  579. }
  580. #[test]
  581. fn frontmatter_date_override_filename_date() {
  582. let config = Config::default();
  583. let content = r#"
  584. +++
  585. date = 2018-09-09
  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-09-09".to_string()));
  594. assert_eq!(page.slug, "hello");
  595. }
  596. #[test]
  597. fn can_specify_language_in_filename() {
  598. let mut config = Config::default();
  599. config.languages.push(Language { code: String::from("fr"), rss: false });
  600. let content = r#"
  601. +++
  602. +++
  603. Bonjour le monde"#
  604. .to_string();
  605. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  606. assert!(res.is_ok());
  607. let page = res.unwrap();
  608. assert_eq!(page.lang, "fr".to_string());
  609. assert_eq!(page.slug, "hello");
  610. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  611. }
  612. #[test]
  613. fn can_specify_language_in_filename_with_date() {
  614. let mut config = Config::default();
  615. config.languages.push(Language { code: String::from("fr"), rss: false });
  616. let content = r#"
  617. +++
  618. +++
  619. Bonjour le monde"#
  620. .to_string();
  621. let res =
  622. Page::parse(Path::new("2018-10-08_hello.fr.md"), &content, &config, &PathBuf::new());
  623. assert!(res.is_ok());
  624. let page = res.unwrap();
  625. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  626. assert_eq!(page.lang, "fr".to_string());
  627. assert_eq!(page.slug, "hello");
  628. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  629. }
  630. #[test]
  631. fn i18n_frontmatter_path_overrides_default_permalink() {
  632. let mut config = Config::default();
  633. config.languages.push(Language { code: String::from("fr"), rss: false });
  634. let content = r#"
  635. +++
  636. path = "bonjour"
  637. +++
  638. Bonjour le monde"#
  639. .to_string();
  640. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  641. assert!(res.is_ok());
  642. let page = res.unwrap();
  643. assert_eq!(page.lang, "fr".to_string());
  644. assert_eq!(page.slug, "hello");
  645. assert_eq!(page.permalink, "http://a-website.com/bonjour/");
  646. }
  647. }