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.

317 lines
12KB

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