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.

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