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.

278 lines
9.0KB

  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. /// Reload the Tera templates
  79. pub fn reload_templates(&mut self) -> Result<()> {
  80. Ok(())
  81. }
  82. /// Copy the content of the `static` folder into the `public` folder
  83. pub fn copy_static_files(&self) -> Result<()> {
  84. Ok(())
  85. }
  86. /// Re-parse and re-generate the site
  87. /// Very dumb for now, ideally it would only rebuild what changed
  88. pub fn rebuild(&mut self) -> Result<()> {
  89. self.parse_site()?;
  90. self.build()
  91. }
  92. /// Builds the site to the `public` directory after deleting it
  93. pub fn build(&self) -> Result<()> {
  94. if Path::new("public").exists() {
  95. // Delete current `public` directory so we can start fresh
  96. remove_dir_all("public").chain_err(|| "Couldn't delete `public` directory")?;
  97. }
  98. // Start from scratch
  99. create_dir("public")?;
  100. let public = Path::new("public");
  101. let mut pages = vec![];
  102. let mut category_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  103. let mut tag_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  104. // First we render the pages themselves
  105. for page in self.pages.values() {
  106. // Copy the nesting of the content directory if we have sections for that page
  107. let mut current_path = public.to_path_buf();
  108. // This loop happens when the page doesn't have a set URL
  109. for section in &page.sections {
  110. current_path.push(section);
  111. if !current_path.exists() {
  112. create_dir(&current_path)?;
  113. }
  114. }
  115. // if we have a url already set, use that as base
  116. if let Some(ref url) = page.meta.url {
  117. current_path.push(url);
  118. }
  119. // Make sure the folder exists
  120. create_dir(&current_path)?;
  121. // Finally, create a index.html file there with the page rendered
  122. let output = page.render_html(&self.templates, &self.config)?;
  123. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  124. pages.push(page);
  125. if let Some(ref category) = page.meta.category {
  126. category_pages.entry(category.to_string()).or_insert(vec![]).push(page);
  127. }
  128. if let Some(ref tags) = page.meta.tags {
  129. for tag in tags {
  130. tag_pages.entry(tag.to_string()).or_insert(vec![]).push(page);
  131. }
  132. }
  133. }
  134. // Outputting categories and pages
  135. self.render_categories_and_tags(RenderList::Categories, &category_pages)?;
  136. self.render_categories_and_tags(RenderList::Tags, &tag_pages)?;
  137. self.render_sitemap()?;
  138. self.render_rss_feed()?;
  139. // And finally the index page
  140. let mut context = Context::new();
  141. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  142. context.add("pages", &pages);
  143. context.add("config", &self.config);
  144. let index = self.templates.render("index.html", &context)?;
  145. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  146. Ok(())
  147. }
  148. /// Render the /{categories, list} pages and each individual category/tag page
  149. fn render_categories_and_tags(&self, kind: RenderList, container: &HashMap<String, Vec<&Page>>) -> Result<()> {
  150. if container.is_empty() {
  151. return Ok(());
  152. }
  153. let (name, list_tpl_name, single_tpl_name, var_name) = if kind == RenderList::Categories {
  154. ("categories", "categories.html", "category.html", "category")
  155. } else {
  156. ("tags", "tags.html", "tag.html", "tag")
  157. };
  158. let public = Path::new("public");
  159. let mut output_path = public.to_path_buf();
  160. output_path.push(name);
  161. create_dir(&output_path)?;
  162. // First we render the list of categories/tags page
  163. let mut sorted_container = vec![];
  164. for (item, count) in Vec::from_iter(container).into_iter().map(|(a, b)| (a, b.len())) {
  165. sorted_container.push(ListItem::new(item, count));
  166. }
  167. sorted_container.sort_by(|a, b| b.count.cmp(&a.count));
  168. let mut context = Context::new();
  169. context.add(name, &sorted_container);
  170. context.add("config", &self.config);
  171. let list_output = self.templates.render(list_tpl_name, &context)?;
  172. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  173. // and then each individual item
  174. for (item_name, mut pages) in container.clone() {
  175. let mut context = Context::new();
  176. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  177. let slug = slugify(&item_name);
  178. context.add(var_name, &item_name);
  179. context.add(&format!("{}_slug", var_name), &slug);
  180. context.add("pages", &pages);
  181. context.add("config", &self.config);
  182. let single_output = self.templates.render(single_tpl_name, &context)?;
  183. create_dir(&output_path.join(&slug))?;
  184. create_file(
  185. output_path.join(&slug).join("index.html"),
  186. &self.inject_livereload(single_output)
  187. )?;
  188. }
  189. Ok(())
  190. }
  191. fn render_sitemap(&self) -> Result<()> {
  192. let tpl = String::from_utf8(include_bytes!("templates/sitemap.xml").to_vec()).unwrap();
  193. let mut context = Context::new();
  194. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  195. let sitemap = Tera::one_off(&tpl, &context, false)?;
  196. let public = Path::new("public");
  197. create_file(public.join("sitemap.xml"), &sitemap)?;
  198. Ok(())
  199. }
  200. fn get_rss_feed_url(&self) -> String {
  201. if self.config.base_url.ends_with("/") {
  202. format!("{}{}", self.config.base_url, "feed.xml")
  203. } else {
  204. format!("{}/{}", self.config.base_url, "feed.xml")
  205. }
  206. }
  207. fn render_rss_feed(&self) -> Result<()> {
  208. let tpl = String::from_utf8(include_bytes!("templates/rss.xml").to_vec()).unwrap();
  209. let mut context = Context::new();
  210. let mut pages = self.pages.values()
  211. .filter(|p| p.meta.date.is_some())
  212. .take(15) // limit to the last 15 elements
  213. .collect::<Vec<&Page>>();
  214. // Don't generate a RSS feed if none of the pages has a date
  215. if pages.is_empty() {
  216. return Ok(());
  217. }
  218. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  219. context.add("pages", &pages);
  220. context.add("last_build_date", &pages[0].meta.date);
  221. context.add("config", &self.config);
  222. context.add("feed_url", &self.get_rss_feed_url());
  223. let sitemap = Tera::one_off(&tpl, &context, false)?;
  224. let public = Path::new("public");
  225. create_file(public.join("rss.xml"), &sitemap)?;
  226. Ok(())
  227. }
  228. }