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.

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