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.

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