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.

346 lines
12KB

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