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.

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