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.

823 lines
29KB

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