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.

820 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(parent.file_name().unwrap().to_str().unwrap(), config.slugify_paths)
  158. }
  159. } else {
  160. maybe_slugify_paths(&page.file.name, config.slugify_paths)
  161. }
  162. } else if let Some(slug) = slug_from_dated_filename {
  163. maybe_slugify_paths(&slug, config.slugify_paths)
  164. } else {
  165. maybe_slugify_paths(&page.file.name, config.slugify_paths)
  166. }
  167. };
  168. if let Some(ref p) = page.meta.path {
  169. page.path = p.trim().trim_start_matches('/').to_string();
  170. } else {
  171. let mut path = if page.file.components.is_empty() {
  172. page.slug.clone()
  173. } else {
  174. format!("{}/{}", page.file.components.join("/"), page.slug)
  175. };
  176. if page.lang != config.default_language {
  177. path = format!("{}/{}", page.lang, path);
  178. }
  179. page.path = path;
  180. }
  181. if !page.path.ends_with('/') {
  182. page.path = format!("{}/", page.path);
  183. }
  184. page.components = page
  185. .path
  186. .split('/')
  187. .map(|p| p.to_string())
  188. .filter(|p| !p.is_empty())
  189. .collect::<Vec<_>>();
  190. page.permalink = config.make_permalink(&page.path);
  191. Ok(page)
  192. }
  193. /// Read and parse a .md file into a Page struct
  194. pub fn from_file<P: AsRef<Path>>(
  195. path: P,
  196. config: &Config,
  197. base_path: &PathBuf,
  198. ) -> Result<Page> {
  199. let path = path.as_ref();
  200. let content = read_file(path)?;
  201. let mut page = Page::parse(path, &content, config, base_path)?;
  202. if page.file.name == "index" {
  203. let parent_dir = path.parent().unwrap();
  204. let assets = find_related_assets(parent_dir);
  205. if let Some(ref globset) = config.ignored_content_globset {
  206. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  207. // filtering only needs to work against the file_name component, not the full suffix. If
  208. // `find_related_assets` was changed to also return files in subdirectories, we could
  209. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  210. // against the remaining path. Note that the current behaviour effectively means that
  211. // the `ignored_content` setting in the config file is limited to single-file glob
  212. // patterns (no "**" patterns).
  213. page.assets = assets
  214. .into_iter()
  215. .filter(|path| match path.file_name() {
  216. None => true,
  217. Some(file) => !globset.is_match(file),
  218. })
  219. .collect();
  220. } else {
  221. page.assets = assets;
  222. }
  223. page.serialized_assets = page.serialize_assets(&base_path);
  224. } else {
  225. page.assets = vec![];
  226. }
  227. Ok(page)
  228. }
  229. /// We need access to all pages url to render links relative to content
  230. /// so that can't happen at the same time as parsing
  231. pub fn render_markdown(
  232. &mut self,
  233. permalinks: &HashMap<String, String>,
  234. tera: &Tera,
  235. config: &Config,
  236. anchor_insert: InsertAnchor,
  237. ) -> Result<()> {
  238. let mut context =
  239. RenderContext::new(tera, config, &self.permalink, permalinks, anchor_insert);
  240. context.tera_context.insert("page", &SerializingPage::from_page_basic(self, None));
  241. let res = render_content(&self.raw_content, &context).map_err(|e| {
  242. Error::chain(format!("Failed to render content of {}", self.file.path.display()), e)
  243. })?;
  244. self.summary = res.summary_len.map(|l| res.body[0..l].to_owned());
  245. self.content = res.body;
  246. self.toc = res.toc;
  247. self.external_links = res.external_links;
  248. self.internal_links_with_anchors = res.internal_links_with_anchors;
  249. Ok(())
  250. }
  251. /// Renders the page using the default layout, unless specified in front-matter
  252. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  253. let tpl_name = match self.meta.template {
  254. Some(ref l) => l,
  255. None => "page.html",
  256. };
  257. let mut context = TeraContext::new();
  258. context.insert("config", config);
  259. context.insert("current_url", &self.permalink);
  260. context.insert("current_path", &self.path);
  261. context.insert("page", &self.to_serialized(library));
  262. context.insert("lang", &self.lang);
  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 mut config = Config::default();
  403. config.slugify_paths = true;
  404. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  405. assert!(res.is_ok());
  406. let page = res.unwrap();
  407. assert_eq!(page.path, "hello-world/");
  408. assert_eq!(page.components, vec!["hello-world"]);
  409. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  410. }
  411. #[test]
  412. fn can_make_url_from_utf8_slug_frontmatter() {
  413. let content = r#"
  414. +++
  415. slug = "日本"
  416. +++
  417. Hello world"#;
  418. let mut config = Config::default();
  419. config.slugify_paths = false;
  420. let res = Page::parse(Path::new("start.md"), content, &config, &PathBuf::new());
  421. assert!(res.is_ok());
  422. let page = res.unwrap();
  423. assert_eq!(page.path, "日本/");
  424. assert_eq!(page.components, vec!["日本"]);
  425. assert_eq!(page.permalink, config.make_permalink("日本"));
  426. }
  427. #[test]
  428. fn can_make_url_from_path() {
  429. let content = r#"
  430. +++
  431. path = "hello-world"
  432. +++
  433. Hello world"#;
  434. let config = Config::default();
  435. let res = Page::parse(
  436. Path::new("content/posts/intro/start.md"),
  437. content,
  438. &config,
  439. &PathBuf::new(),
  440. );
  441. assert!(res.is_ok());
  442. let page = res.unwrap();
  443. assert_eq!(page.path, "hello-world/");
  444. assert_eq!(page.components, vec!["hello-world"]);
  445. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  446. }
  447. #[test]
  448. fn can_make_url_from_path_starting_slash() {
  449. let content = r#"
  450. +++
  451. path = "/hello-world"
  452. +++
  453. Hello world"#;
  454. let config = Config::default();
  455. let res = Page::parse(
  456. Path::new("content/posts/intro/start.md"),
  457. content,
  458. &config,
  459. &PathBuf::new(),
  460. );
  461. assert!(res.is_ok());
  462. let page = res.unwrap();
  463. assert_eq!(page.path, "hello-world/");
  464. assert_eq!(page.permalink, config.make_permalink("hello-world"));
  465. }
  466. #[test]
  467. fn errors_on_invalid_front_matter_format() {
  468. // missing starting +++
  469. let content = r#"
  470. title = "Hello"
  471. description = "hey there"
  472. slug = "hello-world"
  473. +++
  474. Hello world"#;
  475. let res = Page::parse(Path::new("start.md"), content, &Config::default(), &PathBuf::new());
  476. assert!(res.is_err());
  477. }
  478. #[test]
  479. fn can_make_slug_from_non_slug_filename() {
  480. let mut config = Config::default();
  481. config.slugify_paths = true;
  482. let res =
  483. Page::parse(Path::new(" file with space.md"), "+++\n+++", &config, &PathBuf::new());
  484. assert!(res.is_ok());
  485. let page = res.unwrap();
  486. assert_eq!(page.slug, "file-with-space");
  487. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  488. }
  489. #[test]
  490. fn can_make_path_from_utf8_filename() {
  491. let mut config = Config::default();
  492. config.slugify_paths = false;
  493. let res = Page::parse(Path::new("日本.md"), "+++\n++++", &config, &PathBuf::new());
  494. assert!(res.is_ok());
  495. let page = res.unwrap();
  496. assert_eq!(page.slug, "日本");
  497. assert_eq!(page.permalink, config.make_permalink(&page.slug));
  498. }
  499. #[test]
  500. fn can_specify_summary() {
  501. let config = Config::default();
  502. let content = r#"
  503. +++
  504. +++
  505. Hello world
  506. <!-- more -->"#
  507. .to_string();
  508. let res = Page::parse(Path::new("hello.md"), &content, &config, &PathBuf::new());
  509. assert!(res.is_ok());
  510. let mut page = res.unwrap();
  511. page.render_markdown(&HashMap::default(), &Tera::default(), &config, InsertAnchor::None)
  512. .unwrap();
  513. assert_eq!(page.summary, Some("<p>Hello world</p>\n".to_string()));
  514. }
  515. #[test]
  516. fn page_with_assets_gets_right_info() {
  517. let tmp_dir = tempdir().expect("create temp dir");
  518. let path = tmp_dir.path();
  519. create_dir(&path.join("content")).expect("create content temp dir");
  520. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  521. let nested_path = path.join("content").join("posts").join("with-assets");
  522. create_dir(&nested_path).expect("create nested temp dir");
  523. let mut f = File::create(nested_path.join("index.md")).unwrap();
  524. f.write_all(b"+++\n+++\n").unwrap();
  525. File::create(nested_path.join("example.js")).unwrap();
  526. File::create(nested_path.join("graph.jpg")).unwrap();
  527. File::create(nested_path.join("fail.png")).unwrap();
  528. let res = Page::from_file(
  529. nested_path.join("index.md").as_path(),
  530. &Config::default(),
  531. &path.to_path_buf(),
  532. );
  533. assert!(res.is_ok());
  534. let page = res.unwrap();
  535. assert_eq!(page.file.parent, path.join("content").join("posts"));
  536. assert_eq!(page.slug, "with-assets");
  537. assert_eq!(page.assets.len(), 3);
  538. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  539. }
  540. #[test]
  541. fn page_with_assets_and_slug_overrides_path() {
  542. let tmp_dir = tempdir().expect("create temp dir");
  543. let path = tmp_dir.path();
  544. create_dir(&path.join("content")).expect("create content temp dir");
  545. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  546. let nested_path = path.join("content").join("posts").join("with-assets");
  547. create_dir(&nested_path).expect("create nested temp dir");
  548. let mut f = File::create(nested_path.join("index.md")).unwrap();
  549. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  550. File::create(nested_path.join("example.js")).unwrap();
  551. File::create(nested_path.join("graph.jpg")).unwrap();
  552. File::create(nested_path.join("fail.png")).unwrap();
  553. let res = Page::from_file(
  554. nested_path.join("index.md").as_path(),
  555. &Config::default(),
  556. &path.to_path_buf(),
  557. );
  558. assert!(res.is_ok());
  559. let page = res.unwrap();
  560. assert_eq!(page.file.parent, path.join("content").join("posts"));
  561. assert_eq!(page.slug, "hey");
  562. assert_eq!(page.assets.len(), 3);
  563. assert_eq!(page.permalink, "http://a-website.com/posts/hey/");
  564. }
  565. // https://github.com/getzola/zola/issues/674
  566. #[test]
  567. fn page_with_assets_uses_filepath_for_assets() {
  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("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").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.assets.len(), 3);
  588. assert_eq!(page.serialized_assets.len(), 3);
  589. // We should not get with-assets since that's the slugified version
  590. assert!(page.serialized_assets[0].contains("with_assets"));
  591. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  592. }
  593. // https://github.com/getzola/zola/issues/607
  594. #[test]
  595. fn page_with_assets_and_date_in_folder_name() {
  596. let tmp_dir = tempdir().expect("create temp dir");
  597. let path = tmp_dir.path();
  598. create_dir(&path.join("content")).expect("create content temp dir");
  599. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  600. let nested_path = path.join("content").join("posts").join("2013-06-02_with-assets");
  601. create_dir(&nested_path).expect("create nested temp dir");
  602. let mut f = File::create(nested_path.join("index.md")).unwrap();
  603. f.write_all(b"+++\n\n+++\n").unwrap();
  604. File::create(nested_path.join("example.js")).unwrap();
  605. File::create(nested_path.join("graph.jpg")).unwrap();
  606. File::create(nested_path.join("fail.png")).unwrap();
  607. let res = Page::from_file(
  608. nested_path.join("index.md").as_path(),
  609. &Config::default(),
  610. &path.to_path_buf(),
  611. );
  612. assert!(res.is_ok());
  613. let page = res.unwrap();
  614. assert_eq!(page.file.parent, path.join("content").join("posts"));
  615. assert_eq!(page.slug, "with-assets");
  616. assert_eq!(page.meta.date, Some("2013-06-02".to_string()));
  617. assert_eq!(page.assets.len(), 3);
  618. assert_eq!(page.permalink, "http://a-website.com/posts/with-assets/");
  619. }
  620. #[test]
  621. fn page_with_ignored_assets_filters_out_correct_files() {
  622. let tmp_dir = tempdir().expect("create temp dir");
  623. let path = tmp_dir.path();
  624. create_dir(&path.join("content")).expect("create content temp dir");
  625. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  626. let nested_path = path.join("content").join("posts").join("with-assets");
  627. create_dir(&nested_path).expect("create nested temp dir");
  628. let mut f = File::create(nested_path.join("index.md")).unwrap();
  629. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  630. File::create(nested_path.join("example.js")).unwrap();
  631. File::create(nested_path.join("graph.jpg")).unwrap();
  632. File::create(nested_path.join("fail.png")).unwrap();
  633. let mut gsb = GlobSetBuilder::new();
  634. gsb.add(Glob::new("*.{js,png}").unwrap());
  635. let mut config = Config::default();
  636. config.ignored_content_globset = Some(gsb.build().unwrap());
  637. let res =
  638. Page::from_file(nested_path.join("index.md").as_path(), &config, &path.to_path_buf());
  639. assert!(res.is_ok());
  640. let page = res.unwrap();
  641. assert_eq!(page.assets.len(), 1);
  642. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  643. }
  644. #[test]
  645. fn can_get_date_from_short_date_in_filename() {
  646. let config = Config::default();
  647. let content = r#"
  648. +++
  649. +++
  650. Hello world
  651. <!-- more -->"#
  652. .to_string();
  653. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  654. assert!(res.is_ok());
  655. let page = res.unwrap();
  656. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  657. assert_eq!(page.slug, "hello");
  658. }
  659. #[test]
  660. fn can_get_date_from_full_rfc3339_date_in_filename() {
  661. let config = Config::default();
  662. let content = r#"
  663. +++
  664. +++
  665. Hello world
  666. <!-- more -->"#
  667. .to_string();
  668. let res = Page::parse(
  669. Path::new("2018-10-02T15:00:00Z-hello.md"),
  670. &content,
  671. &config,
  672. &PathBuf::new(),
  673. );
  674. assert!(res.is_ok());
  675. let page = res.unwrap();
  676. assert_eq!(page.meta.date, Some("2018-10-02T15:00:00Z".to_string()));
  677. assert_eq!(page.slug, "hello");
  678. }
  679. #[test]
  680. fn frontmatter_date_override_filename_date() {
  681. let config = Config::default();
  682. let content = r#"
  683. +++
  684. date = 2018-09-09
  685. +++
  686. Hello world
  687. <!-- more -->"#
  688. .to_string();
  689. let res = Page::parse(Path::new("2018-10-08_hello.md"), &content, &config, &PathBuf::new());
  690. assert!(res.is_ok());
  691. let page = res.unwrap();
  692. assert_eq!(page.meta.date, Some("2018-09-09".to_string()));
  693. assert_eq!(page.slug, "hello");
  694. }
  695. #[test]
  696. fn can_specify_language_in_filename() {
  697. let mut config = Config::default();
  698. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  699. let content = r#"
  700. +++
  701. +++
  702. Bonjour le monde"#
  703. .to_string();
  704. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  705. assert!(res.is_ok());
  706. let page = res.unwrap();
  707. assert_eq!(page.lang, "fr".to_string());
  708. assert_eq!(page.slug, "hello");
  709. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  710. }
  711. #[test]
  712. fn can_specify_language_in_filename_with_date() {
  713. let mut config = Config::default();
  714. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  715. let content = r#"
  716. +++
  717. +++
  718. Bonjour le monde"#
  719. .to_string();
  720. let res =
  721. Page::parse(Path::new("2018-10-08_hello.fr.md"), &content, &config, &PathBuf::new());
  722. assert!(res.is_ok());
  723. let page = res.unwrap();
  724. assert_eq!(page.meta.date, Some("2018-10-08".to_string()));
  725. assert_eq!(page.lang, "fr".to_string());
  726. assert_eq!(page.slug, "hello");
  727. assert_eq!(page.permalink, "http://a-website.com/fr/hello/");
  728. }
  729. #[test]
  730. fn i18n_frontmatter_path_overrides_default_permalink() {
  731. let mut config = Config::default();
  732. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  733. let content = r#"
  734. +++
  735. path = "bonjour"
  736. +++
  737. Bonjour le monde"#
  738. .to_string();
  739. let res = Page::parse(Path::new("hello.fr.md"), &content, &config, &PathBuf::new());
  740. assert!(res.is_ok());
  741. let page = res.unwrap();
  742. assert_eq!(page.lang, "fr".to_string());
  743. assert_eq!(page.slug, "hello");
  744. assert_eq!(page.permalink, "http://a-website.com/bonjour/");
  745. }
  746. }