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.

268 lines
8.7KB

  1. use std::collections::HashMap;
  2. use std::iter::FromIterator;
  3. use std::fs::{create_dir, remove_dir_all};
  4. use std::path::Path;
  5. use glob::glob;
  6. use tera::{Tera, Context};
  7. use slug::slugify;
  8. use errors::{Result, ResultExt};
  9. use config::{Config, get_config};
  10. use page::Page;
  11. use utils::create_file;
  12. #[derive(Debug, PartialEq)]
  13. enum RenderList {
  14. Tags,
  15. Categories,
  16. }
  17. /// A tag or category
  18. #[derive(Debug, Serialize, PartialEq)]
  19. struct ListItem {
  20. name: String,
  21. slug: String,
  22. count: usize,
  23. }
  24. impl ListItem {
  25. pub fn new(name: &str, count: usize) -> ListItem {
  26. ListItem {
  27. name: name.to_string(),
  28. slug: slugify(name),
  29. count: count,
  30. }
  31. }
  32. }
  33. #[derive(Debug)]
  34. pub struct Site {
  35. config: Config,
  36. pages: HashMap<String, Page>,
  37. sections: HashMap<String, Vec<String>>,
  38. templates: Tera,
  39. live_reload: bool,
  40. }
  41. impl Site {
  42. pub fn new(livereload: bool) -> Result<Site> {
  43. let tera = Tera::new("templates/**/*").chain_err(|| "Error parsing templates")?;
  44. let mut site = Site {
  45. config: get_config(),
  46. pages: HashMap::new(),
  47. sections: HashMap::new(),
  48. templates: tera,
  49. live_reload: livereload,
  50. };
  51. site.parse_site()?;
  52. Ok(site)
  53. }
  54. /// Reads all .md files in the `content` directory and create pages
  55. /// out of them
  56. fn parse_site(&mut self) -> Result<()> {
  57. // First step: do all the articles and group article by sections
  58. // hardcoded pattern so can't error
  59. for entry in glob("content/**/*.md").unwrap().filter_map(|e| e.ok()) {
  60. let page = Page::from_file(&entry.as_path(), &self.config)?;
  61. for section in &page.sections {
  62. self.sections.entry(section.clone()).or_insert(vec![]).push(page.slug.clone());
  63. }
  64. self.pages.insert(page.slug.clone(), page);
  65. }
  66. Ok(())
  67. }
  68. // Inject live reload script tag if in live reload mode
  69. fn inject_livereload(&self, html: String) -> String {
  70. if self.live_reload {
  71. return html.replace(
  72. "</body>",
  73. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  74. );
  75. }
  76. html
  77. }
  78. /// Re-parse and re-generate the site
  79. /// Very dumb for now, ideally it would only rebuild what changed
  80. pub fn rebuild(&mut self) -> Result<()> {
  81. self.parse_site()?;
  82. self.build()
  83. }
  84. /// Builds the site to the `public` directory after deleting it
  85. pub fn build(&self) -> Result<()> {
  86. if Path::new("public").exists() {
  87. // Delete current `public` directory so we can start fresh
  88. remove_dir_all("public").chain_err(|| "Couldn't delete `public` directory")?;
  89. }
  90. // Start from scratch
  91. create_dir("public")?;
  92. let public = Path::new("public");
  93. let mut pages = vec![];
  94. let mut category_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  95. let mut tag_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  96. // First we render the pages themselves
  97. for page in self.pages.values() {
  98. // Copy the nesting of the content directory if we have sections for that page
  99. let mut current_path = public.to_path_buf();
  100. // This loop happens when the page doesn't have a set URL
  101. for section in &page.sections {
  102. current_path.push(section);
  103. if !current_path.exists() {
  104. create_dir(&current_path)?;
  105. }
  106. }
  107. // if we have a url already set, use that as base
  108. if let Some(ref url) = page.meta.url {
  109. current_path.push(url);
  110. }
  111. // Make sure the folder exists
  112. create_dir(&current_path)?;
  113. // Finally, create a index.html file there with the page rendered
  114. let output = page.render_html(&self.templates, &self.config)?;
  115. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  116. pages.push(page);
  117. if let Some(ref category) = page.meta.category {
  118. category_pages.entry(category.to_string()).or_insert(vec![]).push(page);
  119. }
  120. if let Some(ref tags) = page.meta.tags {
  121. for tag in tags {
  122. tag_pages.entry(tag.to_string()).or_insert(vec![]).push(page);
  123. }
  124. }
  125. }
  126. // Outputting categories and pages
  127. self.render_categories_and_tags(RenderList::Categories, &category_pages)?;
  128. self.render_categories_and_tags(RenderList::Tags, &tag_pages)?;
  129. self.render_sitemap()?;
  130. self.render_rss_feed()?;
  131. // And finally the index page
  132. let mut context = Context::new();
  133. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  134. context.add("pages", &pages);
  135. context.add("config", &self.config);
  136. let index = self.templates.render("index.html", &context)?;
  137. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  138. Ok(())
  139. }
  140. /// Render the /{categories, list} pages and each individual category/tag page
  141. fn render_categories_and_tags(&self, kind: RenderList, container: &HashMap<String, Vec<&Page>>) -> Result<()> {
  142. if container.is_empty() {
  143. return Ok(());
  144. }
  145. let (name, list_tpl_name, single_tpl_name, var_name) = if kind == RenderList::Categories {
  146. ("categories", "categories.html", "category.html", "category")
  147. } else {
  148. ("tags", "tags.html", "tag.html", "tag")
  149. };
  150. let public = Path::new("public");
  151. let mut output_path = public.to_path_buf();
  152. output_path.push(name);
  153. create_dir(&output_path)?;
  154. // First we render the list of categories/tags page
  155. let mut sorted_container = vec![];
  156. for (item, count) in Vec::from_iter(container).into_iter().map(|(a, b)| (a, b.len())) {
  157. sorted_container.push(ListItem::new(item, count));
  158. }
  159. sorted_container.sort_by(|a, b| b.count.cmp(&a.count));
  160. let mut context = Context::new();
  161. context.add(name, &sorted_container);
  162. context.add("config", &self.config);
  163. let list_output = self.templates.render(list_tpl_name, &context)?;
  164. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  165. // and then each individual item
  166. for (item_name, mut pages) in container.clone() {
  167. let mut context = Context::new();
  168. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  169. let slug = slugify(&item_name);
  170. context.add(var_name, &item_name);
  171. context.add(&format!("{}_slug", var_name), &slug);
  172. context.add("pages", &pages);
  173. context.add("config", &self.config);
  174. let single_output = self.templates.render(single_tpl_name, &context)?;
  175. create_dir(&output_path.join(&slug))?;
  176. create_file(
  177. output_path.join(&slug).join("index.html"),
  178. &self.inject_livereload(single_output)
  179. )?;
  180. }
  181. Ok(())
  182. }
  183. fn render_sitemap(&self) -> Result<()> {
  184. let tpl = String::from_utf8(include_bytes!("templates/sitemap.xml").to_vec()).unwrap();
  185. let mut context = Context::new();
  186. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  187. let sitemap = Tera::one_off(&tpl, &context, false)?;
  188. let public = Path::new("public");
  189. create_file(public.join("sitemap.xml"), &sitemap)?;
  190. Ok(())
  191. }
  192. fn get_rss_feed_url(&self) -> String {
  193. if self.config.base_url.ends_with("/") {
  194. format!("{}{}", self.config.base_url, "feed.xml")
  195. } else {
  196. format!("{}/{}", self.config.base_url, "feed.xml")
  197. }
  198. }
  199. fn render_rss_feed(&self) -> Result<()> {
  200. let tpl = String::from_utf8(include_bytes!("templates/rss.xml").to_vec()).unwrap();
  201. let mut context = Context::new();
  202. let mut pages = self.pages.values()
  203. .filter(|p| p.meta.date.is_some())
  204. .take(15) // limit to the last 15 elements
  205. .collect::<Vec<&Page>>();
  206. // Don't generate a RSS feed if none of the pages has a date
  207. if pages.is_empty() {
  208. return Ok(());
  209. }
  210. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  211. context.add("pages", &pages);
  212. context.add("last_build_date", &pages[0].meta.date);
  213. context.add("config", &self.config);
  214. context.add("feed_url", &self.get_rss_feed_url());
  215. let sitemap = Tera::one_off(&tpl, &context, false)?;
  216. let public = Path::new("public");
  217. create_file(public.join("rss.xml"), &sitemap)?;
  218. Ok(())
  219. }
  220. }