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.

section.rs 15KB

4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
7 years ago
5 years ago
5 years ago
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. use std::collections::HashMap;
  2. use std::path::{Path, PathBuf};
  3. use slotmap::DefaultKey;
  4. use tera::{Context as TeraContext, Tera};
  5. use config::Config;
  6. use errors::{Error, Result};
  7. use front_matter::{split_section_content, SectionFrontMatter};
  8. use rendering::{render_content, Heading, RenderContext};
  9. use utils::fs::{find_related_assets, read_file};
  10. use utils::site::get_reading_analytics;
  11. use utils::templates::render_template;
  12. use crate::content::file_info::FileInfo;
  13. use crate::content::has_anchor;
  14. use crate::content::ser::SerializingSection;
  15. use crate::library::Library;
  16. #[derive(Clone, Debug, PartialEq)]
  17. pub struct Section {
  18. /// All info about the actual file
  19. pub file: FileInfo,
  20. /// The front matter meta-data
  21. pub meta: SectionFrontMatter,
  22. /// The URL path of the page
  23. pub path: String,
  24. /// The components for the path of that page
  25. pub components: Vec<String>,
  26. /// The full URL for that page
  27. pub permalink: String,
  28. /// The actual content of the page, in markdown
  29. pub raw_content: String,
  30. /// The HTML rendered of the page
  31. pub content: String,
  32. /// All the non-md files we found next to the .md file
  33. pub assets: Vec<PathBuf>,
  34. /// All the non-md files we found next to the .md file as string for use in templates
  35. pub serialized_assets: Vec<String>,
  36. /// All direct pages of that section
  37. pub pages: Vec<DefaultKey>,
  38. /// All pages that cannot be sorted in this section
  39. pub ignored_pages: Vec<DefaultKey>,
  40. /// The list of parent sections
  41. pub ancestors: Vec<DefaultKey>,
  42. /// All direct subsections
  43. pub subsections: Vec<DefaultKey>,
  44. /// Toc made from the headings of the markdown file
  45. pub toc: Vec<Heading>,
  46. /// How many words in the raw content
  47. pub word_count: Option<usize>,
  48. /// How long would it take to read the raw content.
  49. /// See `get_reading_analytics` on how it is calculated
  50. pub reading_time: Option<usize>,
  51. /// The language of that section. Equal to the default lang if the user doesn't setup `languages` in config.
  52. /// Corresponds to the lang in the _index.{lang}.md file scheme
  53. pub lang: String,
  54. /// Contains all the translated version of that section
  55. pub translations: Vec<DefaultKey>,
  56. /// Contains the internal links that have an anchor: we can only check the anchor
  57. /// after all pages have been built and their ToC compiled. The page itself should exist otherwise
  58. /// it would have errored before getting there
  59. /// (path to markdown, anchor value)
  60. pub internal_links_with_anchors: Vec<(String, String)>,
  61. /// Contains the external links that need to be checked
  62. pub external_links: Vec<String>,
  63. }
  64. impl Section {
  65. pub fn new<P: AsRef<Path>>(
  66. file_path: P,
  67. meta: SectionFrontMatter,
  68. base_path: &PathBuf,
  69. ) -> Section {
  70. let file_path = file_path.as_ref();
  71. Section {
  72. file: FileInfo::new_section(file_path, base_path),
  73. meta,
  74. ancestors: vec![],
  75. path: "".to_string(),
  76. components: vec![],
  77. permalink: "".to_string(),
  78. raw_content: "".to_string(),
  79. assets: vec![],
  80. serialized_assets: vec![],
  81. content: "".to_string(),
  82. pages: vec![],
  83. ignored_pages: vec![],
  84. subsections: vec![],
  85. toc: vec![],
  86. word_count: None,
  87. reading_time: None,
  88. lang: String::new(),
  89. translations: Vec::new(),
  90. internal_links_with_anchors: Vec::new(),
  91. external_links: Vec::new(),
  92. }
  93. }
  94. pub fn parse(
  95. file_path: &Path,
  96. content: &str,
  97. config: &Config,
  98. base_path: &PathBuf,
  99. ) -> Result<Section> {
  100. let (meta, content) = split_section_content(file_path, content)?;
  101. let mut section = Section::new(file_path, meta, base_path);
  102. section.lang = section.file.find_language(config)?;
  103. section.raw_content = content;
  104. let (word_count, reading_time) = get_reading_analytics(&section.raw_content);
  105. section.word_count = Some(word_count);
  106. section.reading_time = Some(reading_time);
  107. let path = section.file.components.join("/");
  108. if section.lang != config.default_language {
  109. if path.is_empty() {
  110. section.path = format!("{}/", section.lang);
  111. } else {
  112. section.path = format!("{}/{}/", section.lang, path);
  113. }
  114. } else {
  115. section.path = format!("{}/", path);
  116. }
  117. section.components = section
  118. .path
  119. .split('/')
  120. .map(|p| p.to_string())
  121. .filter(|p| !p.is_empty())
  122. .collect::<Vec<_>>();
  123. section.permalink = config.make_permalink(&section.path);
  124. Ok(section)
  125. }
  126. /// Read and parse a .md file into a Section struct
  127. pub fn from_file<P: AsRef<Path>>(
  128. path: P,
  129. config: &Config,
  130. base_path: &PathBuf,
  131. ) -> Result<Section> {
  132. let path = path.as_ref();
  133. let content = read_file(path)?;
  134. let mut section = Section::parse(path, &content, config, base_path)?;
  135. let parent_dir = path.parent().unwrap();
  136. let assets = find_related_assets(parent_dir);
  137. if let Some(ref globset) = config.ignored_content_globset {
  138. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  139. // filtering only needs to work against the file_name component, not the full suffix. If
  140. // `find_related_assets` was changed to also return files in subdirectories, we could
  141. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  142. // against the remaining path. Note that the current behaviour effectively means that
  143. // the `ignored_content` setting in the config file is limited to single-file glob
  144. // patterns (no "**" patterns).
  145. section.assets = assets
  146. .into_iter()
  147. .filter(|path| match path.file_name() {
  148. None => true,
  149. Some(file) => !globset.is_match(file),
  150. })
  151. .collect();
  152. } else {
  153. section.assets = assets;
  154. }
  155. section.serialized_assets = section.serialize_assets();
  156. Ok(section)
  157. }
  158. pub fn get_template_name(&self) -> &str {
  159. match self.meta.template {
  160. Some(ref l) => l,
  161. None => {
  162. if self.is_index() {
  163. return "index.html";
  164. }
  165. "section.html"
  166. }
  167. }
  168. }
  169. /// We need access to all pages url to render links relative to content
  170. /// so that can't happen at the same time as parsing
  171. pub fn render_markdown(
  172. &mut self,
  173. permalinks: &HashMap<String, String>,
  174. tera: &Tera,
  175. config: &Config,
  176. ) -> Result<()> {
  177. let mut context = RenderContext::new(
  178. tera,
  179. config,
  180. &self.permalink,
  181. permalinks,
  182. self.meta.insert_anchor_links,
  183. );
  184. context.tera_context.insert("section", &SerializingSection::from_section_basic(self, None));
  185. let res = render_content(&self.raw_content, &context).map_err(|e| {
  186. Error::chain(format!("Failed to render content of {}", self.file.path.display()), e)
  187. })?;
  188. self.content = res.body;
  189. self.toc = res.toc;
  190. self.external_links = res.external_links;
  191. self.internal_links_with_anchors = res.internal_links_with_anchors;
  192. Ok(())
  193. }
  194. /// Renders the page using the default layout, unless specified in front-matter
  195. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  196. let tpl_name = self.get_template_name();
  197. let mut context = TeraContext::new();
  198. context.insert("config", config);
  199. context.insert("current_url", &self.permalink);
  200. context.insert("current_path", &self.path);
  201. context.insert("section", &self.to_serialized(library));
  202. context.insert("lang", &self.lang);
  203. render_template(tpl_name, tera, context, &config.theme).map_err(|e| {
  204. Error::chain(format!("Failed to render section '{}'", self.file.path.display()), e)
  205. })
  206. }
  207. /// Is this the index section?
  208. pub fn is_index(&self) -> bool {
  209. self.file.components.is_empty()
  210. }
  211. /// Creates a vectors of asset URLs.
  212. fn serialize_assets(&self) -> Vec<String> {
  213. self.assets
  214. .iter()
  215. .filter_map(|asset| asset.file_name())
  216. .filter_map(|filename| filename.to_str())
  217. .map(|filename| self.path.clone() + filename)
  218. .collect()
  219. }
  220. pub fn has_anchor(&self, anchor: &str) -> bool {
  221. has_anchor(&self.toc, anchor)
  222. }
  223. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  224. SerializingSection::from_section(self, library)
  225. }
  226. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  227. SerializingSection::from_section_basic(self, Some(library))
  228. }
  229. }
  230. /// Used to create a default index section if there is no _index.md in the root content directory
  231. impl Default for Section {
  232. fn default() -> Section {
  233. Section {
  234. file: FileInfo::default(),
  235. meta: SectionFrontMatter::default(),
  236. ancestors: vec![],
  237. path: "".to_string(),
  238. components: vec![],
  239. permalink: "".to_string(),
  240. raw_content: "".to_string(),
  241. assets: vec![],
  242. serialized_assets: vec![],
  243. content: "".to_string(),
  244. pages: vec![],
  245. ignored_pages: vec![],
  246. subsections: vec![],
  247. toc: vec![],
  248. reading_time: None,
  249. word_count: None,
  250. lang: String::new(),
  251. translations: Vec::new(),
  252. internal_links_with_anchors: Vec::new(),
  253. external_links: Vec::new(),
  254. }
  255. }
  256. }
  257. #[cfg(test)]
  258. mod tests {
  259. use std::fs::{create_dir, File};
  260. use std::io::Write;
  261. use std::path::{Path, PathBuf};
  262. use globset::{Glob, GlobSetBuilder};
  263. use tempfile::tempdir;
  264. use super::Section;
  265. use config::{Config, Language};
  266. #[test]
  267. fn section_with_assets_gets_right_info() {
  268. let tmp_dir = tempdir().expect("create temp dir");
  269. let path = tmp_dir.path();
  270. create_dir(&path.join("content")).expect("create content temp dir");
  271. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  272. let nested_path = path.join("content").join("posts").join("with-assets");
  273. create_dir(&nested_path).expect("create nested temp dir");
  274. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  275. f.write_all(b"+++\n+++\n").unwrap();
  276. File::create(nested_path.join("example.js")).unwrap();
  277. File::create(nested_path.join("graph.jpg")).unwrap();
  278. File::create(nested_path.join("fail.png")).unwrap();
  279. let res = Section::from_file(
  280. nested_path.join("_index.md").as_path(),
  281. &Config::default(),
  282. &PathBuf::new(),
  283. );
  284. assert!(res.is_ok());
  285. let section = res.unwrap();
  286. assert_eq!(section.assets.len(), 3);
  287. assert_eq!(section.permalink, "http://a-website.com/posts/with-assets/");
  288. }
  289. #[test]
  290. fn section_with_ignored_assets_filters_out_correct_files() {
  291. let tmp_dir = tempdir().expect("create temp dir");
  292. let path = tmp_dir.path();
  293. create_dir(&path.join("content")).expect("create content temp dir");
  294. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  295. let nested_path = path.join("content").join("posts").join("with-assets");
  296. create_dir(&nested_path).expect("create nested temp dir");
  297. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  298. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  299. File::create(nested_path.join("example.js")).unwrap();
  300. File::create(nested_path.join("graph.jpg")).unwrap();
  301. File::create(nested_path.join("fail.png")).unwrap();
  302. let mut gsb = GlobSetBuilder::new();
  303. gsb.add(Glob::new("*.{js,png}").unwrap());
  304. let mut config = Config::default();
  305. config.ignored_content_globset = Some(gsb.build().unwrap());
  306. let res =
  307. Section::from_file(nested_path.join("_index.md").as_path(), &config, &PathBuf::new());
  308. assert!(res.is_ok());
  309. let page = res.unwrap();
  310. assert_eq!(page.assets.len(), 1);
  311. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  312. }
  313. #[test]
  314. fn can_specify_language_in_filename() {
  315. let mut config = Config::default();
  316. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  317. let content = r#"
  318. +++
  319. +++
  320. Bonjour le monde"#
  321. .to_string();
  322. let res = Section::parse(
  323. Path::new("content/hello/nested/_index.fr.md"),
  324. &content,
  325. &config,
  326. &PathBuf::new(),
  327. );
  328. assert!(res.is_ok());
  329. let section = res.unwrap();
  330. assert_eq!(section.lang, "fr".to_string());
  331. assert_eq!(section.permalink, "http://a-website.com/fr/hello/nested/");
  332. }
  333. // https://zola.discourse.group/t/rfc-i18n/13/17?u=keats
  334. #[test]
  335. fn can_make_links_to_translated_sections_without_double_trailing_slash() {
  336. let mut config = Config::default();
  337. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  338. let content = r#"
  339. +++
  340. +++
  341. Bonjour le monde"#
  342. .to_string();
  343. let res =
  344. Section::parse(Path::new("content/_index.fr.md"), &content, &config, &PathBuf::new());
  345. assert!(res.is_ok());
  346. let section = res.unwrap();
  347. assert_eq!(section.lang, "fr".to_string());
  348. assert_eq!(section.permalink, "http://a-website.com/fr/");
  349. }
  350. #[test]
  351. fn can_make_links_to_translated_subsections_with_trailing_slash() {
  352. let mut config = Config::default();
  353. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  354. let content = r#"
  355. +++
  356. +++
  357. Bonjour le monde"#
  358. .to_string();
  359. let res = Section::parse(
  360. Path::new("content/subcontent/_index.fr.md"),
  361. &content,
  362. &config,
  363. &PathBuf::new(),
  364. );
  365. assert!(res.is_ok());
  366. let section = res.unwrap();
  367. assert_eq!(section.lang, "fr".to_string());
  368. assert_eq!(section.permalink, "http://a-website.com/fr/subcontent/");
  369. }
  370. }