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.

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