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.

810 lines
29KB

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