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.

293 lines
11KB

  1. use std::collections::HashMap;
  2. use std::path::{Path, PathBuf};
  3. use tera::{Tera, Context as TeraContext};
  4. use slotmap::Key;
  5. use config::Config;
  6. use front_matter::{SectionFrontMatter, split_section_content};
  7. use errors::{Result, ResultExt};
  8. use utils::fs::{read_file, find_related_assets};
  9. use utils::templates::render_template;
  10. use utils::site::get_reading_analytics;
  11. use rendering::{RenderContext, Header, render_content};
  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. }
  51. impl Section {
  52. pub fn new<P: AsRef<Path>>(file_path: P, meta: SectionFrontMatter) -> Section {
  53. let file_path = file_path.as_ref();
  54. Section {
  55. file: FileInfo::new_section(file_path),
  56. meta,
  57. ancestors: vec![],
  58. path: "".to_string(),
  59. components: vec![],
  60. permalink: "".to_string(),
  61. raw_content: "".to_string(),
  62. assets: vec![],
  63. serialized_assets: vec![],
  64. content: "".to_string(),
  65. pages: vec![],
  66. ignored_pages: vec![],
  67. subsections: vec![],
  68. toc: vec![],
  69. word_count: None,
  70. reading_time: None,
  71. }
  72. }
  73. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  74. let (meta, content) = split_section_content(file_path, content)?;
  75. let mut section = Section::new(file_path, meta);
  76. section.raw_content = content.clone();
  77. let (word_count, reading_time) = get_reading_analytics(&section.raw_content);
  78. section.word_count = Some(word_count);
  79. section.reading_time = Some(reading_time);
  80. section.path = format!("{}/", section.file.components.join("/"));
  81. section.components = section.path.split('/')
  82. .map(|p| p.to_string())
  83. .filter(|p| !p.is_empty())
  84. .collect::<Vec<_>>();
  85. section.permalink = config.make_permalink(&section.path);
  86. Ok(section)
  87. }
  88. /// Read and parse a .md file into a Page struct
  89. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  90. let path = path.as_ref();
  91. let content = read_file(path)?;
  92. let mut section = Section::parse(path, &content, config)?;
  93. let parent_dir = path.parent().unwrap();
  94. let assets = find_related_assets(parent_dir);
  95. if let Some(ref globset) = config.ignored_content_globset {
  96. // `find_related_assets` only scans the immediate directory (it is not recursive) so our
  97. // filtering only needs to work against the file_name component, not the full suffix. If
  98. // `find_related_assets` was changed to also return files in subdirectories, we could
  99. // use `PathBuf.strip_prefix` to remove the parent directory and then glob-filter
  100. // against the remaining path. Note that the current behaviour effectively means that
  101. // the `ignored_content` setting in the config file is limited to single-file glob
  102. // patterns (no "**" patterns).
  103. section.assets = assets.into_iter()
  104. .filter(|path|
  105. match path.file_name() {
  106. None => true,
  107. Some(file) => !globset.is_match(file)
  108. }
  109. ).collect();
  110. } else {
  111. section.assets = assets;
  112. }
  113. section.serialized_assets = section.serialize_assets();
  114. Ok(section)
  115. }
  116. pub fn get_template_name(&self) -> String {
  117. match self.meta.template {
  118. Some(ref l) => l.to_string(),
  119. None => {
  120. if self.is_index() {
  121. return "index.html".to_string();
  122. }
  123. "section.html".to_string()
  124. }
  125. }
  126. }
  127. /// We need access to all pages url to render links relative to content
  128. /// so that can't happen at the same time as parsing
  129. pub fn render_markdown(
  130. &mut self,
  131. permalinks: &HashMap<String, String>,
  132. tera: &Tera,
  133. config: &Config,
  134. ) -> Result<()> {
  135. let mut context = RenderContext::new(
  136. tera,
  137. config,
  138. &self.permalink,
  139. permalinks,
  140. self.meta.insert_anchor_links,
  141. );
  142. context.tera_context.insert("section", &SerializingSection::from_section_basic(self, None));
  143. let res = render_content(&self.raw_content, &context)
  144. .chain_err(|| format!("Failed to render content of {}", self.file.path.display()))?;
  145. self.content = res.body;
  146. self.toc = res.toc;
  147. Ok(())
  148. }
  149. /// Renders the page using the default layout, unless specified in front-matter
  150. pub fn render_html(&self, tera: &Tera, config: &Config, library: &Library) -> Result<String> {
  151. let tpl_name = self.get_template_name();
  152. let mut context = TeraContext::new();
  153. context.insert("config", config);
  154. context.insert("current_url", &self.permalink);
  155. context.insert("current_path", &self.path);
  156. context.insert("section", &self.to_serialized(library));
  157. render_template(&tpl_name, tera, &context, &config.theme)
  158. .chain_err(|| format!("Failed to render section '{}'", self.file.path.display()))
  159. }
  160. /// Is this the index section?
  161. pub fn is_index(&self) -> bool {
  162. self.file.components.is_empty()
  163. }
  164. /// Creates a vectors of asset URLs.
  165. fn serialize_assets(&self) -> Vec<String> {
  166. self.assets.iter()
  167. .filter_map(|asset| asset.file_name())
  168. .filter_map(|filename| filename.to_str())
  169. .map(|filename| self.path.clone() + filename)
  170. .collect()
  171. }
  172. pub fn to_serialized<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  173. SerializingSection::from_section(self, library)
  174. }
  175. pub fn to_serialized_basic<'a>(&'a self, library: &'a Library) -> SerializingSection<'a> {
  176. SerializingSection::from_section_basic(self, Some(library))
  177. }
  178. }
  179. /// Used to create a default index section if there is no _index.md in the root content directory
  180. impl Default for Section {
  181. fn default() -> Section {
  182. Section {
  183. file: FileInfo::default(),
  184. meta: SectionFrontMatter::default(),
  185. ancestors: vec![],
  186. path: "".to_string(),
  187. components: vec![],
  188. permalink: "".to_string(),
  189. raw_content: "".to_string(),
  190. assets: vec![],
  191. serialized_assets: vec![],
  192. content: "".to_string(),
  193. pages: vec![],
  194. ignored_pages: vec![],
  195. subsections: vec![],
  196. toc: vec![],
  197. reading_time: None,
  198. word_count: None,
  199. }
  200. }
  201. }
  202. #[cfg(test)]
  203. mod tests {
  204. use std::io::Write;
  205. use std::fs::{File, create_dir};
  206. use tempfile::tempdir;
  207. use globset::{Glob, GlobSetBuilder};
  208. use config::Config;
  209. use super::Section;
  210. #[test]
  211. fn section_with_assets_gets_right_info() {
  212. let tmp_dir = tempdir().expect("create temp dir");
  213. let path = tmp_dir.path();
  214. create_dir(&path.join("content")).expect("create content temp dir");
  215. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  216. let nested_path = path.join("content").join("posts").join("with-assets");
  217. create_dir(&nested_path).expect("create nested temp dir");
  218. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  219. f.write_all(b"+++\n+++\n").unwrap();
  220. File::create(nested_path.join("example.js")).unwrap();
  221. File::create(nested_path.join("graph.jpg")).unwrap();
  222. File::create(nested_path.join("fail.png")).unwrap();
  223. let res = Section::from_file(
  224. nested_path.join("_index.md").as_path(),
  225. &Config::default(),
  226. );
  227. assert!(res.is_ok());
  228. let section = res.unwrap();
  229. assert_eq!(section.assets.len(), 3);
  230. assert_eq!(section.permalink, "http://a-website.com/posts/with-assets/");
  231. }
  232. #[test]
  233. fn section_with_ignored_assets_filters_out_correct_files() {
  234. let tmp_dir = tempdir().expect("create temp dir");
  235. let path = tmp_dir.path();
  236. create_dir(&path.join("content")).expect("create content temp dir");
  237. create_dir(&path.join("content").join("posts")).expect("create posts temp dir");
  238. let nested_path = path.join("content").join("posts").join("with-assets");
  239. create_dir(&nested_path).expect("create nested temp dir");
  240. let mut f = File::create(nested_path.join("_index.md")).unwrap();
  241. f.write_all(b"+++\nslug=\"hey\"\n+++\n").unwrap();
  242. File::create(nested_path.join("example.js")).unwrap();
  243. File::create(nested_path.join("graph.jpg")).unwrap();
  244. File::create(nested_path.join("fail.png")).unwrap();
  245. let mut gsb = GlobSetBuilder::new();
  246. gsb.add(Glob::new("*.{js,png}").unwrap());
  247. let mut config = Config::default();
  248. config.ignored_content_globset = Some(gsb.build().unwrap());
  249. let res = Section::from_file(
  250. nested_path.join("_index.md").as_path(),
  251. &config,
  252. );
  253. assert!(res.is_ok());
  254. let page = res.unwrap();
  255. assert_eq!(page.assets.len(), 1);
  256. assert_eq!(page.assets[0].file_name().unwrap().to_str(), Some("graph.jpg"));
  257. }
  258. }