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.

728 lines
25KB

  1. extern crate tera;
  2. extern crate rayon;
  3. extern crate glob;
  4. extern crate walkdir;
  5. extern crate serde;
  6. #[macro_use]
  7. extern crate serde_derive;
  8. extern crate sass_rs;
  9. #[macro_use]
  10. extern crate errors;
  11. extern crate config;
  12. extern crate utils;
  13. extern crate front_matter;
  14. extern crate templates;
  15. extern crate pagination;
  16. extern crate taxonomies;
  17. extern crate content;
  18. #[cfg(test)]
  19. extern crate tempdir;
  20. use std::collections::HashMap;
  21. use std::fs::{remove_dir_all, copy, create_dir_all};
  22. use std::mem;
  23. use std::path::{Path, PathBuf};
  24. use glob::glob;
  25. use tera::{Tera, Context};
  26. use walkdir::WalkDir;
  27. use sass_rs::{Options, compile_file};
  28. use errors::{Result, ResultExt};
  29. use config::{Config, get_config};
  30. use utils::fs::{create_file, create_directory, ensure_directory_exists};
  31. use content::{Page, Section, populate_previous_and_next_pages, sort_pages};
  32. use templates::{GUTENBERG_TERA, global_fns, render_redirect_template};
  33. use front_matter::{SortBy, InsertAnchor};
  34. use taxonomies::Taxonomy;
  35. use pagination::Paginator;
  36. use rayon::prelude::*;
  37. /// The sitemap only needs links and potentially date so we trim down
  38. /// all pages to only that
  39. #[derive(Debug, Serialize)]
  40. struct SitemapEntry {
  41. permalink: String,
  42. date: Option<String>,
  43. }
  44. impl SitemapEntry {
  45. pub fn new(permalink: String, date: Option<String>) -> SitemapEntry {
  46. SitemapEntry { permalink, date }
  47. }
  48. }
  49. #[derive(Debug)]
  50. pub struct Site {
  51. /// The base path of the gutenberg site
  52. pub base_path: PathBuf,
  53. /// The parsed config for the site
  54. pub config: Config,
  55. pub pages: HashMap<PathBuf, Page>,
  56. pub sections: HashMap<PathBuf, Section>,
  57. pub tera: Tera,
  58. live_reload: bool,
  59. output_path: PathBuf,
  60. static_path: PathBuf,
  61. pub tags: Option<Taxonomy>,
  62. pub categories: Option<Taxonomy>,
  63. /// A map of all .md files (section and pages) and their permalink
  64. /// We need that if there are relative links in the content that need to be resolved
  65. pub permalinks: HashMap<String, String>,
  66. }
  67. impl Site {
  68. /// Parse a site at the given path. Defaults to the current dir
  69. /// Passing in a path is only used in tests
  70. pub fn new<P: AsRef<Path>>(path: P, config_file: &str) -> Result<Site> {
  71. let path = path.as_ref();
  72. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
  73. let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
  74. tera.extend(&GUTENBERG_TERA)?;
  75. let site = Site {
  76. base_path: path.to_path_buf(),
  77. config: get_config(path, config_file),
  78. pages: HashMap::new(),
  79. sections: HashMap::new(),
  80. tera: tera,
  81. live_reload: false,
  82. output_path: path.join("public"),
  83. static_path: path.join("static"),
  84. tags: None,
  85. categories: None,
  86. permalinks: HashMap::new(),
  87. };
  88. Ok(site)
  89. }
  90. /// What the function name says
  91. pub fn enable_live_reload(&mut self) {
  92. self.live_reload = true;
  93. }
  94. /// Get all the orphan (== without section) pages in the site
  95. pub fn get_all_orphan_pages(&self) -> Vec<&Page> {
  96. let mut pages_in_sections = vec![];
  97. let mut orphans = vec![];
  98. for s in self.sections.values() {
  99. pages_in_sections.extend(s.all_pages_path());
  100. }
  101. for page in self.pages.values() {
  102. if !pages_in_sections.contains(&page.file.path) {
  103. orphans.push(page);
  104. }
  105. }
  106. orphans
  107. }
  108. /// Used by tests to change the output path to a tmp dir
  109. #[doc(hidden)]
  110. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  111. self.output_path = path.as_ref().to_path_buf();
  112. }
  113. /// Reads all .md files in the `content` directory and create pages/sections
  114. /// out of them
  115. pub fn load(&mut self) -> Result<()> {
  116. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  117. let content_glob = format!("{}/{}", base_path, "content/**/*.md");
  118. let (section_entries, page_entries): (Vec<_>, Vec<_>) = glob(&content_glob)
  119. .unwrap()
  120. .filter_map(|e| e.ok())
  121. .partition(|entry| entry.as_path().file_name().unwrap() == "_index.md");
  122. let sections = {
  123. let config = &self.config;
  124. section_entries
  125. .into_par_iter()
  126. .filter(|entry| entry.as_path().file_name().unwrap() == "_index.md")
  127. .map(|entry| {
  128. let path = entry.as_path();
  129. Section::from_file(path, config)
  130. }).collect::<Vec<_>>()
  131. };
  132. let pages = {
  133. let config = &self.config;
  134. page_entries
  135. .into_par_iter()
  136. .filter(|entry| entry.as_path().file_name().unwrap() != "_index.md")
  137. .map(|entry| {
  138. let path = entry.as_path();
  139. Page::from_file(path, config)
  140. }).collect::<Vec<_>>()
  141. };
  142. // Kinda duplicated code for add_section/add_page but necessary to do it that
  143. // way because of the borrow checker
  144. for section in sections {
  145. let s = section?;
  146. self.add_section(s, false)?;
  147. }
  148. // Insert a default index section if necessary so we don't need to create
  149. // a _index.md to render the index page
  150. let index_path = self.base_path.join("content").join("_index.md");
  151. if !self.sections.contains_key(&index_path) {
  152. let mut index_section = Section::default();
  153. index_section.permalink = self.config.make_permalink("");
  154. // TODO: need to insert into permalinks too
  155. self.sections.insert(index_path, index_section);
  156. }
  157. let mut pages_insert_anchors = HashMap::new();
  158. for page in pages {
  159. let p = page?;
  160. pages_insert_anchors.insert(p.file.path.clone(), self.find_parent_section_insert_anchor(&p.file.parent.clone()));
  161. self.add_page(p, false)?;
  162. }
  163. {
  164. // Another silly thing needed to not borrow &self in parallel and
  165. // make the borrow checker happy
  166. let permalinks = &self.permalinks;
  167. let tera = &self.tera;
  168. let config = &self.config;
  169. self.pages.par_iter_mut()
  170. .map(|(_, page)| page)
  171. .map(|page| {
  172. let insert_anchor = pages_insert_anchors[&page.file.path];
  173. page.render_markdown(permalinks, tera, config, insert_anchor)
  174. })
  175. .fold(|| Ok(()), Result::and)
  176. .reduce(|| Ok(()), Result::and)?;
  177. self.sections.par_iter_mut()
  178. .map(|(_, section)| section)
  179. .map(|section| section.render_markdown(permalinks, tera, config))
  180. .fold(|| Ok(()), Result::and)
  181. .reduce(|| Ok(()), Result::and)?;
  182. }
  183. self.populate_sections();
  184. self.populate_tags_and_categories();
  185. self.tera.register_global_function("get_page", global_fns::make_get_page(&self.pages));
  186. self.tera.register_global_function("get_section", global_fns::make_get_section(&self.sections));
  187. self.register_get_url_fn();
  188. Ok(())
  189. }
  190. /// Separate fn as it can be called in the serve command
  191. pub fn register_get_url_fn(&mut self) {
  192. self.tera.register_global_function(
  193. "get_url",
  194. global_fns::make_get_url(self.permalinks.clone(), self.config.clone())
  195. );
  196. }
  197. /// Add a page to the site
  198. /// The `render` parameter is used in the serve command, when rebuilding a page.
  199. /// If `true`, it will also render the markdown for that page
  200. /// Returns the previous page struct if there was one
  201. pub fn add_page(&mut self, page: Page, render: bool) -> Result<Option<Page>> {
  202. let path = page.file.path.clone();
  203. self.permalinks.insert(page.file.relative.clone(), page.permalink.clone());
  204. let prev = self.pages.insert(page.file.path.clone(), page);
  205. if render {
  206. let insert_anchor = self.find_parent_section_insert_anchor(&self.pages[&path].file.parent);
  207. let mut page = self.pages.get_mut(&path).unwrap();
  208. page.render_markdown(&self.permalinks, &self.tera, &self.config, insert_anchor)?;
  209. }
  210. Ok(prev)
  211. }
  212. /// Add a section to the site
  213. /// The `render` parameter is used in the serve command, when rebuilding a page.
  214. /// If `true`, it will also render the markdown for that page
  215. /// Returns the previous section struct if there was one
  216. pub fn add_section(&mut self, section: Section, render: bool) -> Result<Option<Section>> {
  217. let path = section.file.path.clone();
  218. self.permalinks.insert(section.file.relative.clone(), section.permalink.clone());
  219. let prev = self.sections.insert(section.file.path.clone(), section);
  220. if render {
  221. let mut section = self.sections.get_mut(&path).unwrap();
  222. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  223. }
  224. Ok(prev)
  225. }
  226. /// Finds the insert_anchor for the parent section of the directory at `path`.
  227. /// Defaults to `AnchorInsert::None` if no parent section found
  228. pub fn find_parent_section_insert_anchor(&self, parent_path: &PathBuf) -> InsertAnchor {
  229. match self.sections.get(&parent_path.join("_index.md")) {
  230. Some(s) => s.meta.insert_anchor.unwrap(),
  231. None => InsertAnchor::None
  232. }
  233. }
  234. /// Find out the direct subsections of each subsection if there are some
  235. /// as well as the pages for each section
  236. pub fn populate_sections(&mut self) {
  237. let mut grandparent_paths = HashMap::new();
  238. for section in self.sections.values_mut() {
  239. if let Some(ref grand_parent) = section.file.grand_parent {
  240. grandparent_paths.entry(grand_parent.to_path_buf()).or_insert_with(|| vec![]).push(section.clone());
  241. }
  242. // Make sure the pages of a section are empty since we can call that many times on `serve`
  243. section.pages = vec![];
  244. section.ignored_pages = vec![];
  245. }
  246. for page in self.pages.values() {
  247. let parent_section_path = page.file.parent.join("_index.md");
  248. if self.sections.contains_key(&parent_section_path) {
  249. self.sections.get_mut(&parent_section_path).unwrap().pages.push(page.clone());
  250. }
  251. }
  252. for section in self.sections.values_mut() {
  253. match grandparent_paths.get(&section.file.parent) {
  254. Some(paths) => section.subsections.extend(paths.clone()),
  255. None => continue,
  256. };
  257. }
  258. self.sort_sections_pages(None);
  259. }
  260. /// Sorts the pages of the section at the given path
  261. /// By default will sort all sections but can be made to only sort a single one by providing a path
  262. pub fn sort_sections_pages(&mut self, only: Option<&Path>) {
  263. for (path, section) in &mut self.sections {
  264. if let Some(p) = only {
  265. if p != path {
  266. continue;
  267. }
  268. }
  269. let pages = mem::replace(&mut section.pages, vec![]);
  270. let (sorted_pages, cannot_be_sorted_pages) = sort_pages(pages, section.meta.sort_by());
  271. section.pages = populate_previous_and_next_pages(&sorted_pages);
  272. section.ignored_pages = cannot_be_sorted_pages;
  273. }
  274. }
  275. /// Find all the tags and categories if it's asked in the config
  276. pub fn populate_tags_and_categories(&mut self) {
  277. let generate_tags_pages = self.config.generate_tags_pages.unwrap();
  278. let generate_categories_pages = self.config.generate_categories_pages.unwrap();
  279. if !generate_tags_pages && !generate_categories_pages {
  280. return;
  281. }
  282. // TODO: can we pass a reference?
  283. let (tags, categories) = Taxonomy::find_tags_and_categories(
  284. self.pages.values().cloned().collect::<Vec<_>>().as_slice()
  285. );
  286. if generate_tags_pages {
  287. self.tags = Some(tags);
  288. }
  289. if generate_categories_pages {
  290. self.categories = Some(categories);
  291. }
  292. }
  293. /// Inject live reload script tag if in live reload mode
  294. fn inject_livereload(&self, html: String) -> String {
  295. if self.live_reload {
  296. return html.replace(
  297. "</body>",
  298. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  299. );
  300. }
  301. html
  302. }
  303. /// Copy static file to public directory.
  304. pub fn copy_static_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
  305. let relative_path = path.as_ref().strip_prefix(&self.static_path).unwrap();
  306. let target_path = self.output_path.join(relative_path);
  307. if let Some(parent_directory) = target_path.parent() {
  308. create_dir_all(parent_directory)?;
  309. }
  310. copy(path.as_ref(), &target_path)?;
  311. Ok(())
  312. }
  313. /// Copy the content of the `static` folder into the `public` folder
  314. pub fn copy_static_directory(&self) -> Result<()> {
  315. for entry in WalkDir::new(&self.static_path).into_iter().filter_map(|e| e.ok()) {
  316. let relative_path = entry.path().strip_prefix(&self.static_path).unwrap();
  317. let target_path = self.output_path.join(relative_path);
  318. if entry.path().is_dir() {
  319. if !target_path.exists() {
  320. create_directory(&target_path)?;
  321. }
  322. } else {
  323. let entry_fullpath = self.base_path.join(entry.path());
  324. self.copy_static_file(entry_fullpath)?;
  325. }
  326. }
  327. Ok(())
  328. }
  329. /// Deletes the `public` directory if it exists
  330. pub fn clean(&self) -> Result<()> {
  331. if self.output_path.exists() {
  332. // Delete current `public` directory so we can start fresh
  333. remove_dir_all(&self.output_path).chain_err(|| "Couldn't delete `public` directory")?;
  334. }
  335. Ok(())
  336. }
  337. /// Renders a single content page
  338. pub fn render_page(&self, page: &Page) -> Result<()> {
  339. ensure_directory_exists(&self.output_path)?;
  340. // Copy the nesting of the content directory if we have sections for that page
  341. let mut current_path = self.output_path.to_path_buf();
  342. for component in page.path.split('/') {
  343. current_path.push(component);
  344. if !current_path.exists() {
  345. create_directory(&current_path)?;
  346. }
  347. }
  348. // Make sure the folder exists
  349. create_directory(&current_path)?;
  350. // Finally, create a index.html file there with the page rendered
  351. let output = page.render_html(&self.tera, &self.config)?;
  352. create_file(&current_path.join("index.html"), &self.inject_livereload(output))?;
  353. // Copy any asset we found previously into the same directory as the index.html
  354. for asset in &page.assets {
  355. let asset_path = asset.as_path();
  356. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  357. }
  358. Ok(())
  359. }
  360. /// Deletes the `public` directory and builds the site
  361. pub fn build(&self) -> Result<()> {
  362. self.clean()?;
  363. // Render aliases first to allow overwriting
  364. self.render_aliases()?;
  365. self.render_sections()?;
  366. self.render_orphan_pages()?;
  367. self.render_sitemap()?;
  368. if self.config.generate_rss.unwrap() {
  369. self.render_rss_feed()?;
  370. }
  371. self.render_robots()?;
  372. // `render_categories` and `render_tags` will check whether the config allows
  373. // them to render or not
  374. self.render_categories()?;
  375. self.render_tags()?;
  376. if self.config.compile_sass.unwrap() {
  377. self.compile_sass()?;
  378. }
  379. self.copy_static_directory()
  380. }
  381. pub fn compile_sass(&self) -> Result<()> {
  382. ensure_directory_exists(&self.output_path)?;
  383. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  384. let sass_glob = format!("{}/{}", base_path, "sass/**/*.scss");
  385. let files = glob(&sass_glob)
  386. .unwrap()
  387. .filter_map(|e| e.ok())
  388. .filter(|entry| !entry.as_path().file_name().unwrap().to_string_lossy().starts_with('_'))
  389. .collect::<Vec<_>>();
  390. for file in files {
  391. let name = file.as_path().file_stem().unwrap().to_string_lossy();
  392. let css = match compile_file(file.as_path(), Options::default()) {
  393. Ok(c) => c,
  394. Err(e) => bail!(e)
  395. };
  396. create_file(&self.output_path.join(format!("{}.css", name)), &css)?;
  397. }
  398. Ok(())
  399. }
  400. pub fn render_aliases(&self) -> Result<()> {
  401. for page in self.pages.values() {
  402. if let Some(ref aliases) = page.meta.aliases {
  403. for alias in aliases {
  404. let mut output_path = self.output_path.to_path_buf();
  405. for component in alias.split('/') {
  406. output_path.push(&component);
  407. if !output_path.exists() {
  408. create_directory(&output_path)?;
  409. }
  410. }
  411. create_file(&output_path.join("index.html"), &render_redirect_template(&page.permalink, &self.tera)?)?;
  412. }
  413. }
  414. }
  415. Ok(())
  416. }
  417. /// Renders robots.txt
  418. pub fn render_robots(&self) -> Result<()> {
  419. ensure_directory_exists(&self.output_path)?;
  420. create_file(
  421. &self.output_path.join("robots.txt"),
  422. &self.tera.render("robots.txt", &Context::new())?
  423. )
  424. }
  425. /// Renders all categories and the single category pages if there are some
  426. pub fn render_categories(&self) -> Result<()> {
  427. if let Some(ref categories) = self.categories {
  428. self.render_taxonomy(categories)?;
  429. }
  430. Ok(())
  431. }
  432. /// Renders all tags and the single tag pages if there are some
  433. pub fn render_tags(&self) -> Result<()> {
  434. if let Some(ref tags) = self.tags {
  435. self.render_taxonomy(tags)?;
  436. }
  437. Ok(())
  438. }
  439. fn render_taxonomy(&self, taxonomy: &Taxonomy) -> Result<()> {
  440. if taxonomy.items.is_empty() {
  441. return Ok(())
  442. }
  443. ensure_directory_exists(&self.output_path)?;
  444. let output_path = self.output_path.join(&taxonomy.get_list_name());
  445. let list_output = taxonomy.render_list(&self.tera, &self.config)?;
  446. create_directory(&output_path)?;
  447. create_file(&output_path.join("index.html"), &self.inject_livereload(list_output))?;
  448. taxonomy
  449. .items
  450. .par_iter()
  451. .map(|item| {
  452. let single_output = taxonomy.render_single_item(item, &self.tera, &self.config)?;
  453. create_directory(&output_path.join(&item.slug))?;
  454. create_file(
  455. &output_path.join(&item.slug).join("index.html"),
  456. &self.inject_livereload(single_output)
  457. )
  458. })
  459. .fold(|| Ok(()), Result::and)
  460. .reduce(|| Ok(()), Result::and)
  461. }
  462. /// What it says on the tin
  463. pub fn render_sitemap(&self) -> Result<()> {
  464. ensure_directory_exists(&self.output_path)?;
  465. let mut context = Context::new();
  466. context.add(
  467. "pages",
  468. &self.pages.values().map(|p| SitemapEntry::new(p.permalink.clone(), p.meta.date.clone())).collect::<Vec<_>>()
  469. );
  470. context.add(
  471. "sections",
  472. &self.sections.values().map(|s| SitemapEntry::new(s.permalink.clone(), None)).collect::<Vec<_>>()
  473. );
  474. let mut categories = vec![];
  475. if let Some(ref c) = self.categories {
  476. let name = c.get_list_name();
  477. categories.push(SitemapEntry::new(self.config.make_permalink(&name), None));
  478. for item in &c.items {
  479. categories.push(
  480. SitemapEntry::new(self.config.make_permalink(&format!("{}/{}", &name, item.slug)), None),
  481. );
  482. }
  483. }
  484. context.add("categories", &categories);
  485. let mut tags = vec![];
  486. if let Some(ref t) = self.tags {
  487. let name = t.get_list_name();
  488. tags.push(SitemapEntry::new(self.config.make_permalink(&name), None));
  489. for item in &t.items {
  490. tags.push(
  491. SitemapEntry::new(self.config.make_permalink(&format!("{}/{}", &name, item.slug)), None),
  492. );
  493. }
  494. }
  495. context.add("tags", &tags);
  496. let sitemap = self.tera.render("sitemap.xml", &context)?;
  497. create_file(&self.output_path.join("sitemap.xml"), &sitemap)?;
  498. Ok(())
  499. }
  500. pub fn render_rss_feed(&self) -> Result<()> {
  501. ensure_directory_exists(&self.output_path)?;
  502. let mut context = Context::new();
  503. let pages = self.pages.values()
  504. .filter(|p| p.meta.date.is_some())
  505. .cloned()
  506. .collect::<Vec<Page>>();
  507. // Don't generate a RSS feed if none of the pages has a date
  508. if pages.is_empty() {
  509. return Ok(());
  510. }
  511. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  512. context.add("last_build_date", &sorted_pages[0].meta.date);
  513. // limit to the last n elements)
  514. context.add("pages", &sorted_pages.iter().take(self.config.rss_limit.unwrap()).collect::<Vec<_>>());
  515. context.add("config", &self.config);
  516. let rss_feed_url = if self.config.base_url.ends_with('/') {
  517. format!("{}{}", self.config.base_url, "rss.xml")
  518. } else {
  519. format!("{}/{}", self.config.base_url, "rss.xml")
  520. };
  521. context.add("feed_url", &rss_feed_url);
  522. let sitemap = self.tera.render("rss.xml", &context)?;
  523. create_file(&self.output_path.join("rss.xml"), &sitemap)?;
  524. Ok(())
  525. }
  526. /// Renders a single section
  527. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  528. ensure_directory_exists(&self.output_path)?;
  529. let public = self.output_path.clone();
  530. let mut output_path = public.to_path_buf();
  531. for component in &section.file.components {
  532. output_path.push(component);
  533. if !output_path.exists() {
  534. create_directory(&output_path)?;
  535. }
  536. }
  537. if render_pages {
  538. section
  539. .pages
  540. .par_iter()
  541. .map(|p| self.render_page(p))
  542. .fold(|| Ok(()), Result::and)
  543. .reduce(|| Ok(()), Result::and)?;
  544. }
  545. if !section.meta.should_render() {
  546. return Ok(());
  547. }
  548. if let Some(ref redirect_to) = section.meta.redirect_to {
  549. let permalink = self.config.make_permalink(redirect_to);
  550. create_file(&output_path.join("index.html"), &render_redirect_template(&permalink, &self.tera)?)?;
  551. return Ok(());
  552. }
  553. if section.meta.is_paginated() {
  554. self.render_paginated(&output_path, section)?;
  555. } else {
  556. let output = section.render_html(&self.tera, &self.config)?;
  557. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  558. }
  559. Ok(())
  560. }
  561. pub fn render_index(&self) -> Result<()> {
  562. self.render_section(&self.sections[&self.base_path.join("content").join("_index.md")], false)
  563. }
  564. /// Renders all sections
  565. pub fn render_sections(&self) -> Result<()> {
  566. self.sections
  567. .values()
  568. .collect::<Vec<_>>()
  569. .into_par_iter()
  570. .map(|s| self.render_section(s, true))
  571. .fold(|| Ok(()), Result::and)
  572. .reduce(|| Ok(()), Result::and)
  573. }
  574. /// Renders all pages that do not belong to any sections
  575. pub fn render_orphan_pages(&self) -> Result<()> {
  576. ensure_directory_exists(&self.output_path)?;
  577. for page in self.get_all_orphan_pages() {
  578. self.render_page(page)?;
  579. }
  580. Ok(())
  581. }
  582. /// Renders a list of pages when the section/index is wanting pagination.
  583. pub fn render_paginated(&self, output_path: &Path, section: &Section) -> Result<()> {
  584. ensure_directory_exists(&self.output_path)?;
  585. let paginate_path = match section.meta.paginate_path {
  586. Some(ref s) => s.clone(),
  587. None => unreachable!()
  588. };
  589. let paginator = Paginator::new(&section.pages, section);
  590. let folder_path = output_path.join(&paginate_path);
  591. create_directory(&folder_path)?;
  592. paginator
  593. .pagers
  594. .par_iter()
  595. .enumerate()
  596. .map(|(i, pager)| {
  597. let page_path = folder_path.join(&format!("{}", i + 1));
  598. create_directory(&page_path)?;
  599. let output = paginator.render_pager(pager, &self.config, &self.tera)?;
  600. if i > 0 {
  601. create_file(&page_path.join("index.html"), &self.inject_livereload(output))?;
  602. } else {
  603. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  604. create_file(&page_path.join("index.html"), &render_redirect_template(&section.permalink, &self.tera)?)?;
  605. }
  606. Ok(())
  607. })
  608. .fold(|| Ok(()), Result::and)
  609. .reduce(|| Ok(()), Result::and)
  610. }
  611. }