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.

726 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.tera.register_global_function("get_static_url", global_fns::make_get_static_url(self.config.clone()));
  188. self.register_get_url_fn();
  189. Ok(())
  190. }
  191. /// Separate fn as it can be called in the serve command
  192. pub fn register_get_url_fn(&mut self) {
  193. self.tera.register_global_function("get_url", global_fns::make_get_url(self.permalinks.clone()));
  194. }
  195. /// Add a page to the site
  196. /// The `render` parameter is used in the serve command, when rebuilding a page.
  197. /// If `true`, it will also render the markdown for that page
  198. /// Returns the previous page struct if there was one
  199. pub fn add_page(&mut self, page: Page, render: bool) -> Result<Option<Page>> {
  200. let path = page.file.path.clone();
  201. self.permalinks.insert(page.file.relative.clone(), page.permalink.clone());
  202. let prev = self.pages.insert(page.file.path.clone(), page);
  203. if render {
  204. let insert_anchor = self.find_parent_section_insert_anchor(&self.pages[&path].file.parent);
  205. let mut page = self.pages.get_mut(&path).unwrap();
  206. page.render_markdown(&self.permalinks, &self.tera, &self.config, insert_anchor)?;
  207. }
  208. Ok(prev)
  209. }
  210. /// Add a section to the site
  211. /// The `render` parameter is used in the serve command, when rebuilding a page.
  212. /// If `true`, it will also render the markdown for that page
  213. /// Returns the previous section struct if there was one
  214. pub fn add_section(&mut self, section: Section, render: bool) -> Result<Option<Section>> {
  215. let path = section.file.path.clone();
  216. self.permalinks.insert(section.file.relative.clone(), section.permalink.clone());
  217. let prev = self.sections.insert(section.file.path.clone(), section);
  218. if render {
  219. let mut section = self.sections.get_mut(&path).unwrap();
  220. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  221. }
  222. Ok(prev)
  223. }
  224. /// Finds the insert_anchor for the parent section of the directory at `path`.
  225. /// Defaults to `AnchorInsert::None` if no parent section found
  226. pub fn find_parent_section_insert_anchor(&self, parent_path: &PathBuf) -> InsertAnchor {
  227. match self.sections.get(&parent_path.join("_index.md")) {
  228. Some(s) => s.meta.insert_anchor.unwrap(),
  229. None => InsertAnchor::None
  230. }
  231. }
  232. /// Find out the direct subsections of each subsection if there are some
  233. /// as well as the pages for each section
  234. pub fn populate_sections(&mut self) {
  235. let mut grandparent_paths = HashMap::new();
  236. for section in self.sections.values_mut() {
  237. if let Some(ref grand_parent) = section.file.grand_parent {
  238. grandparent_paths.entry(grand_parent.to_path_buf()).or_insert_with(|| vec![]).push(section.clone());
  239. }
  240. // Make sure the pages of a section are empty since we can call that many times on `serve`
  241. section.pages = vec![];
  242. section.ignored_pages = vec![];
  243. }
  244. for page in self.pages.values() {
  245. let parent_section_path = page.file.parent.join("_index.md");
  246. if self.sections.contains_key(&parent_section_path) {
  247. self.sections.get_mut(&parent_section_path).unwrap().pages.push(page.clone());
  248. }
  249. }
  250. for section in self.sections.values_mut() {
  251. match grandparent_paths.get(&section.file.parent) {
  252. Some(paths) => section.subsections.extend(paths.clone()),
  253. None => continue,
  254. };
  255. }
  256. self.sort_sections_pages(None);
  257. }
  258. /// Sorts the pages of the section at the given path
  259. /// By default will sort all sections but can be made to only sort a single one by providing a path
  260. pub fn sort_sections_pages(&mut self, only: Option<&Path>) {
  261. for (path, section) in &mut self.sections {
  262. if let Some(p) = only {
  263. if p != path {
  264. continue;
  265. }
  266. }
  267. let pages = mem::replace(&mut section.pages, vec![]);
  268. let (sorted_pages, cannot_be_sorted_pages) = sort_pages(pages, section.meta.sort_by());
  269. section.pages = populate_previous_and_next_pages(&sorted_pages);
  270. section.ignored_pages = cannot_be_sorted_pages;
  271. }
  272. }
  273. /// Find all the tags and categories if it's asked in the config
  274. pub fn populate_tags_and_categories(&mut self) {
  275. let generate_tags_pages = self.config.generate_tags_pages.unwrap();
  276. let generate_categories_pages = self.config.generate_categories_pages.unwrap();
  277. if !generate_tags_pages && !generate_categories_pages {
  278. return;
  279. }
  280. // TODO: can we pass a reference?
  281. let (tags, categories) = Taxonomy::find_tags_and_categories(
  282. self.pages.values().cloned().collect::<Vec<_>>().as_slice()
  283. );
  284. if generate_tags_pages {
  285. self.tags = Some(tags);
  286. }
  287. if generate_categories_pages {
  288. self.categories = Some(categories);
  289. }
  290. }
  291. /// Inject live reload script tag if in live reload mode
  292. fn inject_livereload(&self, html: String) -> String {
  293. if self.live_reload {
  294. return html.replace(
  295. "</body>",
  296. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  297. );
  298. }
  299. html
  300. }
  301. /// Copy static file to public directory.
  302. pub fn copy_static_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
  303. let relative_path = path.as_ref().strip_prefix(&self.static_path).unwrap();
  304. let target_path = self.output_path.join(relative_path);
  305. if let Some(parent_directory) = target_path.parent() {
  306. create_dir_all(parent_directory)?;
  307. }
  308. copy(path.as_ref(), &target_path)?;
  309. Ok(())
  310. }
  311. /// Copy the content of the `static` folder into the `public` folder
  312. pub fn copy_static_directory(&self) -> Result<()> {
  313. for entry in WalkDir::new(&self.static_path).into_iter().filter_map(|e| e.ok()) {
  314. let relative_path = entry.path().strip_prefix(&self.static_path).unwrap();
  315. let target_path = self.output_path.join(relative_path);
  316. if entry.path().is_dir() {
  317. if !target_path.exists() {
  318. create_directory(&target_path)?;
  319. }
  320. } else {
  321. let entry_fullpath = self.base_path.join(entry.path());
  322. self.copy_static_file(entry_fullpath)?;
  323. }
  324. }
  325. Ok(())
  326. }
  327. /// Deletes the `public` directory if it exists
  328. pub fn clean(&self) -> Result<()> {
  329. if self.output_path.exists() {
  330. // Delete current `public` directory so we can start fresh
  331. remove_dir_all(&self.output_path).chain_err(|| "Couldn't delete `public` directory")?;
  332. }
  333. Ok(())
  334. }
  335. /// Renders a single content page
  336. pub fn render_page(&self, page: &Page) -> Result<()> {
  337. ensure_directory_exists(&self.output_path)?;
  338. // Copy the nesting of the content directory if we have sections for that page
  339. let mut current_path = self.output_path.to_path_buf();
  340. for component in page.path.split('/') {
  341. current_path.push(component);
  342. if !current_path.exists() {
  343. create_directory(&current_path)?;
  344. }
  345. }
  346. // Make sure the folder exists
  347. create_directory(&current_path)?;
  348. // Finally, create a index.html file there with the page rendered
  349. let output = page.render_html(&self.tera, &self.config)?;
  350. create_file(&current_path.join("index.html"), &self.inject_livereload(output))?;
  351. // Copy any asset we found previously into the same directory as the index.html
  352. for asset in &page.assets {
  353. let asset_path = asset.as_path();
  354. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  355. }
  356. Ok(())
  357. }
  358. /// Deletes the `public` directory and builds the site
  359. pub fn build(&self) -> Result<()> {
  360. self.clean()?;
  361. // Render aliases first to allow overwriting
  362. self.render_aliases()?;
  363. self.render_sections()?;
  364. self.render_orphan_pages()?;
  365. self.render_sitemap()?;
  366. if self.config.generate_rss.unwrap() {
  367. self.render_rss_feed()?;
  368. }
  369. self.render_robots()?;
  370. // `render_categories` and `render_tags` will check whether the config allows
  371. // them to render or not
  372. self.render_categories()?;
  373. self.render_tags()?;
  374. if self.config.compile_sass.unwrap() {
  375. self.compile_sass()?;
  376. }
  377. self.copy_static_directory()
  378. }
  379. pub fn compile_sass(&self) -> Result<()> {
  380. ensure_directory_exists(&self.output_path)?;
  381. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  382. let sass_glob = format!("{}/{}", base_path, "sass/**/*.scss");
  383. let files = glob(&sass_glob)
  384. .unwrap()
  385. .filter_map(|e| e.ok())
  386. .filter(|entry| !entry.as_path().file_name().unwrap().to_string_lossy().starts_with('_'))
  387. .collect::<Vec<_>>();
  388. for file in files {
  389. let name = file.as_path().file_stem().unwrap().to_string_lossy();
  390. let css = match compile_file(file.as_path(), Options::default()) {
  391. Ok(c) => c,
  392. Err(e) => bail!(e)
  393. };
  394. create_file(&self.output_path.join(format!("{}.css", name)), &css)?;
  395. }
  396. Ok(())
  397. }
  398. pub fn render_aliases(&self) -> Result<()> {
  399. for page in self.pages.values() {
  400. if let Some(ref aliases) = page.meta.aliases {
  401. for alias in aliases {
  402. let mut output_path = self.output_path.to_path_buf();
  403. for component in alias.split('/') {
  404. output_path.push(&component);
  405. if !output_path.exists() {
  406. create_directory(&output_path)?;
  407. }
  408. }
  409. create_file(&output_path.join("index.html"), &render_redirect_template(&page.permalink, &self.tera)?)?;
  410. }
  411. }
  412. }
  413. Ok(())
  414. }
  415. /// Renders robots.txt
  416. pub fn render_robots(&self) -> Result<()> {
  417. ensure_directory_exists(&self.output_path)?;
  418. create_file(
  419. &self.output_path.join("robots.txt"),
  420. &self.tera.render("robots.txt", &Context::new())?
  421. )
  422. }
  423. /// Renders all categories and the single category pages if there are some
  424. pub fn render_categories(&self) -> Result<()> {
  425. if let Some(ref categories) = self.categories {
  426. self.render_taxonomy(categories)?;
  427. }
  428. Ok(())
  429. }
  430. /// Renders all tags and the single tag pages if there are some
  431. pub fn render_tags(&self) -> Result<()> {
  432. if let Some(ref tags) = self.tags {
  433. self.render_taxonomy(tags)?;
  434. }
  435. Ok(())
  436. }
  437. fn render_taxonomy(&self, taxonomy: &Taxonomy) -> Result<()> {
  438. if taxonomy.items.is_empty() {
  439. return Ok(())
  440. }
  441. ensure_directory_exists(&self.output_path)?;
  442. let output_path = self.output_path.join(&taxonomy.get_list_name());
  443. let list_output = taxonomy.render_list(&self.tera, &self.config)?;
  444. create_directory(&output_path)?;
  445. create_file(&output_path.join("index.html"), &self.inject_livereload(list_output))?;
  446. taxonomy
  447. .items
  448. .par_iter()
  449. .map(|item| {
  450. let single_output = taxonomy.render_single_item(item, &self.tera, &self.config)?;
  451. create_directory(&output_path.join(&item.slug))?;
  452. create_file(
  453. &output_path.join(&item.slug).join("index.html"),
  454. &self.inject_livereload(single_output)
  455. )
  456. })
  457. .fold(|| Ok(()), Result::and)
  458. .reduce(|| Ok(()), Result::and)
  459. }
  460. /// What it says on the tin
  461. pub fn render_sitemap(&self) -> Result<()> {
  462. ensure_directory_exists(&self.output_path)?;
  463. let mut context = Context::new();
  464. context.add(
  465. "pages",
  466. &self.pages.values().map(|p| SitemapEntry::new(p.permalink.clone(), p.meta.date.clone())).collect::<Vec<_>>()
  467. );
  468. context.add(
  469. "sections",
  470. &self.sections.values().map(|s| SitemapEntry::new(s.permalink.clone(), None)).collect::<Vec<_>>()
  471. );
  472. let mut categories = vec![];
  473. if let Some(ref c) = self.categories {
  474. let name = c.get_list_name();
  475. categories.push(SitemapEntry::new(self.config.make_permalink(&name), None));
  476. for item in &c.items {
  477. categories.push(
  478. SitemapEntry::new(self.config.make_permalink(&format!("{}/{}", &name, item.slug)), None),
  479. );
  480. }
  481. }
  482. context.add("categories", &categories);
  483. let mut tags = vec![];
  484. if let Some(ref t) = self.tags {
  485. let name = t.get_list_name();
  486. tags.push(SitemapEntry::new(self.config.make_permalink(&name), None));
  487. for item in &t.items {
  488. tags.push(
  489. SitemapEntry::new(self.config.make_permalink(&format!("{}/{}", &name, item.slug)), None),
  490. );
  491. }
  492. }
  493. context.add("tags", &tags);
  494. let sitemap = self.tera.render("sitemap.xml", &context)?;
  495. create_file(&self.output_path.join("sitemap.xml"), &sitemap)?;
  496. Ok(())
  497. }
  498. pub fn render_rss_feed(&self) -> Result<()> {
  499. ensure_directory_exists(&self.output_path)?;
  500. let mut context = Context::new();
  501. let pages = self.pages.values()
  502. .filter(|p| p.meta.date.is_some())
  503. .cloned()
  504. .collect::<Vec<Page>>();
  505. // Don't generate a RSS feed if none of the pages has a date
  506. if pages.is_empty() {
  507. return Ok(());
  508. }
  509. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  510. context.add("last_build_date", &sorted_pages[0].meta.date);
  511. // limit to the last n elements)
  512. context.add("pages", &sorted_pages.iter().take(self.config.rss_limit.unwrap()).collect::<Vec<_>>());
  513. context.add("config", &self.config);
  514. let rss_feed_url = if self.config.base_url.ends_with('/') {
  515. format!("{}{}", self.config.base_url, "rss.xml")
  516. } else {
  517. format!("{}/{}", self.config.base_url, "rss.xml")
  518. };
  519. context.add("feed_url", &rss_feed_url);
  520. let sitemap = self.tera.render("rss.xml", &context)?;
  521. create_file(&self.output_path.join("rss.xml"), &sitemap)?;
  522. Ok(())
  523. }
  524. /// Renders a single section
  525. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  526. ensure_directory_exists(&self.output_path)?;
  527. let public = self.output_path.clone();
  528. let mut output_path = public.to_path_buf();
  529. for component in &section.file.components {
  530. output_path.push(component);
  531. if !output_path.exists() {
  532. create_directory(&output_path)?;
  533. }
  534. }
  535. if render_pages {
  536. section
  537. .pages
  538. .par_iter()
  539. .map(|p| self.render_page(p))
  540. .fold(|| Ok(()), Result::and)
  541. .reduce(|| Ok(()), Result::and)?;
  542. }
  543. if !section.meta.should_render() {
  544. return Ok(());
  545. }
  546. if let Some(ref redirect_to) = section.meta.redirect_to {
  547. let permalink = self.config.make_permalink(redirect_to);
  548. create_file(&output_path.join("index.html"), &render_redirect_template(&permalink, &self.tera)?)?;
  549. return Ok(());
  550. }
  551. if section.meta.is_paginated() {
  552. self.render_paginated(&output_path, section)?;
  553. } else {
  554. let output = section.render_html(&self.tera, &self.config)?;
  555. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  556. }
  557. Ok(())
  558. }
  559. pub fn render_index(&self) -> Result<()> {
  560. self.render_section(&self.sections[&self.base_path.join("content").join("_index.md")], false)
  561. }
  562. /// Renders all sections
  563. pub fn render_sections(&self) -> Result<()> {
  564. self.sections
  565. .values()
  566. .collect::<Vec<_>>()
  567. .into_par_iter()
  568. .map(|s| self.render_section(s, true))
  569. .fold(|| Ok(()), Result::and)
  570. .reduce(|| Ok(()), Result::and)
  571. }
  572. /// Renders all pages that do not belong to any sections
  573. pub fn render_orphan_pages(&self) -> Result<()> {
  574. ensure_directory_exists(&self.output_path)?;
  575. for page in self.get_all_orphan_pages() {
  576. self.render_page(page)?;
  577. }
  578. Ok(())
  579. }
  580. /// Renders a list of pages when the section/index is wanting pagination.
  581. pub fn render_paginated(&self, output_path: &Path, section: &Section) -> Result<()> {
  582. ensure_directory_exists(&self.output_path)?;
  583. let paginate_path = match section.meta.paginate_path {
  584. Some(ref s) => s.clone(),
  585. None => unreachable!()
  586. };
  587. let paginator = Paginator::new(&section.pages, section);
  588. let folder_path = output_path.join(&paginate_path);
  589. create_directory(&folder_path)?;
  590. paginator
  591. .pagers
  592. .par_iter()
  593. .enumerate()
  594. .map(|(i, pager)| {
  595. let page_path = folder_path.join(&format!("{}", i + 1));
  596. create_directory(&page_path)?;
  597. let output = paginator.render_pager(pager, &self.config, &self.tera)?;
  598. if i > 0 {
  599. create_file(&page_path.join("index.html"), &self.inject_livereload(output))?;
  600. } else {
  601. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  602. create_file(&page_path.join("index.html"), &render_redirect_template(&section.permalink, &self.tera)?)?;
  603. }
  604. Ok(())
  605. })
  606. .fold(|| Ok(()), Result::and)
  607. .reduce(|| Ok(()), Result::and)
  608. }
  609. }