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.

332 lines
11KB

  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_with(|| 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. pub fn rebuild_after_content_change(&mut self) -> Result<()> {
  127. self.parse_site()?;
  128. self.build()
  129. }
  130. pub fn rebuild_after_template_change(&mut self) -> Result<()> {
  131. self.templates.full_reload()?;
  132. self.build_pages()
  133. }
  134. pub fn build_pages(&self) -> Result<()> {
  135. let public = Path::new("public");
  136. if !public.exists() {
  137. create_directory(&public)?;
  138. }
  139. let mut pages = vec![];
  140. let mut category_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  141. let mut tag_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  142. // First we render the pages themselves
  143. for page in self.pages.values() {
  144. // Copy the nesting of the content directory if we have sections for that page
  145. let mut current_path = public.to_path_buf();
  146. // This loop happens when the page doesn't have a set URL
  147. for section in &page.sections {
  148. current_path.push(section);
  149. if !current_path.exists() {
  150. create_directory(&current_path)?;
  151. }
  152. }
  153. // if we have a url already set, use that as base
  154. if let Some(ref url) = page.meta.url {
  155. current_path.push(url);
  156. }
  157. // Make sure the folder exists
  158. create_directory(&current_path)?;
  159. // Finally, create a index.html file there with the page rendered
  160. let output = page.render_html(&self.templates, &self.config)?;
  161. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  162. // Copy any asset we found previously into the same directory as the index.html
  163. for asset in &page.assets {
  164. let asset_path = asset.as_path();
  165. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  166. }
  167. pages.push(page);
  168. if let Some(ref category) = page.meta.category {
  169. category_pages.entry(category.to_string()).or_insert_with(|| vec![]).push(page);
  170. }
  171. if let Some(ref tags) = page.meta.tags {
  172. for tag in tags {
  173. tag_pages.entry(tag.to_string()).or_insert_with(|| vec![]).push(page);
  174. }
  175. }
  176. }
  177. // Outputting categories and pages
  178. self.render_categories_and_tags(RenderList::Categories, &category_pages)?;
  179. self.render_categories_and_tags(RenderList::Tags, &tag_pages)?;
  180. // And finally the index page
  181. let mut context = Context::new();
  182. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  183. context.add("pages", &pages);
  184. context.add("config", &self.config);
  185. let index = self.templates.render("index.html", &context)?;
  186. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  187. Ok(())
  188. }
  189. /// Builds the site to the `public` directory after deleting it
  190. pub fn build(&self) -> Result<()> {
  191. self.clean()?;
  192. self.build_pages()?;
  193. self.render_sitemap()?;
  194. if self.config.generate_rss.unwrap() {
  195. self.render_rss_feed()?;
  196. }
  197. self.copy_static_directory()
  198. }
  199. /// Render the /{categories, list} pages and each individual category/tag page
  200. fn render_categories_and_tags(&self, kind: RenderList, container: &HashMap<String, Vec<&Page>>) -> Result<()> {
  201. if container.is_empty() {
  202. return Ok(());
  203. }
  204. let (name, list_tpl_name, single_tpl_name, var_name) = if kind == RenderList::Categories {
  205. ("categories", "categories.html", "category.html", "category")
  206. } else {
  207. ("tags", "tags.html", "tag.html", "tag")
  208. };
  209. let public = Path::new("public");
  210. let mut output_path = public.to_path_buf();
  211. output_path.push(name);
  212. create_directory(&output_path)?;
  213. // First we render the list of categories/tags page
  214. let mut sorted_container = vec![];
  215. for (item, count) in Vec::from_iter(container).into_iter().map(|(a, b)| (a, b.len())) {
  216. sorted_container.push(ListItem::new(item, count));
  217. }
  218. sorted_container.sort_by(|a, b| b.count.cmp(&a.count));
  219. let mut context = Context::new();
  220. context.add(name, &sorted_container);
  221. context.add("config", &self.config);
  222. let list_output = self.templates.render(list_tpl_name, &context)?;
  223. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  224. // and then each individual item
  225. for (item_name, mut pages) in container.clone() {
  226. let mut context = Context::new();
  227. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  228. let slug = slugify(&item_name);
  229. context.add(var_name, &item_name);
  230. context.add(&format!("{}_slug", var_name), &slug);
  231. context.add("pages", &pages);
  232. context.add("config", &self.config);
  233. let single_output = self.templates.render(single_tpl_name, &context)?;
  234. create_directory(&output_path.join(&slug))?;
  235. create_file(
  236. output_path.join(&slug).join("index.html"),
  237. &self.inject_livereload(single_output)
  238. )?;
  239. }
  240. Ok(())
  241. }
  242. fn render_sitemap(&self) -> Result<()> {
  243. let mut context = Context::new();
  244. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  245. let sitemap = self.templates.render("sitemap.xml", &context)?;
  246. let public = Path::new("public");
  247. create_file(public.join("sitemap.xml"), &sitemap)?;
  248. Ok(())
  249. }
  250. fn render_rss_feed(&self) -> Result<()> {
  251. let mut context = Context::new();
  252. let mut pages = self.pages.values()
  253. .filter(|p| p.meta.date.is_some())
  254. .take(15) // limit to the last 15 elements
  255. .collect::<Vec<&Page>>();
  256. // Don't generate a RSS feed if none of the pages has a date
  257. if pages.is_empty() {
  258. return Ok(());
  259. }
  260. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  261. context.add("pages", &pages);
  262. context.add("last_build_date", &pages[0].meta.date);
  263. context.add("config", &self.config);
  264. let rss_feed_url = if self.config.base_url.ends_with('/') {
  265. format!("{}{}", self.config.base_url, "feed.xml")
  266. } else {
  267. format!("{}/{}", self.config.base_url, "feed.xml")
  268. };
  269. context.add("feed_url", &rss_feed_url);
  270. let sitemap = self.templates.render("rss.xml", &context)?;
  271. let public = Path::new("public");
  272. create_file(public.join("rss.xml"), &sitemap)?;
  273. Ok(())
  274. }
  275. }