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.

173 lines
5.8KB

  1. use std::collections::HashMap;
  2. use std::path::{Path, PathBuf};
  3. use std::result::Result as StdResult;
  4. use tera::{Tera, Context as TeraContext};
  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::fs::read_file;
  10. use rendering::{Context, Header, markdown_to_html};
  11. use page::Page;
  12. use 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. /// Toc made from the headers of the markdown file
  34. pub toc: Vec<Header>,
  35. }
  36. impl Section {
  37. pub fn new<P: AsRef<Path>>(file_path: P, meta: SectionFrontMatter) -> Section {
  38. let file_path = file_path.as_ref();
  39. Section {
  40. file: FileInfo::new_section(file_path),
  41. meta: meta,
  42. path: "".to_string(),
  43. permalink: "".to_string(),
  44. raw_content: "".to_string(),
  45. content: "".to_string(),
  46. pages: vec![],
  47. ignored_pages: vec![],
  48. subsections: vec![],
  49. toc: vec![],
  50. }
  51. }
  52. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  53. let (meta, content) = split_section_content(file_path, content)?;
  54. let mut section = Section::new(file_path, meta);
  55. section.raw_content = content.clone();
  56. section.path = format!("{}/", section.file.components.join("/"));
  57. section.permalink = config.make_permalink(&section.path);
  58. Ok(section)
  59. }
  60. /// Read and parse a .md file into a Page struct
  61. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  62. let path = path.as_ref();
  63. let content = read_file(path)?;
  64. Section::parse(path, &content, config)
  65. }
  66. pub fn get_template_name(&self) -> String {
  67. match self.meta.template {
  68. Some(ref l) => l.to_string(),
  69. None => {
  70. if self.is_index() {
  71. return "index.html".to_string();
  72. }
  73. "section.html".to_string()
  74. },
  75. }
  76. }
  77. /// We need access to all pages url to render links relative to content
  78. /// so that can't happen at the same time as parsing
  79. pub fn render_markdown(&mut self, permalinks: &HashMap<String, String>, tera: &Tera, config: &Config) -> Result<()> {
  80. let context = Context::new(
  81. tera,
  82. config.highlight_code.unwrap(),
  83. config.highlight_theme.clone().unwrap(),
  84. &self.permalink,
  85. permalinks,
  86. self.meta.insert_anchor.unwrap()
  87. );
  88. let res = markdown_to_html(&self.raw_content, &context)?;
  89. self.content = res.0;
  90. self.toc = res.1;
  91. Ok(())
  92. }
  93. /// Renders the page using the default layout, unless specified in front-matter
  94. pub fn render_html(&self, tera: &Tera, config: &Config) -> Result<String> {
  95. let tpl_name = self.get_template_name();
  96. let mut context = TeraContext::new();
  97. context.add("config", config);
  98. context.add("section", self);
  99. context.add("current_url", &self.permalink);
  100. context.add("current_path", &self.path);
  101. tera.render(&tpl_name, &context)
  102. .chain_err(|| format!("Failed to render section '{}'", self.file.path.display()))
  103. }
  104. /// Is this the index section?
  105. pub fn is_index(&self) -> bool {
  106. self.file.components.is_empty()
  107. }
  108. /// Returns all the paths of the pages belonging to that section
  109. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  110. let mut paths = vec![];
  111. paths.extend(self.pages.iter().map(|p| p.file.path.clone()));
  112. paths.extend(self.ignored_pages.iter().map(|p| p.file.path.clone()));
  113. paths
  114. }
  115. /// Whether the page given belongs to that section
  116. pub fn is_child_page(&self, path: &PathBuf) -> bool {
  117. self.all_pages_path().contains(path)
  118. }
  119. }
  120. impl ser::Serialize for Section {
  121. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  122. let mut state = serializer.serialize_struct("section", 10)?;
  123. state.serialize_field("content", &self.content)?;
  124. state.serialize_field("permalink", &self.permalink)?;
  125. state.serialize_field("title", &self.meta.title)?;
  126. state.serialize_field("description", &self.meta.description)?;
  127. state.serialize_field("extra", &self.meta.extra)?;
  128. state.serialize_field("path", &format!("/{}", self.path))?;
  129. state.serialize_field("permalink", &self.permalink)?;
  130. state.serialize_field("pages", &self.pages)?;
  131. state.serialize_field("subsections", &self.subsections)?;
  132. state.serialize_field("toc", &self.toc)?;
  133. state.end()
  134. }
  135. }
  136. /// Used to create a default index section if there is no _index.md in the root content directory
  137. impl Default for Section {
  138. fn default() -> Section {
  139. Section {
  140. file: FileInfo::default(),
  141. meta: SectionFrontMatter::default(),
  142. path: "".to_string(),
  143. permalink: "".to_string(),
  144. raw_content: "".to_string(),
  145. content: "".to_string(),
  146. pages: vec![],
  147. ignored_pages: vec![],
  148. subsections: vec![],
  149. toc: vec![],
  150. }
  151. }
  152. }