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.

170 lines
5.9KB

  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. section.relative_path = "_index.md".to_string();
  66. } else {
  67. section.relative_path = format!("{}/_index.md", section.components.join("/"));
  68. }
  69. Ok(section)
  70. }
  71. /// Read and parse a .md file into a Page struct
  72. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  73. let path = path.as_ref();
  74. let content = read_file(path)?;
  75. Section::parse(path, &content, config)
  76. }
  77. pub fn get_template_name(&self) -> String {
  78. match self.meta.template {
  79. Some(ref l) => l.to_string(),
  80. None => {
  81. if self.is_index() {
  82. return "index.html".to_string();
  83. }
  84. "section.html".to_string()
  85. },
  86. }
  87. }
  88. /// We need access to all pages url to render links relative to content
  89. /// so that can't happen at the same time as parsing
  90. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config) -> Result<()> {
  91. self.content = markdown_to_html(&self.raw_content, permalinks, tera, config)?;
  92. Ok(())
  93. }
  94. /// Renders the page using the default layout, unless specified in front-matter
  95. pub fn render_html(&self, sections: &HashMap<String, Section>, tera: &Tera, config: &Config) -> Result<String> {
  96. let tpl_name = self.get_template_name();
  97. let mut context = Context::new();
  98. context.add("config", config);
  99. context.add("section", self);
  100. context.add("current_url", &self.permalink);
  101. context.add("current_path", &self.path);
  102. if self.is_index() {
  103. context.add("sections", sections);
  104. }
  105. tera.render(&tpl_name, &context)
  106. .chain_err(|| format!("Failed to render section '{}'", self.file_path.display()))
  107. }
  108. /// Is this the index section?
  109. pub fn is_index(&self) -> bool {
  110. self.components.is_empty()
  111. }
  112. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  113. let mut paths = vec![];
  114. paths.extend(self.pages.iter().map(|p| p.file_path.clone()));
  115. paths.extend(self.ignored_pages.iter().map(|p| p.file_path.clone()));
  116. paths
  117. }
  118. }
  119. impl ser::Serialize for Section {
  120. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  121. let mut state = serializer.serialize_struct("section", 7)?;
  122. state.serialize_field("content", &self.content)?;
  123. state.serialize_field("title", &self.meta.title)?;
  124. state.serialize_field("description", &self.meta.description)?;
  125. state.serialize_field("path", &format!("/{}", self.path))?;
  126. state.serialize_field("permalink", &self.permalink)?;
  127. state.serialize_field("pages", &self.pages)?;
  128. state.serialize_field("subsections", &self.subsections)?;
  129. state.end()
  130. }
  131. }
  132. impl Default for Section {
  133. /// Used to create a default index section if there is no _index.md in the root content directory
  134. fn default() -> Section {
  135. Section {
  136. file_path: PathBuf::new(),
  137. relative_path: "".to_string(),
  138. parent_path: PathBuf::new(),
  139. components: vec![],
  140. path: "".to_string(),
  141. permalink: "".to_string(),
  142. raw_content: "".to_string(),
  143. content: "".to_string(),
  144. meta: FrontMatter::default(),
  145. pages: vec![],
  146. ignored_pages: vec![],
  147. subsections: vec![],
  148. }
  149. }
  150. }