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.

450 lines
15KB

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