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.

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