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.

page.rs 29KB

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