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 14KB

6 years ago
6 years ago
6 years ago
5 years ago
7 years ago
5 years ago
6 years ago
6 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
6 years ago
5 years ago
6 years ago
6 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. use std::collections::HashMap;
  2. use std::path::{Path, PathBuf};
  3. use slotmap::Key;
  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, Header, 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 content::file_info::FileInfo;
  13. use content::has_anchor;
  14. use content::ser::SerializingSection;
  15. use 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<Key>,
  38. /// All pages that cannot be sorted in this section
  39. pub ignored_pages: Vec<Key>,
  40. /// The list of parent sections
  41. pub ancestors: Vec<Key>,
  42. /// All direct subsections
  43. pub subsections: Vec<Key>,
  44. /// Toc made from the headers of the markdown file
  45. pub toc: Vec<Header>,
  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<Key>,
  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. section.path = format!("{}/{}", section.lang, path);
  110. } else {
  111. section.path = format!("{}/", path);
  112. }
  113. section.components = section
  114. .path
  115. .split('/')
  116. .map(|p| p.to_string())
  117. .filter(|p| !p.is_empty())
  118. .collect::<Vec<_>>();
  119. section.permalink = config.make_permalink(&section.path);
  120. Ok(section)
  121. }
  122. /// Read and parse a .md file into a Page struct
  123. pub fn from_file<P: AsRef<Path>>(
  124. path: P,
  125. config: &Config,
  126. base_path: &PathBuf,
  127. ) -> Result<Section> {
  128. let path = path.as_ref();
  129. let content = read_file(path)?;
  130. let mut section = Section::parse(path, &content, config, base_path)?;
  131. let parent_dir = path.parent().unwrap();
  132. let assets = find_related_assets(parent_dir);
  133. if let Some(ref globset) = config.ignored_content_globset {
  134. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  135. // filtering only needs to work against the file_name component, not the full suffix. If
  136. // `find_related_assets` was changed to also return files in subdirectories, we could
  137. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  138. // against the remaining path. Note that the current behaviour effectively means that
  139. // the `ignored_content` setting in the config file is limited to single-file glob
  140. // patterns (no "**" patterns).
  141. section.assets = assets
  142. .into_iter()
  143. .filter(|path| match path.file_name() {
  144. None => true,
  145. Some(file) => !globset.is_match(file),
  146. })
  147. .collect();
  148. } else {
  149. section.assets = assets;
  150. }
  151. section.serialized_assets = section.serialize_assets();
  152. Ok(section)
  153. }
  154. pub fn get_template_name(&self) -> &str {
  155. match self.meta.template {
  156. Some(ref l) => l,
  157. None => {
  158. if self.is_index() {
  159. return "index.html";
  160. }
  161. "section.html"
  162. }
  163. }
  164. }
  165. /// We need access to all pages url to render links relative to content
  166. /// so that can't happen at the same time as parsing
  167. pub fn render_markdown(
  168. &mut self,
  169. permalinks: &HashMap<String, String>,
  170. tera: &Tera,
  171. config: &Config,
  172. ) -> Result<()> {
  173. let mut context = RenderContext::new(
  174. tera,
  175. config,
  176. &self.permalink,
  177. permalinks,
  178. self.meta.insert_anchor_links,
  179. );
  180. context.tera_context.insert("section", &SerializingSection::from_section_basic(self, None));
  181. let res = render_content(&self.raw_content, &context).map_err(|e| {
  182. Error::chain(format!("Failed to render content of {}", self.file.path.display()), e)
  183. })?;
  184. self.content = res.body;
  185. self.toc = res.toc;
  186. self.external_links = res.external_links;
  187. self.internal_links_with_anchors = res.internal_links_with_anchors;
  188. Ok(())
  189. }
  190. /// Renders the page using the default layout, unless specified in front-matter
  191. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  192. let tpl_name = self.get_template_name();
  193. let mut context = TeraContext::new();
  194. context.insert("config", config);
  195. context.insert("current_url", &self.permalink);
  196. context.insert("current_path", &self.path);
  197. context.insert("section", &self.to_serialized(library));
  198. context.insert("lang", &self.lang);
  199. context.insert("toc", &self.toc);
  200. render_template(tpl_name, tera, context, &config.theme).map_err(|e| {
  201. Error::chain(format!("Failed to render section '{}'", self.file.path.display()), e)
  202. })
  203. }
  204. /// Is this the index section?
  205. pub fn is_index(&self) -> bool {
  206. self.file.components.is_empty()
  207. }
  208. /// Creates a vectors of asset URLs.
  209. fn serialize_assets(&self) -> Vec<String> {
  210. self.assets
  211. .iter()
  212. .filter_map(|asset| asset.file_name())
  213. .filter_map(|filename| filename.to_str())
  214. .map(|filename| self.path.clone() + filename)
  215. .collect()
  216. }
  217. pub fn has_anchor(&self, anchor: &str) -> bool {
  218. has_anchor(&self.toc, anchor)
  219. }
  220. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  221. SerializingSection::from_section(self, library)
  222. }
  223. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  224. SerializingSection::from_section_basic(self, Some(library))
  225. }
  226. }
  227. /// Used to create a default index section if there is no _index.md in the root content directory
  228. impl Default for Section {
  229. fn default() -> Section {
  230. Section {
  231. file: FileInfo::default(),
  232. meta: SectionFrontMatter::default(),
  233. ancestors: vec![],
  234. path: "".to_string(),
  235. components: vec![],
  236. permalink: "".to_string(),
  237. raw_content: "".to_string(),
  238. assets: vec![],
  239. serialized_assets: vec![],
  240. content: "".to_string(),
  241. pages: vec![],
  242. ignored_pages: vec![],
  243. subsections: vec![],
  244. toc: vec![],
  245. reading_time: None,
  246. word_count: None,
  247. lang: String::new(),
  248. translations: Vec::new(),
  249. internal_links_with_anchors: Vec::new(),
  250. external_links: Vec::new(),
  251. }
  252. }
  253. }
  254. #[cfg(test)]
  255. mod tests {
  256. use std::fs::{create_dir, File};
  257. use std::io::Write;
  258. use std::path::{Path, PathBuf};
  259. use globset::{Glob, GlobSetBuilder};
  260. use tempfile::tempdir;
  261. use super::Section;
  262. use config::{Config, Language};
  263. #[test]
  264. fn section_with_assets_gets_right_info() {
  265. let tmp_dir = tempdir().expect("create temp dir");
  266. let path = tmp_dir.path();
  267. create_dir(&path.join("content")).expect("create content temp dir");
  268. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  269. let nested_path = path.join("content").join("posts").join("with-assets");
  270. create_dir(&nested_path).expect("create nested temp dir");
  271. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  272. f.write_all(b"+++\n+++\n").unwrap();
  273. File::create(nested_path.join("example.js")).unwrap();
  274. File::create(nested_path.join("graph.jpg")).unwrap();
  275. File::create(nested_path.join("fail.png")).unwrap();
  276. let res = Section::from_file(
  277. nested_path.join("_index.md").as_path(),
  278. &Config::default(),
  279. &PathBuf::new(),
  280. );
  281. assert!(res.is_ok());
  282. let section = res.unwrap();
  283. assert_eq!(section.assets.len(), 3);
  284. assert_eq!(section.permalink, "http://a-website.com/posts/with-assets/");
  285. }
  286. #[test]
  287. fn section_with_ignored_assets_filters_out_correct_files() {
  288. let tmp_dir = tempdir().expect("create temp dir");
  289. let path = tmp_dir.path();
  290. create_dir(&path.join("content")).expect("create content temp dir");
  291. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  292. let nested_path = path.join("content").join("posts").join("with-assets");
  293. create_dir(&nested_path).expect("create nested temp dir");
  294. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  295. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  296. File::create(nested_path.join("example.js")).unwrap();
  297. File::create(nested_path.join("graph.jpg")).unwrap();
  298. File::create(nested_path.join("fail.png")).unwrap();
  299. let mut gsb = GlobSetBuilder::new();
  300. gsb.add(Glob::new("*.{js,png}").unwrap());
  301. let mut config = Config::default();
  302. config.ignored_content_globset = Some(gsb.build().unwrap());
  303. let res =
  304. Section::from_file(nested_path.join("_index.md").as_path(), &config, &PathBuf::new());
  305. assert!(res.is_ok());
  306. let page = res.unwrap();
  307. assert_eq!(page.assets.len(), 1);
  308. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  309. }
  310. #[test]
  311. fn can_specify_language_in_filename() {
  312. let mut config = Config::default();
  313. config.languages.push(Language { code: String::from("fr"), rss: false });
  314. let content = r#"
  315. +++
  316. +++
  317. Bonjour le monde"#
  318. .to_string();
  319. let res = Section::parse(
  320. Path::new("content/hello/nested/_index.fr.md"),
  321. &content,
  322. &config,
  323. &PathBuf::new(),
  324. );
  325. assert!(res.is_ok());
  326. let section = res.unwrap();
  327. assert_eq!(section.lang, "fr".to_string());
  328. assert_eq!(section.permalink, "http://a-website.com/fr/hello/nested/");
  329. }
  330. // https://zola.discourse.group/t/rfc-i18n/13/17?u=keats
  331. #[test]
  332. fn can_make_links_to_translated_sections_without_double_trailing_slash() {
  333. let mut config = Config::default();
  334. config.languages.push(Language { code: String::from("fr"), rss: false });
  335. let content = r#"
  336. +++
  337. +++
  338. Bonjour le monde"#
  339. .to_string();
  340. let res =
  341. Section::parse(Path::new("content/_index.fr.md"), &content, &config, &PathBuf::new());
  342. assert!(res.is_ok());
  343. let section = res.unwrap();
  344. assert_eq!(section.lang, "fr".to_string());
  345. assert_eq!(section.permalink, "http://a-website.com/fr/");
  346. }
  347. }