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.

319 lines
10KB

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