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.

396 lines
13KB

  1. use std::collections::{BTreeMap, HashMap};
  2. use std::iter::FromIterator;
  3. use std::fs::{remove_dir_all, copy, remove_file};
  4. use std::path::{Path, PathBuf};
  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. use section::{Section};
  14. lazy_static! {
  15. static ref GUTENBERG_TERA: Tera = {
  16. let mut tera = Tera::default();
  17. tera.add_raw_templates(vec![
  18. ("rss.xml", include_str!("templates/rss.xml")),
  19. ("sitemap.xml", include_str!("templates/sitemap.xml")),
  20. ]).unwrap();
  21. tera
  22. };
  23. }
  24. #[derive(Debug, PartialEq)]
  25. enum RenderList {
  26. Tags,
  27. Categories,
  28. }
  29. /// A tag or category
  30. #[derive(Debug, Serialize, PartialEq)]
  31. struct ListItem {
  32. name: String,
  33. slug: String,
  34. count: usize,
  35. }
  36. impl ListItem {
  37. pub fn new(name: &str, count: usize) -> ListItem {
  38. ListItem {
  39. name: name.to_string(),
  40. slug: slugify(name),
  41. count: count,
  42. }
  43. }
  44. }
  45. #[derive(Debug)]
  46. pub struct Site {
  47. pub base_path: PathBuf,
  48. pub config: Config,
  49. pub pages: HashMap<PathBuf, Page>,
  50. pub sections: BTreeMap<PathBuf, Section>,
  51. pub templates: Tera,
  52. live_reload: bool,
  53. output_path: PathBuf,
  54. }
  55. impl Site {
  56. /// Parse a site at the given path. Defaults to the current dir
  57. /// Passing in a path is only used in tests
  58. pub fn new<P: AsRef<Path>>(path: P) -> Result<Site> {
  59. let path = path.as_ref();
  60. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*");
  61. let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
  62. tera.extend(&GUTENBERG_TERA)?;
  63. let mut site = Site {
  64. base_path: path.to_path_buf(),
  65. config: get_config(&path),
  66. pages: HashMap::new(),
  67. sections: BTreeMap::new(),
  68. templates: tera,
  69. live_reload: false,
  70. output_path: PathBuf::from("public"),
  71. };
  72. site.parse_site()?;
  73. Ok(site)
  74. }
  75. /// What the function name says
  76. pub fn enable_live_reload(&mut self) {
  77. self.live_reload = true;
  78. }
  79. /// Used by tests to change the output path to a tmp dir
  80. #[doc(hidden)]
  81. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  82. self.output_path = path.as_ref().to_path_buf();
  83. }
  84. /// Reads all .md files in the `content` directory and create pages
  85. /// out of them
  86. fn parse_site(&mut self) -> Result<()> {
  87. let path = self.base_path.to_string_lossy().replace("\\", "/");
  88. let content_glob = format!("{}/{}", path, "content/**/*.md");
  89. // parent_dir -> Section
  90. let mut sections = BTreeMap::new();
  91. // Glob is giving us the result order so _index will show up first
  92. // for each directory
  93. for entry in glob(&content_glob).unwrap().filter_map(|e| e.ok()) {
  94. let path = entry.as_path();
  95. if path.file_name().unwrap() == "_index.md" {
  96. let section = Section::from_file(&path, &self.config)?;
  97. sections.insert(section.parent_path.clone(), section);
  98. } else {
  99. let page = Page::from_file(&path, &self.config)?;
  100. if sections.contains_key(&page.parent_path) {
  101. sections.get_mut(&page.parent_path).unwrap().pages.push(page.clone());
  102. }
  103. self.pages.insert(page.file_path.clone(), page);
  104. }
  105. }
  106. // Find out the direct subsections of each subsection if there are some
  107. let mut grandparent_paths = HashMap::new();
  108. for section in sections.values() {
  109. let grand_parent = section.parent_path.parent().unwrap().to_path_buf();
  110. grandparent_paths.entry(grand_parent).or_insert_with(|| vec![]).push(section.clone());
  111. }
  112. for (parent_path, section) in sections.iter_mut() {
  113. match grandparent_paths.get(parent_path) {
  114. Some(paths) => section.subsections.extend(paths.clone()),
  115. None => continue,
  116. };
  117. }
  118. self.sections = sections;
  119. Ok(())
  120. }
  121. /// Inject live reload script tag if in live reload mode
  122. fn inject_livereload(&self, html: String) -> String {
  123. if self.live_reload {
  124. return html.replace(
  125. "</body>",
  126. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  127. );
  128. }
  129. html
  130. }
  131. /// Copy the content of the `static` folder into the `public` folder
  132. ///
  133. /// TODO: only copy one file if possible because that would be a waste
  134. /// to do re-copy the whole thing. Benchmark first to see if it's a big difference
  135. pub fn copy_static_directory(&self) -> Result<()> {
  136. let from = Path::new("static");
  137. let target = Path::new("public");
  138. for entry in WalkDir::new(from).into_iter().filter_map(|e| e.ok()) {
  139. let relative_path = entry.path().strip_prefix(&from).unwrap();
  140. let target_path = {
  141. let mut target_path = target.to_path_buf();
  142. target_path.push(relative_path);
  143. target_path
  144. };
  145. if entry.path().is_dir() {
  146. if !target_path.exists() {
  147. create_directory(&target_path)?;
  148. }
  149. } else {
  150. if target_path.exists() {
  151. remove_file(&target_path)?;
  152. }
  153. copy(entry.path(), &target_path)?;
  154. }
  155. }
  156. Ok(())
  157. }
  158. /// Deletes the `public` directory if it exists
  159. pub fn clean(&self) -> Result<()> {
  160. if Path::new("public").exists() {
  161. // Delete current `public` directory so we can start fresh
  162. remove_dir_all("public").chain_err(|| "Couldn't delete `public` directory")?;
  163. }
  164. Ok(())
  165. }
  166. pub fn rebuild_after_content_change(&mut self) -> Result<()> {
  167. self.parse_site()?;
  168. self.build()
  169. }
  170. pub fn rebuild_after_template_change(&mut self) -> Result<()> {
  171. self.templates.full_reload()?;
  172. self.build_pages()
  173. }
  174. pub fn build_pages(&self) -> Result<()> {
  175. let public = self.output_path.clone();
  176. if !public.exists() {
  177. create_directory(&public)?;
  178. }
  179. let mut pages = vec![];
  180. let mut category_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  181. let mut tag_pages: HashMap<String, Vec<&Page>> = HashMap::new();
  182. // First we render the pages themselves
  183. for page in self.pages.values() {
  184. // Copy the nesting of the content directory if we have sections for that page
  185. let mut current_path = public.to_path_buf();
  186. for component in page.url.split("/") {
  187. current_path.push(component);
  188. if !current_path.exists() {
  189. create_directory(&current_path)?;
  190. }
  191. }
  192. // Make sure the folder exists
  193. create_directory(&current_path)?;
  194. // Finally, create a index.html file there with the page rendered
  195. let output = page.render_html(&self.templates, &self.config)?;
  196. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  197. // Copy any asset we found previously into the same directory as the index.html
  198. for asset in &page.assets {
  199. let asset_path = asset.as_path();
  200. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  201. }
  202. pages.push(page);
  203. if let Some(ref category) = page.meta.category {
  204. category_pages.entry(category.to_string()).or_insert_with(|| vec![]).push(page);
  205. }
  206. if let Some(ref tags) = page.meta.tags {
  207. for tag in tags {
  208. tag_pages.entry(tag.to_string()).or_insert_with(|| vec![]).push(page);
  209. }
  210. }
  211. }
  212. // Outputting categories and pages
  213. self.render_categories_and_tags(RenderList::Categories, &category_pages)?;
  214. self.render_categories_and_tags(RenderList::Tags, &tag_pages)?;
  215. // And finally the index page
  216. let mut context = Context::new();
  217. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  218. context.add("pages", &pages);
  219. context.add("config", &self.config);
  220. let index = self.templates.render("index.html", &context)?;
  221. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  222. Ok(())
  223. }
  224. /// Builds the site to the `public` directory after deleting it
  225. pub fn build(&self) -> Result<()> {
  226. self.clean()?;
  227. self.build_pages()?;
  228. self.render_sitemap()?;
  229. if self.config.generate_rss.unwrap() {
  230. self.render_rss_feed()?;
  231. }
  232. self.render_sections()?;
  233. self.copy_static_directory()
  234. }
  235. /// Render the /{categories, list} pages and each individual category/tag page
  236. fn render_categories_and_tags(&self, kind: RenderList, container: &HashMap<String, Vec<&Page>>) -> Result<()> {
  237. if container.is_empty() {
  238. return Ok(());
  239. }
  240. let (name, list_tpl_name, single_tpl_name, var_name) = if kind == RenderList::Categories {
  241. ("categories", "categories.html", "category.html", "category")
  242. } else {
  243. ("tags", "tags.html", "tag.html", "tag")
  244. };
  245. let public = self.output_path.clone();
  246. let mut output_path = public.to_path_buf();
  247. output_path.push(name);
  248. create_directory(&output_path)?;
  249. // First we render the list of categories/tags page
  250. let mut sorted_container = vec![];
  251. for (item, count) in Vec::from_iter(container).into_iter().map(|(a, b)| (a, b.len())) {
  252. sorted_container.push(ListItem::new(item, count));
  253. }
  254. sorted_container.sort_by(|a, b| b.count.cmp(&a.count));
  255. let mut context = Context::new();
  256. context.add(name, &sorted_container);
  257. context.add("config", &self.config);
  258. let list_output = self.templates.render(list_tpl_name, &context)?;
  259. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  260. // and then each individual item
  261. for (item_name, mut pages) in container.clone() {
  262. let mut context = Context::new();
  263. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  264. let slug = slugify(&item_name);
  265. context.add(var_name, &item_name);
  266. context.add(&format!("{}_slug", var_name), &slug);
  267. context.add("pages", &pages);
  268. context.add("config", &self.config);
  269. let single_output = self.templates.render(single_tpl_name, &context)?;
  270. create_directory(&output_path.join(&slug))?;
  271. create_file(
  272. output_path.join(&slug).join("index.html"),
  273. &self.inject_livereload(single_output)
  274. )?;
  275. }
  276. Ok(())
  277. }
  278. fn render_sitemap(&self) -> Result<()> {
  279. let mut context = Context::new();
  280. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  281. let sitemap = self.templates.render("sitemap.xml", &context)?;
  282. create_file(self.output_path.join("sitemap.xml"), &sitemap)?;
  283. Ok(())
  284. }
  285. fn render_rss_feed(&self) -> Result<()> {
  286. let mut context = Context::new();
  287. let mut pages = self.pages.values()
  288. .filter(|p| p.meta.date.is_some())
  289. .take(15) // limit to the last 15 elements
  290. .collect::<Vec<&Page>>();
  291. // Don't generate a RSS feed if none of the pages has a date
  292. if pages.is_empty() {
  293. return Ok(());
  294. }
  295. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  296. context.add("pages", &pages);
  297. context.add("last_build_date", &pages[0].meta.date);
  298. context.add("config", &self.config);
  299. let rss_feed_url = if self.config.base_url.ends_with('/') {
  300. format!("{}{}", self.config.base_url, "feed.xml")
  301. } else {
  302. format!("{}/{}", self.config.base_url, "feed.xml")
  303. };
  304. context.add("feed_url", &rss_feed_url);
  305. let sitemap = self.templates.render("rss.xml", &context)?;
  306. create_file(self.output_path.join("rss.xml"), &sitemap)?;
  307. Ok(())
  308. }
  309. fn render_sections(&self) -> Result<()> {
  310. let public = self.output_path.clone();
  311. for section in self.sections.values() {
  312. let mut output_path = public.to_path_buf();
  313. for component in &section.components {
  314. output_path.push(component);
  315. if !output_path.exists() {
  316. create_directory(&output_path)?;
  317. }
  318. }
  319. let output = section.render_html(&self.templates, &self.config)?;
  320. create_file(output_path.join("index.html"), &self.inject_livereload(output))?;
  321. }
  322. Ok(())
  323. }
  324. }