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.

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