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.

172 lines
6.0KB

  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::{FrontMatter, split_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 _index.md full path
  15. pub file_path: PathBuf,
  16. /// The .md path, starting from the content directory, with / slashes
  17. pub relative_path: String,
  18. /// Path of the directory containing the _index.md file
  19. pub parent_path: PathBuf,
  20. /// The folder names from `content` to this section file
  21. pub components: Vec<String>,
  22. /// The URL path of the page
  23. pub path: String,
  24. /// The full URL for that page
  25. pub permalink: String,
  26. /// The actual content of the page, in markdown
  27. pub raw_content: String,
  28. /// The HTML rendered of the page
  29. pub content: String,
  30. /// The front matter meta-data
  31. pub meta: FrontMatter,
  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: FrontMatter) -> Section {
  41. let file_path = file_path.as_ref();
  42. Section {
  43. file_path: file_path.to_path_buf(),
  44. relative_path: "".to_string(),
  45. parent_path: file_path.parent().unwrap().to_path_buf(),
  46. components: vec![],
  47. path: "".to_string(),
  48. permalink: "".to_string(),
  49. raw_content: "".to_string(),
  50. content: "".to_string(),
  51. meta: meta,
  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_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. }
  121. impl ser::Serialize for Section {
  122. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  123. let mut state = serializer.serialize_struct("section", 7)?;
  124. state.serialize_field("content", &self.content)?;
  125. state.serialize_field("title", &self.meta.title)?;
  126. state.serialize_field("description", &self.meta.description)?;
  127. state.serialize_field("path", &format!("/{}", self.path))?;
  128. state.serialize_field("permalink", &self.permalink)?;
  129. state.serialize_field("pages", &self.pages)?;
  130. state.serialize_field("subsections", &self.subsections)?;
  131. state.end()
  132. }
  133. }
  134. impl Default for Section {
  135. /// Used to create a default index section if there is no _index.md in the root content directory
  136. fn default() -> Section {
  137. Section {
  138. file_path: PathBuf::new(),
  139. relative_path: "".to_string(),
  140. parent_path: PathBuf::new(),
  141. components: vec![],
  142. path: "".to_string(),
  143. permalink: "".to_string(),
  144. raw_content: "".to_string(),
  145. content: "".to_string(),
  146. meta: FrontMatter::default(),
  147. pages: vec![],
  148. ignored_pages: vec![],
  149. subsections: vec![],
  150. }
  151. }
  152. }