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.

501 lines
16KB

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