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.

133 lines
4.5KB

  1. use std::path::{Path, PathBuf};
  2. use std::result::Result as StdResult;
  3. use tera::{Tera, Context};
  4. use serde::ser::{SerializeStruct, self};
  5. use config::Config;
  6. use front_matter::{FrontMatter, split_content};
  7. use errors::{Result, ResultExt};
  8. use utils::{read_file, find_content_components};
  9. use page::{Page};
  10. #[derive(Clone, Debug, PartialEq)]
  11. pub struct Section {
  12. /// The _index.md full path
  13. pub file_path: PathBuf,
  14. /// The .md path, starting from the content directory, with / slashes
  15. pub relative_path: String,
  16. /// Path of the directory containing the _index.md file
  17. pub parent_path: PathBuf,
  18. /// The folder names from `content` to this section file
  19. pub components: Vec<String>,
  20. /// The URL path of the page
  21. pub path: String,
  22. /// The full URL for that page
  23. pub permalink: String,
  24. /// The front matter meta-data
  25. pub meta: FrontMatter,
  26. /// All direct pages of that section
  27. pub pages: Vec<Page>,
  28. /// All pages that cannot be sorted in this section
  29. pub ignored_pages: Vec<Page>,
  30. /// All direct subsections
  31. pub subsections: Vec<Section>,
  32. }
  33. impl Section {
  34. pub fn new<P: AsRef<Path>>(file_path: P, meta: FrontMatter) -> Section {
  35. let file_path = file_path.as_ref();
  36. Section {
  37. file_path: file_path.to_path_buf(),
  38. relative_path: "".to_string(),
  39. parent_path: file_path.parent().unwrap().to_path_buf(),
  40. components: vec![],
  41. path: "".to_string(),
  42. permalink: "".to_string(),
  43. meta: meta,
  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, _) = split_content(file_path, content)?;
  51. let mut section = Section::new(file_path, meta);
  52. section.components = find_content_components(&section.file_path);
  53. section.path = section.components.join("/");
  54. section.permalink = config.make_permalink(&section.path);
  55. if section.components.is_empty() {
  56. section.relative_path = "_index.md".to_string();
  57. } else {
  58. section.relative_path = format!("{}/_index.md", section.components.join("/"));
  59. }
  60. Ok(section)
  61. }
  62. /// Read and parse a .md file into a Page struct
  63. pub fn from_file<P: AsRef<Path>>(path: P, config: &Config) -> Result<Section> {
  64. let path = path.as_ref();
  65. let content = read_file(path)?;
  66. Section::parse(path, &content, config)
  67. }
  68. pub fn get_template_name(&self) -> String {
  69. match self.meta.template {
  70. Some(ref l) => l.to_string(),
  71. None => {
  72. if self.is_index() {
  73. return "index.html".to_string();
  74. }
  75. "section.html".to_string()
  76. },
  77. }
  78. }
  79. /// Renders the page using the default layout, unless specified in front-matter
  80. pub fn render_html(&self, sections: &[&Section], tera: &Tera, config: &Config) -> Result<String> {
  81. let tpl_name = self.get_template_name();
  82. let mut context = Context::new();
  83. context.add("config", config);
  84. context.add("section", self);
  85. context.add("current_url", &self.permalink);
  86. context.add("current_path", &self.path);
  87. if self.is_index() {
  88. context.add("sections", &sections);
  89. }
  90. tera.render(&tpl_name, &context)
  91. .chain_err(|| format!("Failed to render section '{}'", self.file_path.display()))
  92. }
  93. /// Is this the index section?
  94. pub fn is_index(&self) -> bool {
  95. self.components.is_empty()
  96. }
  97. pub fn all_pages_path(&self) -> Vec<PathBuf> {
  98. let mut paths = vec![];
  99. paths.extend(self.pages.iter().map(|p| p.file_path.clone()));
  100. paths.extend(self.ignored_pages.iter().map(|p| p.file_path.clone()));
  101. paths
  102. }
  103. }
  104. impl ser::Serialize for Section {
  105. fn serialize<S>(&self, serializer: S) -> StdResult<S::Ok, S::Error> where S: ser::Serializer {
  106. let mut state = serializer.serialize_struct("section", 6)?;
  107. state.serialize_field("title", &self.meta.title)?;
  108. state.serialize_field("description", &self.meta.description)?;
  109. state.serialize_field("path", &format!("/{}", self.path))?;
  110. state.serialize_field("permalink", &self.permalink)?;
  111. state.serialize_field("pages", &self.pages)?;
  112. state.serialize_field("subsections", &self.subsections)?;
  113. state.end()
  114. }
  115. }