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.

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