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.

776 lines
28KB

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