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.

366 lines
13KB

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