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.

328 lines
10KB

  1. use std::collections::HashMap;
  2. use std::iter::FromIterator;
  3. use std::fs::{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, create_directory};
  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. /// Copy the content of the `static` folder into the `public` folder
  92. ///
  93. /// TODO: only copy one file if possible because that would be a waster
  94. /// to do re-copy the whole thing
  95. pub fn copy_static_directory(&self) -> Result<()> {
  96. let from = Path::new("static");
  97. let target = Path::new("public");
  98. for entry in WalkDir::new(from).into_iter().filter_map(|e| e.ok()) {
  99. let relative_path = entry.path().strip_prefix(&from).unwrap();
  100. let target_path = {
  101. let mut target_path = target.to_path_buf();
  102. target_path.push(relative_path);
  103. target_path
  104. };
  105. if entry.path().is_dir() {
  106. if !target_path.exists() {
  107. create_directory(&target_path)?;
  108. }
  109. } else {
  110. if target_path.exists() {
  111. remove_file(&target_path)?;
  112. }
  113. copy(entry.path(), &target_path)?;
  114. }
  115. }
  116. Ok(())
  117. }
  118. /// Deletes the `public` directory if it exists
  119. pub fn clean(&self) -> Result<()> {
  120. if Path::new("public").exists() {
  121. // Delete current `public` directory so we can start fresh
  122. remove_dir_all("public").chain_err(|| "Couldn't delete `public` directory")?;
  123. }
  124. Ok(())
  125. }
  126. /// Re-parse and re-generate the site
  127. /// Very dumb for now, ideally it would only rebuild what changed
  128. pub fn rebuild(&mut self) -> Result<()> {
  129. self.parse_site()?;
  130. self.build()
  131. }
  132. pub fn rebuild_after_template_change(&mut self) -> Result<()> {
  133. self.templates.full_reload()?;
  134. println!("Reloaded templates");
  135. self.build_pages()
  136. }
  137. pub fn build_pages(&self) -> Result<()> {
  138. let public = Path::new("public");
  139. if !public.exists() {
  140. create_directory(&public)?;
  141. }
  142. let mut pages = vec![];
  143. let mut category_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  144. let mut tag_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  145. // First we render the pages themselves
  146. for page in self.pages.values() {
  147. // Copy the nesting of the content directory if we have sections for that page
  148. let mut current_path = public.to_path_buf();
  149. // This loop happens when the page doesn't have a set URL
  150. for section in &page.sections {
  151. current_path.push(section);
  152. if !current_path.exists() {
  153. create_directory(&current_path)?;
  154. }
  155. }
  156. // if we have a url already set, use that as base
  157. if let Some(ref url) = page.meta.url {
  158. current_path.push(url);
  159. }
  160. // Make sure the folder exists
  161. create_directory(&current_path)?;
  162. // Finally, create a index.html file there with the page rendered
  163. let output = page.render_html(&self.templates, &self.config)?;
  164. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  165. pages.push(page);
  166. if let Some(ref category) = page.meta.category {
  167. category_pages.entry(category.to_string()).or_insert(vec![]).push(page);
  168. }
  169. if let Some(ref tags) = page.meta.tags {
  170. for tag in tags {
  171. tag_pages.entry(tag.to_string()).or_insert(vec![]).push(page);
  172. }
  173. }
  174. }
  175. // Outputting categories and pages
  176. self.render_categories_and_tags(RenderList::Categories, &category_pages)?;
  177. self.render_categories_and_tags(RenderList::Tags, &tag_pages)?;
  178. // And finally the index page
  179. let mut context = Context::new();
  180. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  181. context.add("pages", &pages);
  182. context.add("config", &self.config);
  183. let index = self.templates.render("index.html", &context)?;
  184. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  185. Ok(())
  186. }
  187. /// Builds the site to the `public` directory after deleting it
  188. pub fn build(&self) -> Result<()> {
  189. self.clean()?;
  190. self.build_pages()?;
  191. self.render_sitemap()?;
  192. self.render_rss_feed()?;
  193. self.copy_static_directory()
  194. }
  195. /// Render the /{categories, list} pages and each individual category/tag page
  196. fn render_categories_and_tags(&self, kind: RenderList, container: &HashMap<String, Vec<&Page>>) -> Result<()> {
  197. if container.is_empty() {
  198. return Ok(());
  199. }
  200. let (name, list_tpl_name, single_tpl_name, var_name) = if kind == RenderList::Categories {
  201. ("categories", "categories.html", "category.html", "category")
  202. } else {
  203. ("tags", "tags.html", "tag.html", "tag")
  204. };
  205. let public = Path::new("public");
  206. let mut output_path = public.to_path_buf();
  207. output_path.push(name);
  208. create_directory(&output_path)?;
  209. // First we render the list of categories/tags page
  210. let mut sorted_container = vec![];
  211. for (item, count) in Vec::from_iter(container).into_iter().map(|(a, b)| (a, b.len())) {
  212. sorted_container.push(ListItem::new(item, count));
  213. }
  214. sorted_container.sort_by(|a, b| b.count.cmp(&a.count));
  215. let mut context = Context::new();
  216. context.add(name, &sorted_container);
  217. context.add("config", &self.config);
  218. let list_output = self.templates.render(list_tpl_name, &context)?;
  219. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  220. // and then each individual item
  221. for (item_name, mut pages) in container.clone() {
  222. let mut context = Context::new();
  223. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  224. let slug = slugify(&item_name);
  225. context.add(var_name, &item_name);
  226. context.add(&format!("{}_slug", var_name), &slug);
  227. context.add("pages", &pages);
  228. context.add("config", &self.config);
  229. let single_output = self.templates.render(single_tpl_name, &context)?;
  230. create_directory(&output_path.join(&slug))?;
  231. create_file(
  232. output_path.join(&slug).join("index.html"),
  233. &self.inject_livereload(single_output)
  234. )?;
  235. }
  236. Ok(())
  237. }
  238. fn render_sitemap(&self) -> Result<()> {
  239. let mut context = Context::new();
  240. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  241. let sitemap = self.templates.render("sitemap.xml", &context)?;
  242. let public = Path::new("public");
  243. create_file(public.join("sitemap.xml"), &sitemap)?;
  244. Ok(())
  245. }
  246. fn render_rss_feed(&self) -> Result<()> {
  247. let mut context = Context::new();
  248. let mut pages = self.pages.values()
  249. .filter(|p| p.meta.date.is_some())
  250. .take(15) // limit to the last 15 elements
  251. .collect::<Vec<&Page>>();
  252. // Don't generate a RSS feed if none of the pages has a date
  253. if pages.is_empty() {
  254. return Ok(());
  255. }
  256. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  257. context.add("pages", &pages);
  258. context.add("last_build_date", &pages[0].meta.date);
  259. context.add("config", &self.config);
  260. let rss_feed_url = if self.config.base_url.ends_with("/") {
  261. format!("{}{}", self.config.base_url, "feed.xml")
  262. } else {
  263. format!("{}/{}", self.config.base_url, "feed.xml")
  264. };
  265. context.add("feed_url", &rss_feed_url);
  266. let sitemap = self.templates.render("rss.xml", &context)?;
  267. let public = Path::new("public");
  268. create_file(public.join("rss.xml"), &sitemap)?;
  269. Ok(())
  270. }
  271. }