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.

410 lines
15KB

  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. 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 Page 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. context.insert("toc", &self.toc);
  204. render_template(tpl_name, tera, context, &config.theme).map_err(|e| {
  205. Error::chain(format!("Failed to render section '{}'", self.file.path.display()), e)
  206. })
  207. }
  208. /// Is this the index section?
  209. pub fn is_index(&self) -> bool {
  210. self.file.components.is_empty()
  211. }
  212. /// Creates a vectors of asset URLs.
  213. fn serialize_assets(&self) -> Vec<String> {
  214. self.assets
  215. .iter()
  216. .filter_map(|asset| asset.file_name())
  217. .filter_map(|filename| filename.to_str())
  218. .map(|filename| self.path.clone() + filename)
  219. .collect()
  220. }
  221. pub fn has_anchor(&self, anchor: &str) -> bool {
  222. has_anchor(&self.toc, anchor)
  223. }
  224. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  225. SerializingSection::from_section(self, library)
  226. }
  227. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  228. SerializingSection::from_section_basic(self, Some(library))
  229. }
  230. }
  231. /// Used to create a default index section if there is no _index.md in the root content directory
  232. impl Default for Section {
  233. fn default() -> Section {
  234. Section {
  235. file: FileInfo::default(),
  236. meta: SectionFrontMatter::default(),
  237. ancestors: vec![],
  238. path: "".to_string(),
  239. components: vec![],
  240. permalink: "".to_string(),
  241. raw_content: "".to_string(),
  242. assets: vec![],
  243. serialized_assets: vec![],
  244. content: "".to_string(),
  245. pages: vec![],
  246. ignored_pages: vec![],
  247. subsections: vec![],
  248. toc: vec![],
  249. reading_time: None,
  250. word_count: None,
  251. lang: String::new(),
  252. translations: Vec::new(),
  253. internal_links_with_anchors: Vec::new(),
  254. external_links: Vec::new(),
  255. }
  256. }
  257. }
  258. #[cfg(test)]
  259. mod tests {
  260. use std::fs::{create_dir, File};
  261. use std::io::Write;
  262. use std::path::{Path, PathBuf};
  263. use globset::{Glob, GlobSetBuilder};
  264. use tempfile::tempdir;
  265. use super::Section;
  266. use config::{Config, Language};
  267. #[test]
  268. fn section_with_assets_gets_right_info() {
  269. let tmp_dir = tempdir().expect("create temp dir");
  270. let path = tmp_dir.path();
  271. create_dir(&path.join("content")).expect("create content temp dir");
  272. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  273. let nested_path = path.join("content").join("posts").join("with-assets");
  274. create_dir(&nested_path).expect("create nested temp dir");
  275. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  276. f.write_all(b"+++\n+++\n").unwrap();
  277. File::create(nested_path.join("example.js")).unwrap();
  278. File::create(nested_path.join("graph.jpg")).unwrap();
  279. File::create(nested_path.join("fail.png")).unwrap();
  280. let res = Section::from_file(
  281. nested_path.join("_index.md").as_path(),
  282. &Config::default(),
  283. &PathBuf::new(),
  284. );
  285. assert!(res.is_ok());
  286. let section = res.unwrap();
  287. assert_eq!(section.assets.len(), 3);
  288. assert_eq!(section.permalink, "http://a-website.com/posts/with-assets/");
  289. }
  290. #[test]
  291. fn section_with_ignored_assets_filters_out_correct_files() {
  292. let tmp_dir = tempdir().expect("create temp dir");
  293. let path = tmp_dir.path();
  294. create_dir(&path.join("content")).expect("create content temp dir");
  295. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  296. let nested_path = path.join("content").join("posts").join("with-assets");
  297. create_dir(&nested_path).expect("create nested temp dir");
  298. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  299. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  300. File::create(nested_path.join("example.js")).unwrap();
  301. File::create(nested_path.join("graph.jpg")).unwrap();
  302. File::create(nested_path.join("fail.png")).unwrap();
  303. let mut gsb = GlobSetBuilder::new();
  304. gsb.add(Glob::new("*.{js,png}").unwrap());
  305. let mut config = Config::default();
  306. config.ignored_content_globset = Some(gsb.build().unwrap());
  307. let res =
  308. Section::from_file(nested_path.join("_index.md").as_path(), &config, &PathBuf::new());
  309. assert!(res.is_ok());
  310. let page = res.unwrap();
  311. assert_eq!(page.assets.len(), 1);
  312. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  313. }
  314. #[test]
  315. fn can_specify_language_in_filename() {
  316. let mut config = Config::default();
  317. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  318. let content = r#"
  319. +++
  320. +++
  321. Bonjour le monde"#
  322. .to_string();
  323. let res = Section::parse(
  324. Path::new("content/hello/nested/_index.fr.md"),
  325. &content,
  326. &config,
  327. &PathBuf::new(),
  328. );
  329. assert!(res.is_ok());
  330. let section = res.unwrap();
  331. assert_eq!(section.lang, "fr".to_string());
  332. assert_eq!(section.permalink, "http://a-website.com/fr/hello/nested/");
  333. }
  334. // https://zola.discourse.group/t/rfc-i18n/13/17?u=keats
  335. #[test]
  336. fn can_make_links_to_translated_sections_without_double_trailing_slash() {
  337. let mut config = Config::default();
  338. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  339. let content = r#"
  340. +++
  341. +++
  342. Bonjour le monde"#
  343. .to_string();
  344. let res =
  345. Section::parse(Path::new("content/_index.fr.md"), &content, &config, &PathBuf::new());
  346. assert!(res.is_ok());
  347. let section = res.unwrap();
  348. assert_eq!(section.lang, "fr".to_string());
  349. assert_eq!(section.permalink, "http://a-website.com/fr/");
  350. }
  351. #[test]
  352. fn can_make_links_to_translated_subsections_with_trailing_slash() {
  353. let mut config = Config::default();
  354. config.languages.push(Language { code: String::from("fr"), rss: false, search: false });
  355. let content = r#"
  356. +++
  357. +++
  358. Bonjour le monde"#
  359. .to_string();
  360. let res = Section::parse(
  361. Path::new("content/subcontent/_index.fr.md"),
  362. &content,
  363. &config,
  364. &PathBuf::new(),
  365. );
  366. assert!(res.is_ok());
  367. let section = res.unwrap();
  368. assert_eq!(section.lang, "fr".to_string());
  369. assert_eq!(section.permalink, "http://a-website.com/fr/subcontent/");
  370. }
  371. }