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.

516 lines
17KB

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