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.

289 lines
11KB

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