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.

189 lines
6.4KB

  1. use std::collections::HashMap;
  2. use std::path::{Path, PathBuf};
  3. use std::result::Result as StdResult;
  4. use tera::{Tera, Context};
  5. use serde::ser::{SerializeStruct, self};
  6. use config::Config;
  7. use front_matter::{SectionFrontMatter, split_section_content};
  8. use errors::{Result, ResultExt};
  9. use utils::{read_file, find_content_components};
  10. use markdown::markdown_to_html;
  11. use page::{Page};
  12. #[derive(Clone, Debug, PartialEq)]
  13. pub struct Section {
  14. /// The front matter meta-data
  15. pub meta: SectionFrontMatter,
  16. /// The _index.md full path
  17. pub file_path: PathBuf,
  18. /// The .md path, starting from the content directory, with / slashes
  19. pub relative_path: String,
  20. /// Path of the directory containing the _index.md file
  21. pub parent_path: PathBuf,
  22. /// The folder names from `content` to this section file
  23. pub components: Vec<String>,
  24. /// The URL path of the page
  25. pub path: String,
  26. /// The full URL for that page
  27. pub permalink: String,
  28. /// The actual content of the page, in markdown
  29. pub raw_content: String,
  30. /// The HTML rendered of the page
  31. pub content: String,
  32. /// All direct pages of that section
  33. pub pages: Vec<Page>,
  34. /// All pages that cannot be sorted in this section
  35. pub ignored_pages: Vec<Page>,
  36. /// All direct subsections
  37. pub subsections: Vec<Section>,
  38. }
  39. impl Section {
  40. pub fn new<P: AsRef<Path>>(file_path: P, meta: SectionFrontMatter) -> Section {
  41. let file_path = file_path.as_ref();
  42. Section {
  43. meta: meta,
  44. file_path: file_path.to_path_buf(),
  45. relative_path: "".to_string(),
  46. parent_path: file_path.parent().unwrap().to_path_buf(),
  47. components: vec![],
  48. path: "".to_string(),
  49. permalink: "".to_string(),
  50. raw_content: "".to_string(),
  51. content: "".to_string(),
  52. pages: vec![],
  53. ignored_pages: vec![],
  54. subsections: vec![],
  55. }
  56. }
  57. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  58. let (meta, content) = split_section_content(file_path, content)?;
  59. let mut section = Section::new(file_path, meta);
  60. section.raw_content = content.clone();
  61. section.components = find_content_components(&section.file_path);
  62. section.path = section.components.join("/");
  63. section.permalink = config.make_permalink(&section.path);
  64. if section.components.is_empty() {
  65. // the index one
  66. section.relative_path = "_index.md".to_string();
  67. } else {
  68. section.relative_path = format!("{}/_index.md", section.components.join("/"));
  69. }
  70. Ok(section)
  71. }
  72. /// Read and parse a .md file into a Page struct
  73. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  74. let path = path.as_ref();
  75. let content = read_file(path)?;
  76. Section::parse(path, &content, config)
  77. }
  78. pub fn get_template_name(&self) -> String {
  79. match self.meta.template {
  80. Some(ref l) => l.to_string(),
  81. None => {
  82. if self.is_index() {
  83. return "index.html".to_string();
  84. }
  85. "section.html".to_string()
  86. },
  87. }
  88. }
  89. /// We need access to all pages url to render links relative to content
  90. /// so that can't happen at the same time as parsing
  91. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config) -> Result<()> {
  92. self.content = markdown_to_html(&self.raw_content, permalinks, tera, config)?;
  93. Ok(())
  94. }
  95. /// Renders the page using the default layout, unless specified in front-matter
  96. pub fn render_html(&self, sections: HashMap<String, Section>, tera: &Tera, config: &Config) -> Result<String> {
  97. let tpl_name = self.get_template_name();
  98. let mut context = Context::new();
  99. context.add("config", config);
  100. context.add("section", self);
  101. context.add("current_url", &self.permalink);
  102. context.add("current_path", &self.path);
  103. if self.is_index() {
  104. context.add("sections", &sections);
  105. }
  106. tera.render(&tpl_name, &context)
  107. .chain_err(|| format!("Failed to render section '{}'", self.file_path.display()))
  108. }
  109. /// Is this the index section?
  110. pub fn is_index(&self) -> bool {
  111. self.components.is_empty()
  112. }
  113. /// Returns all the paths for the pages belonging to that section
  114. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  115. let mut paths = vec![];
  116. paths.extend(self.pages.iter().map(|p| p.file_path.clone()));
  117. paths.extend(self.ignored_pages.iter().map(|p| p.file_path.clone()));
  118. paths
  119. }
  120. /// Whether the page given belongs to that section
  121. pub fn is_child_page(&self, page: &Page) -> bool {
  122. for p in &self.pages {
  123. if p.file_path == page.file_path {
  124. return true;
  125. }
  126. }
  127. for p in &self.ignored_pages {
  128. if p.file_path == page.file_path {
  129. return true;
  130. }
  131. }
  132. false
  133. }
  134. }
  135. impl ser::Serialize for Section {
  136. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  137. let mut state = serializer.serialize_struct("section", 7)?;
  138. state.serialize_field("content", &self.content)?;
  139. state.serialize_field("title", &self.meta.title)?;
  140. state.serialize_field("description", &self.meta.description)?;
  141. state.serialize_field("path", &format!("/{}", self.path))?;
  142. state.serialize_field("permalink", &self.permalink)?;
  143. state.serialize_field("pages", &self.pages)?;
  144. state.serialize_field("subsections", &self.subsections)?;
  145. state.end()
  146. }
  147. }
  148. impl Default for Section {
  149. /// Used to create a default index section if there is no _index.md in the root content directory
  150. fn default() -> Section {
  151. Section {
  152. meta: SectionFrontMatter::default(),
  153. file_path: PathBuf::new(),
  154. relative_path: "".to_string(),
  155. parent_path: PathBuf::new(),
  156. components: vec![],
  157. path: "".to_string(),
  158. permalink: "".to_string(),
  159. raw_content: "".to_string(),
  160. content: "".to_string(),
  161. pages: vec![],
  162. ignored_pages: vec![],
  163. subsections: vec![],
  164. }
  165. }
  166. }