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.

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