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.

152 lines
5.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 page::{Page};
  11. #[derive(Clone, Debug, PartialEq)]
  12. pub struct Section {
  13. /// The _index.md full path
  14. pub file_path: PathBuf,
  15. /// The .md path, starting from the content directory, with / slashes
  16. pub relative_path: String,
  17. /// Path of the directory containing the _index.md file
  18. pub parent_path: PathBuf,
  19. /// The folder names from `content` to this section file
  20. pub components: Vec<String>,
  21. /// The URL path of the page
  22. pub path: String,
  23. /// The full URL for that page
  24. pub permalink: String,
  25. /// The front matter meta-data
  26. pub meta: FrontMatter,
  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: FrontMatter) -> Section {
  36. let file_path = file_path.as_ref();
  37. Section {
  38. file_path: file_path.to_path_buf(),
  39. relative_path: "".to_string(),
  40. parent_path: file_path.parent().unwrap().to_path_buf(),
  41. components: vec![],
  42. path: "".to_string(),
  43. permalink: "".to_string(),
  44. meta: meta,
  45. pages: vec![],
  46. ignored_pages: vec![],
  47. subsections: vec![],
  48. }
  49. }
  50. pub fn parse(file_path: &Path, content: &str, config: &Config) -> Result<Section> {
  51. let (meta, _) = split_content(file_path, content)?;
  52. let mut section = Section::new(file_path, meta);
  53. section.components = find_content_components(&section.file_path);
  54. section.path = section.components.join("/");
  55. section.permalink = config.make_permalink(&section.path);
  56. if section.components.is_empty() {
  57. section.relative_path = "_index.md".to_string();
  58. } else {
  59. section.relative_path = format!("{}/_index.md", section.components.join("/"));
  60. }
  61. Ok(section)
  62. }
  63. /// Read and parse a .md file into a Page struct
  64. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  65. let path = path.as_ref();
  66. let content = read_file(path)?;
  67. Section::parse(path, &content, config)
  68. }
  69. pub fn get_template_name(&self) -> String {
  70. match self.meta.template {
  71. Some(ref l) => l.to_string(),
  72. None => {
  73. if self.is_index() {
  74. return "index.html".to_string();
  75. }
  76. "section.html".to_string()
  77. },
  78. }
  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.components.is_empty()
  97. }
  98. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  99. let mut paths = vec![];
  100. paths.extend(self.pages.iter().map(|p| p.file_path.clone()));
  101. paths.extend(self.ignored_pages.iter().map(|p| p.file_path.clone()));
  102. paths
  103. }
  104. }
  105. impl ser::Serialize for Section {
  106. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  107. let mut state = serializer.serialize_struct("section", 6)?;
  108. state.serialize_field("title", &self.meta.title)?;
  109. state.serialize_field("description", &self.meta.description)?;
  110. state.serialize_field("path", &format!("/{}", self.path))?;
  111. state.serialize_field("permalink", &self.permalink)?;
  112. state.serialize_field("pages", &self.pages)?;
  113. state.serialize_field("subsections", &self.subsections)?;
  114. state.end()
  115. }
  116. }
  117. impl Default for Section {
  118. /// Used to create a default index section if there is no _index.md
  119. fn default() -> Section {
  120. Section {
  121. file_path: PathBuf::new(),
  122. relative_path: "".to_string(),
  123. parent_path: PathBuf::new(),
  124. components: vec![],
  125. path: "".to_string(),
  126. permalink: "".to_string(),
  127. meta: FrontMatter::default(),
  128. pages: vec![],
  129. ignored_pages: vec![],
  130. subsections: vec![],
  131. }
  132. }
  133. }