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.

361 lines
13KB

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