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.

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