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.

824 lines
30KB

  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::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. slugify_paths(slug, 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. slugify_paths(&slug, config.slugify.paths)
  156. } else {
  157. slugify_paths(
  158. parent.file_name().unwrap().to_str().unwrap(),
  159. config.slugify.paths,
  160. )
  161. }
  162. } else {
  163. slugify_paths(&page.file.name, config.slugify.paths)
  164. }
  165. } else if let Some(slug) = slug_from_dated_filename {
  166. slugify_paths(&slug, config.slugify.paths)
  167. } else {
  168. 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. use utils::slugs::SlugifyStrategy;
  343. #[test]
  344. fn test_can_parse_a_valid_page() {
  345. let content = r#"
  346. +++
  347. title = "Hello"
  348. description = "hey there"
  349. slug = "hello-world"
  350. +++
  351. Hello world"#;
  352. let res = Page::parse(Path::new("post.md"), content, &Config::default(), &PathBuf::new());
  353. assert!(res.is_ok());
  354. let mut page = res.unwrap();
  355. page.render_markdown(
  356. &HashMap::default(),
  357. &Tera::default(),
  358. &Config::default(),
  359. InsertAnchor::None,
  360. )
  361. .unwrap();
  362. assert_eq!(page.meta.title.unwrap(), "Hello".to_string());
  363. assert_eq!(page.meta.slug.unwrap(), "hello-world".to_string());
  364. assert_eq!(page.raw_content, "Hello world".to_string());
  365. assert_eq!(page.content, "<p>Hello world</p>\n".to_string());
  366. }
  367. #[test]
  368. fn test_can_make_url_from_sections_and_slug() {
  369. let content = r#"
  370. +++
  371. slug = "hello-world"
  372. +++
  373. Hello world"#;
  374. let mut conf = Config::default();
  375. conf.base_url = "http://hello.com/".to_string();
  376. let res =
  377. Page::parse(Path::new("content/posts/intro/start.md"), content, &conf, &PathBuf::new());
  378. assert!(res.is_ok());
  379. let page = res.unwrap();
  380. assert_eq!(page.path, "posts/intro/hello-world/");
  381. assert_eq!(page.components, vec!["posts", "intro", "hello-world"]);
  382. assert_eq!(page.permalink, "http://hello.com/posts/intro/hello-world/");
  383. }
  384. #[test]
  385. fn can_make_url_from_slug_only() {
  386. let content = r#"
  387. +++
  388. slug = "hello-world"
  389. +++
  390. Hello world"#;
  391. let config = Config::default();
  392. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  393. assert!(res.is_ok());
  394. let page = res.unwrap();
  395. assert_eq!(page.path, "hello-world/");
  396. assert_eq!(page.components, vec!["hello-world"]);
  397. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  398. }
  399. #[test]
  400. fn can_make_url_from_slug_only_with_no_special_chars() {
  401. let content = r#"
  402. +++
  403. slug = "hello-&-world"
  404. +++
  405. Hello world"#;
  406. let mut config = Config::default();
  407. config.slugify.paths = SlugifyStrategy::On;
  408. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  409. assert!(res.is_ok());
  410. let page = res.unwrap();
  411. assert_eq!(page.path, "hello-world/");
  412. assert_eq!(page.components, vec!["hello-world"]);
  413. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  414. }
  415. #[test]
  416. fn can_make_url_from_utf8_slug_frontmatter() {
  417. let content = r#"
  418. +++
  419. slug = "日本"
  420. +++
  421. Hello world"#;
  422. let mut config = Config::default();
  423. config.slugify.paths = SlugifyStrategy::Safe;
  424. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  425. assert!(res.is_ok());
  426. let page = res.unwrap();
  427. assert_eq!(page.path, "日本/");
  428. assert_eq!(page.components, vec!["日本"]);
  429. assert_eq!(page.permalink, config.make_permalink("日本"));
  430. }
  431. #[test]
  432. fn can_make_url_from_path() {
  433. let content = r#"
  434. +++
  435. path = "hello-world"
  436. +++
  437. Hello world"#;
  438. let config = Config::default();
  439. let res = Page::parse(
  440. Path::new("content/posts/intro/start.md"),
  441. content,
  442. &config,
  443. &PathBuf::new(),
  444. );
  445. assert!(res.is_ok());
  446. let page = res.unwrap();
  447. assert_eq!(page.path, "hello-world/");
  448. assert_eq!(page.components, vec!["hello-world"]);
  449. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  450. }
  451. #[test]
  452. fn can_make_url_from_path_starting_slash() {
  453. let content = r#"
  454. +++
  455. path = "/hello-world"
  456. +++
  457. Hello world"#;
  458. let config = Config::default();
  459. let res = Page::parse(
  460. Path::new("content/posts/intro/start.md"),
  461. content,
  462. &config,
  463. &PathBuf::new(),
  464. );
  465. assert!(res.is_ok());
  466. let page = res.unwrap();
  467. assert_eq!(page.path, "hello-world/");
  468. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  469. }
  470. #[test]
  471. fn errors_on_invalid_front_matter_format() {
  472. // missing starting +++
  473. let content = r#"
  474. title = "Hello"
  475. description = "hey there"
  476. slug = "hello-world"
  477. +++
  478. Hello world"#;
  479. let res = Page::parse(Path::new("start.md"), content, &Config::default(), &PathBuf::new());
  480. assert!(res.is_err());
  481. }
  482. #[test]
  483. fn can_make_slug_from_non_slug_filename() {
  484. let mut config = Config::default();
  485. config.slugify.paths = SlugifyStrategy::On;
  486. let res =
  487. Page::parse(Path::new(" file with space.md"), "+++\n+++", &config, &PathBuf::new());
  488. assert!(res.is_ok());
  489. let page = res.unwrap();
  490. assert_eq!(page.slug, "file-with-space");
  491. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  492. }
  493. #[test]
  494. fn can_make_path_from_utf8_filename() {
  495. let mut config = Config::default();
  496. config.slugify.paths = SlugifyStrategy::Safe;
  497. let res = Page::parse(Path::new("日本.md"), "+++\n++++", &config, &PathBuf::new());
  498. assert!(res.is_ok());
  499. let page = res.unwrap();
  500. assert_eq!(page.slug, "日本");
  501. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  502. }
  503. #[test]
  504. fn can_specify_summary() {
  505. let config = Config::default();
  506. let content = r#"
  507. +++
  508. +++
  509. Hello world
  510. <!-- more -->"#
  511. .to_string();
  512. let res = Page::parse(Path::new("hello.md"), &content, &config, &PathBuf::new());
  513. assert!(res.is_ok());
  514. let mut page = res.unwrap();
  515. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  516. .unwrap();
  517. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  518. }
  519. #[test]
  520. fn page_with_assets_gets_right_info() {
  521. let tmp_dir = tempdir().expect("create temp dir");
  522. let path = tmp_dir.path();
  523. create_dir(&path.join("content")).expect("create content temp dir");
  524. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  525. let nested_path = path.join("content").join("posts").join("with-assets");
  526. create_dir(&nested_path).expect("create nested temp dir");
  527. let mut f = File::create(nested_path.join("index.md")).unwrap();
  528. f.write_all(b"+++\n+++\n").unwrap();
  529. File::create(nested_path.join("example.js")).unwrap();
  530. File::create(nested_path.join("graph.jpg")).unwrap();
  531. File::create(nested_path.join("fail.png")).unwrap();
  532. let res = Page::from_file(
  533. nested_path.join("index.md").as_path(),
  534. &Config::default(),
  535. &path.to_path_buf(),
  536. );
  537. assert!(res.is_ok());
  538. let page = res.unwrap();
  539. assert_eq!(page.file.parent, path.join("content").join("posts"));
  540. assert_eq!(page.slug, "with-assets");
  541. assert_eq!(page.assets.len(), 3);
  542. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  543. }
  544. #[test]
  545. fn page_with_assets_and_slug_overrides_path() {
  546. let tmp_dir = tempdir().expect("create temp dir");
  547. let path = tmp_dir.path();
  548. create_dir(&path.join("content")).expect("create content temp dir");
  549. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  550. let nested_path = path.join("content").join("posts").join("with-assets");
  551. create_dir(&nested_path).expect("create nested temp dir");
  552. let mut f = File::create(nested_path.join("index.md")).unwrap();
  553. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  554. File::create(nested_path.join("example.js")).unwrap();
  555. File::create(nested_path.join("graph.jpg")).unwrap();
  556. File::create(nested_path.join("fail.png")).unwrap();
  557. let res = Page::from_file(
  558. nested_path.join("index.md").as_path(),
  559. &Config::default(),
  560. &path.to_path_buf(),
  561. );
  562. assert!(res.is_ok());
  563. let page = res.unwrap();
  564. assert_eq!(page.file.parent, path.join("content").join("posts"));
  565. assert_eq!(page.slug, "hey");
  566. assert_eq!(page.assets.len(), 3);
  567. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  568. }
  569. // https://github.com/getzola/zola/issues/674
  570. #[test]
  571. fn page_with_assets_uses_filepath_for_assets() {
  572. let tmp_dir = tempdir().expect("create temp dir");
  573. let path = tmp_dir.path();
  574. create_dir(&path.join("content")).expect("create content temp dir");
  575. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  576. let nested_path = path.join("content").join("posts").join("with_assets");
  577. create_dir(&nested_path).expect("create nested temp dir");
  578. let mut f = File::create(nested_path.join("index.md")).unwrap();
  579. f.write_all(b"+++\n+++\n").unwrap();
  580. File::create(nested_path.join("example.js")).unwrap();
  581. File::create(nested_path.join("graph.jpg")).unwrap();
  582. File::create(nested_path.join("fail.png")).unwrap();
  583. let res = Page::from_file(
  584. nested_path.join("index.md").as_path(),
  585. &Config::default(),
  586. &path.to_path_buf(),
  587. );
  588. assert!(res.is_ok());
  589. let page = res.unwrap();
  590. assert_eq!(page.file.parent, path.join("content").join("posts"));
  591. assert_eq!(page.assets.len(), 3);
  592. assert_eq!(page.serialized_assets.len(), 3);
  593. // We should not get with-assets since that's the slugified version
  594. assert!(page.serialized_assets[0].contains("with_assets"));
  595. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  596. }
  597. // https://github.com/getzola/zola/issues/607
  598. #[test]
  599. fn page_with_assets_and_date_in_folder_name() {
  600. let tmp_dir = tempdir().expect("create temp dir");
  601. let path = tmp_dir.path();
  602. create_dir(&path.join("content")).expect("create content temp dir");
  603. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  604. let nested_path = path.join("content").join("posts").join("2013-06-02_with-assets");
  605. create_dir(&nested_path).expect("create nested temp dir");
  606. let mut f = File::create(nested_path.join("index.md")).unwrap();
  607. f.write_all(b"+++\n\n+++\n").unwrap();
  608. File::create(nested_path.join("example.js")).unwrap();
  609. File::create(nested_path.join("graph.jpg")).unwrap();
  610. File::create(nested_path.join("fail.png")).unwrap();
  611. let res = Page::from_file(
  612. nested_path.join("index.md").as_path(),
  613. &Config::default(),
  614. &path.to_path_buf(),
  615. );
  616. assert!(res.is_ok());
  617. let page = res.unwrap();
  618. assert_eq!(page.file.parent, path.join("content").join("posts"));
  619. assert_eq!(page.slug, "with-assets");
  620. assert_eq!(page.meta.date, Some("2013-06-02".to_string()));
  621. assert_eq!(page.assets.len(), 3);
  622. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  623. }
  624. #[test]
  625. fn page_with_ignored_assets_filters_out_correct_files() {
  626. let tmp_dir = tempdir().expect("create temp dir");
  627. let path = tmp_dir.path();
  628. create_dir(&path.join("content")).expect("create content temp dir");
  629. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  630. let nested_path = path.join("content").join("posts").join("with-assets");
  631. create_dir(&nested_path).expect("create nested temp dir");
  632. let mut f = File::create(nested_path.join("index.md")).unwrap();
  633. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  634. File::create(nested_path.join("example.js")).unwrap();
  635. File::create(nested_path.join("graph.jpg")).unwrap();
  636. File::create(nested_path.join("fail.png")).unwrap();
  637. let mut gsb = GlobSetBuilder::new();
  638. gsb.add(Glob::new("*.{js,png}").unwrap());
  639. let mut config = Config::default();
  640. config.ignored_content_globset = Some(gsb.build().unwrap());
  641. let res =
  642. Page::from_file(nested_path.join("index.md").as_path(), &config, &path.to_path_buf());
  643. assert!(res.is_ok());
  644. let page = res.unwrap();
  645. assert_eq!(page.assets.len(), 1);
  646. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  647. }
  648. #[test]
  649. fn can_get_date_from_short_date_in_filename() {
  650. let config = Config::default();
  651. let content = r#"
  652. +++
  653. +++
  654. Hello world
  655. <!-- more -->"#
  656. .to_string();
  657. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  658. assert!(res.is_ok());
  659. let page = res.unwrap();
  660. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  661. assert_eq!(page.slug, "hello");
  662. }
  663. #[test]
  664. fn can_get_date_from_full_rfc3339_date_in_filename() {
  665. let config = Config::default();
  666. let content = r#"
  667. +++
  668. +++
  669. Hello world
  670. <!-- more -->"#
  671. .to_string();
  672. let res = Page::parse(
  673. Path::new("2018-10-02T15:00:00Z-hello.md"),
  674. &content,
  675. &config,
  676. &PathBuf::new(),
  677. );
  678. assert!(res.is_ok());
  679. let page = res.unwrap();
  680. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  681. assert_eq!(page.slug, "hello");
  682. }
  683. #[test]
  684. fn frontmatter_date_override_filename_date() {
  685. let config = Config::default();
  686. let content = r#"
  687. +++
  688. date = 2018-09-09
  689. +++
  690. Hello world
  691. <!-- more -->"#
  692. .to_string();
  693. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  694. assert!(res.is_ok());
  695. let page = res.unwrap();
  696. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  697. assert_eq!(page.slug, "hello");
  698. }
  699. #[test]
  700. fn can_specify_language_in_filename() {
  701. let mut config = Config::default();
  702. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  703. let content = r#"
  704. +++
  705. +++
  706. Bonjour le monde"#
  707. .to_string();
  708. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  709. assert!(res.is_ok());
  710. let page = res.unwrap();
  711. assert_eq!(page.lang, "fr".to_string());
  712. assert_eq!(page.slug, "hello");
  713. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  714. }
  715. #[test]
  716. fn can_specify_language_in_filename_with_date() {
  717. let mut config = Config::default();
  718. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  719. let content = r#"
  720. +++
  721. +++
  722. Bonjour le monde"#
  723. .to_string();
  724. let res =
  725. Page::parse(Path::new("2018-10-08_hello.fr.md"), &content, &config, &PathBuf::new());
  726. assert!(res.is_ok());
  727. let page = res.unwrap();
  728. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  729. assert_eq!(page.lang, "fr".to_string());
  730. assert_eq!(page.slug, "hello");
  731. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  732. }
  733. #[test]
  734. fn i18n_frontmatter_path_overrides_default_permalink() {
  735. let mut config = Config::default();
  736. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  737. let content = r#"
  738. +++
  739. path = "bonjour"
  740. +++
  741. Bonjour le monde"#
  742. .to_string();
  743. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  744. assert!(res.is_ok());
  745. let page = res.unwrap();
  746. assert_eq!(page.lang, "fr".to_string());
  747. assert_eq!(page.slug, "hello");
  748. assert_eq!(page.permalink, "http://a-website.com/bonjour/");
  749. }
  750. }