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.

467 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. ("robots.txt", include_str!("templates/robots.txt")),
  21. ]).unwrap();
  22. tera
  23. };
  24. }
  25. #[derive(Debug, PartialEq)]
  26. enum RenderList {
  27. Tags,
  28. Categories,
  29. }
  30. /// A tag or category
  31. #[derive(Debug, Serialize, PartialEq)]
  32. struct ListItem {
  33. name: String,
  34. slug: String,
  35. count: usize,
  36. }
  37. impl ListItem {
  38. pub fn new(name: &str, count: usize) -> ListItem {
  39. ListItem {
  40. name: name.to_string(),
  41. slug: slugify(name),
  42. count: count,
  43. }
  44. }
  45. }
  46. #[derive(Debug)]
  47. pub struct Site {
  48. pub base_path: PathBuf,
  49. pub config: Config,
  50. pub pages: HashMap<PathBuf, Page>,
  51. pub sections: BTreeMap<PathBuf, Section>,
  52. pub templates: Tera,
  53. live_reload: bool,
  54. output_path: PathBuf,
  55. pub tags: HashMap<String, Vec<PathBuf>>,
  56. pub categories: HashMap<String, Vec<PathBuf>>,
  57. }
  58. impl Site {
  59. /// Parse a site at the given path. Defaults to the current dir
  60. /// Passing in a path is only used in tests
  61. pub fn new<P: AsRef<Path>>(path: P) -> Result<Site> {
  62. let path = path.as_ref();
  63. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*");
  64. let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
  65. tera.extend(&GUTENBERG_TERA)?;
  66. let site = Site {
  67. base_path: path.to_path_buf(),
  68. config: get_config(path),
  69. pages: HashMap::new(),
  70. sections: BTreeMap::new(),
  71. templates: tera,
  72. live_reload: false,
  73. output_path: PathBuf::from("public"),
  74. tags: HashMap::new(),
  75. categories: HashMap::new(),
  76. };
  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. if self.config.generate_categories_pages.unwrap() {
  229. self.render_categories_and_tags(RenderList::Categories)?;
  230. }
  231. if self.config.generate_tags_pages.unwrap() {
  232. self.render_categories_and_tags(RenderList::Tags)?;
  233. }
  234. // And finally the index page
  235. let mut context = Context::new();
  236. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  237. context.add("pages", &pages);
  238. context.add("config", &self.config);
  239. let index = self.templates.render("index.html", &context)?;
  240. create_file(public.join("index.html"), &self.inject_livereload(index))?;
  241. Ok(())
  242. }
  243. /// Builds the site to the `public` directory after deleting it
  244. pub fn build(&self) -> Result<()> {
  245. self.clean()?;
  246. self.build_pages()?;
  247. self.render_sitemap()?;
  248. if self.config.generate_rss.unwrap() {
  249. self.render_rss_feed()?;
  250. }
  251. self.render_robots()?;
  252. self.render_sections()?;
  253. self.copy_static_directory()
  254. }
  255. fn render_robots(&self) -> Result<()> {
  256. create_file(
  257. self.output_path.join("robots.txt"),
  258. &self.templates.render("robots.txt", &Context::new())?
  259. )
  260. }
  261. /// Render the /{categories, list} pages and each individual category/tag page
  262. /// They are the same thing fundamentally, a list of pages with something in common
  263. fn render_categories_and_tags(&self, kind: RenderList) -> Result<()> {
  264. let items = match kind {
  265. RenderList::Categories => &self.categories,
  266. RenderList::Tags => &self.tags,
  267. };
  268. if items.is_empty() {
  269. return Ok(());
  270. }
  271. let (list_tpl_name, single_tpl_name, name, var_name) = if kind == RenderList::Categories {
  272. ("categories.html", "category.html", "categories", "category")
  273. } else {
  274. ("tags.html", "tag.html", "tags", "tag")
  275. };
  276. // Create the categories/tags directory first
  277. let public = self.output_path.clone();
  278. let mut output_path = public.to_path_buf();
  279. output_path.push(name);
  280. create_directory(&output_path)?;
  281. // Then render the index page for that kind.
  282. // We sort by number of page in that category/tag
  283. let mut sorted_items = vec![];
  284. for (item, count) in Vec::from_iter(items).into_iter().map(|(a, b)| (a, b.len())) {
  285. sorted_items.push(ListItem::new(&item, count));
  286. }
  287. sorted_items.sort_by(|a, b| b.count.cmp(&a.count));
  288. let mut context = Context::new();
  289. context.add(name, &sorted_items);
  290. context.add("config", &self.config);
  291. // And render it immediately
  292. let list_output = self.templates.render(list_tpl_name, &context)?;
  293. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  294. // Now, each individual item
  295. for (item_name, pages_paths) in items.iter() {
  296. let mut pages: Vec<&Page> = self.pages
  297. .iter()
  298. .filter(|&(path, _)| pages_paths.contains(&path))
  299. .map(|(_, page)| page)
  300. .collect();
  301. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  302. let mut context = Context::new();
  303. let slug = slugify(&item_name);
  304. context.add(var_name, &item_name);
  305. context.add(&format!("{}_slug", var_name), &slug);
  306. context.add("pages", &pages);
  307. context.add("config", &self.config);
  308. let single_output = self.templates.render(single_tpl_name, &context)?;
  309. create_directory(&output_path.join(&slug))?;
  310. create_file(
  311. output_path.join(&slug).join("index.html"),
  312. &self.inject_livereload(single_output)
  313. )?;
  314. }
  315. Ok(())
  316. }
  317. fn render_sitemap(&self) -> Result<()> {
  318. let mut context = Context::new();
  319. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  320. context.add("sections", &self.sections.values().collect::<Vec<&Section>>());
  321. let mut categories = vec![];
  322. if self.config.generate_categories_pages.unwrap() {
  323. if !self.categories.is_empty() {
  324. categories.push(self.config.make_permalink("categories"));
  325. for category in self.categories.keys() {
  326. categories.push(
  327. self.config.make_permalink(&format!("categories/{}", slugify(category)))
  328. );
  329. }
  330. }
  331. }
  332. context.add("categories", &categories);
  333. let mut tags = vec![];
  334. if self.config.generate_tags_pages.unwrap() {
  335. if !self.tags.is_empty() {
  336. tags.push(self.config.make_permalink("tags"));
  337. for tag in self.tags.keys() {
  338. tags.push(
  339. self.config.make_permalink(&format!("tags/{}", slugify(tag)))
  340. );
  341. }
  342. }
  343. }
  344. context.add("tags", &tags);
  345. let sitemap = self.templates.render("sitemap.xml", &context)?;
  346. create_file(self.output_path.join("sitemap.xml"), &sitemap)?;
  347. Ok(())
  348. }
  349. fn render_rss_feed(&self) -> Result<()> {
  350. let mut context = Context::new();
  351. let mut pages = self.pages.values()
  352. .filter(|p| p.meta.date.is_some())
  353. .take(15) // limit to the last 15 elements
  354. .collect::<Vec<&Page>>();
  355. // Don't generate a RSS feed if none of the pages has a date
  356. if pages.is_empty() {
  357. return Ok(());
  358. }
  359. pages.sort_by(|a, b| a.partial_cmp(b).unwrap());
  360. context.add("pages", &pages);
  361. context.add("last_build_date", &pages[0].meta.date);
  362. context.add("config", &self.config);
  363. let rss_feed_url = if self.config.base_url.ends_with('/') {
  364. format!("{}{}", self.config.base_url, "feed.xml")
  365. } else {
  366. format!("{}/{}", self.config.base_url, "feed.xml")
  367. };
  368. context.add("feed_url", &rss_feed_url);
  369. let sitemap = self.templates.render("rss.xml", &context)?;
  370. create_file(self.output_path.join("rss.xml"), &sitemap)?;
  371. Ok(())
  372. }
  373. fn render_sections(&self) -> Result<()> {
  374. let public = self.output_path.clone();
  375. for section in self.sections.values() {
  376. let mut output_path = public.to_path_buf();
  377. for component in &section.components {
  378. output_path.push(component);
  379. if !output_path.exists() {
  380. create_directory(&output_path)?;
  381. }
  382. }
  383. let output = section.render_html(&self.templates, &self.config)?;
  384. create_file(output_path.join("index.html"), &self.inject_livereload(output))?;
  385. }
  386. Ok(())
  387. }
  388. }