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.

768 lines
27KB

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