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.

866 lines
31KB

  1. extern crate tera;
  2. extern crate rayon;
  3. extern crate glob;
  4. extern crate serde;
  5. #[macro_use]
  6. extern crate serde_derive;
  7. extern crate sass_rs;
  8. #[macro_use]
  9. extern crate errors;
  10. extern crate config;
  11. extern crate utils;
  12. extern crate front_matter;
  13. extern crate templates;
  14. extern crate pagination;
  15. extern crate taxonomies;
  16. extern crate content;
  17. extern crate search;
  18. #[cfg(test)]
  19. extern crate tempdir;
  20. use std::collections::HashMap;
  21. use std::fs::{create_dir_all, remove_dir_all, copy};
  22. use std::mem;
  23. use std::path::{Path, PathBuf};
  24. use glob::glob;
  25. use tera::{Tera, Context};
  26. use sass_rs::{Options as SassOptions, OutputStyle, compile_file};
  27. use errors::{Result, ResultExt};
  28. use config::{Config, get_config};
  29. use utils::fs::{create_file, copy_directory, create_directory, ensure_directory_exists};
  30. use utils::templates::{render_template, rewrite_theme_paths};
  31. use content::{Page, Section, populate_previous_and_next_pages, sort_pages};
  32. use templates::{GUTENBERG_TERA, global_fns, render_redirect_template};
  33. use front_matter::{SortBy, InsertAnchor};
  34. use taxonomies::Taxonomy;
  35. use pagination::Paginator;
  36. use rayon::prelude::*;
  37. /// The sitemap only needs links and potentially date so we trim down
  38. /// all pages to only that
  39. #[derive(Debug, Serialize)]
  40. struct SitemapEntry {
  41. permalink: String,
  42. date: Option<String>,
  43. }
  44. impl SitemapEntry {
  45. pub fn new(permalink: String, date: Option<String>) -> SitemapEntry {
  46. SitemapEntry { permalink, date }
  47. }
  48. }
  49. #[derive(Debug)]
  50. pub struct Site {
  51. /// The base path of the gutenberg site
  52. pub base_path: PathBuf,
  53. /// The parsed config for the site
  54. pub config: Config,
  55. pub pages: HashMap<PathBuf, Page>,
  56. pub sections: HashMap<PathBuf, Section>,
  57. pub tera: Tera,
  58. live_reload: bool,
  59. pub output_path: PathBuf,
  60. pub static_path: PathBuf,
  61. pub tags: Option<Taxonomy>,
  62. pub categories: Option<Taxonomy>,
  63. /// A map of all .md files (section and pages) and their permalink
  64. /// We need that if there are relative links in the content that need to be resolved
  65. pub permalinks: HashMap<String, String>,
  66. }
  67. impl Site {
  68. /// Parse a site at the given path. Defaults to the current dir
  69. /// Passing in a path is only used in tests
  70. pub fn new<P: AsRef<Path>>(path: P, config_file: &str) -> Result<Site> {
  71. let path = path.as_ref();
  72. let mut config = get_config(path, config_file);
  73. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
  74. // Only parsing as we might be extending templates from themes and that would error
  75. // as we haven't loaded them yet
  76. let mut tera = Tera::parse(&tpl_glob).chain_err(|| "Error parsing templates")?;
  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 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. let theme_tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "themes/**/*.html");
  86. let mut tera_theme = Tera::parse(&theme_tpl_glob).chain_err(|| "Error parsing templates from themes")?;
  87. rewrite_theme_paths(&mut tera_theme, &theme);
  88. tera_theme.build_inheritance_chains()?;
  89. tera.extend(&tera_theme)?;
  90. }
  91. tera.extend(&GUTENBERG_TERA)?;
  92. // the `extend` above already does it but hey
  93. tera.build_inheritance_chains()?;
  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. /// The index section is ALWAYS at that path
  110. pub fn index_section_path(&self) -> PathBuf {
  111. self.base_path.join("content").join("_index.md")
  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. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  132. self.output_path = path.as_ref().to_path_buf();
  133. }
  134. /// Reads all .md files in the `content` directory and create pages/sections
  135. /// out of them
  136. pub fn load(&mut self) -> Result<()> {
  137. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  138. let content_glob = format!("{}/{}", base_path, "content/**/*.md");
  139. let (section_entries, page_entries): (Vec<_>, Vec<_>) = glob(&content_glob)
  140. .unwrap()
  141. .filter_map(|e| e.ok())
  142. .partition(|entry| entry.as_path().file_name().unwrap() == "_index.md");
  143. let sections = {
  144. let config = &self.config;
  145. section_entries
  146. .into_par_iter()
  147. .filter(|entry| entry.as_path().file_name().unwrap() == "_index.md")
  148. .map(|entry| {
  149. let path = entry.as_path();
  150. Section::from_file(path, config)
  151. })
  152. .collect::<Vec<_>>()
  153. };
  154. let pages = {
  155. let config = &self.config;
  156. page_entries
  157. .into_par_iter()
  158. .filter(|entry| entry.as_path().file_name().unwrap() != "_index.md")
  159. .map(|entry| {
  160. let path = entry.as_path();
  161. Page::from_file(path, config)
  162. })
  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.index_section_path();
  174. if let Some(ref index_section) = self.sections.get(&index_path) {
  175. if self.config.build_search_index && index_section.meta.in_search_index {
  176. bail!(
  177. "You have enabled search in the config but disabled it in the index section: \
  178. either turn off the search in the config or remote `in_search_index = true` from the \
  179. section front-matter."
  180. )
  181. }
  182. }
  183. // Not in else because of borrow checker
  184. if !self.sections.contains_key(&index_path) {
  185. let mut index_section = Section::default();
  186. index_section.permalink = self.config.make_permalink("");
  187. index_section.file.parent = self.base_path.join("content");
  188. index_section.file.relative = "_index.md".to_string();
  189. self.sections.insert(index_path, index_section);
  190. }
  191. let mut pages_insert_anchors = HashMap::new();
  192. for page in pages {
  193. let p = page?;
  194. pages_insert_anchors.insert(p.file.path.clone(), self.find_parent_section_insert_anchor(&p.file.parent.clone()));
  195. self.add_page(p, false)?;
  196. }
  197. self.render_markdown()?;
  198. self.populate_sections();
  199. self.populate_tags_and_categories();
  200. self.register_tera_global_fns();
  201. Ok(())
  202. }
  203. /// Render the markdown of all pages/sections
  204. /// Used in a build and in `serve` if a shortcode has changed
  205. pub fn render_markdown(&mut self) -> Result<()> {
  206. // Another silly thing needed to not borrow &self in parallel and
  207. // make the borrow checker happy
  208. let permalinks = &self.permalinks;
  209. let tera = &self.tera;
  210. let config = &self.config;
  211. // TODO: avoid the duplication with function above for that part
  212. // This is needed in the first place because of silly borrow checker
  213. let mut pages_insert_anchors = HashMap::new();
  214. for (_, p) in &self.pages {
  215. pages_insert_anchors.insert(p.file.path.clone(), self.find_parent_section_insert_anchor(&p.file.parent.clone()));
  216. }
  217. self.pages.par_iter_mut()
  218. .map(|(_, page)| {
  219. let insert_anchor = pages_insert_anchors[&page.file.path];
  220. page.render_markdown(permalinks, tera, config, insert_anchor)
  221. })
  222. .fold(|| Ok(()), Result::and)
  223. .reduce(|| Ok(()), Result::and)?;
  224. self.sections.par_iter_mut()
  225. .map(|(_, section)| section.render_markdown(permalinks, tera, config))
  226. .fold(|| Ok(()), Result::and)
  227. .reduce(|| Ok(()), Result::and)?;
  228. Ok(())
  229. }
  230. pub fn register_tera_global_fns(&mut self) {
  231. self.tera.register_global_function("trans", global_fns::make_trans(self.config.clone()));
  232. self.tera.register_global_function("get_page", global_fns::make_get_page(&self.pages));
  233. self.tera.register_global_function("get_section", global_fns::make_get_section(&self.sections));
  234. self.tera.register_global_function(
  235. "get_taxonomy_url",
  236. global_fns::make_get_taxonomy_url(self.tags.clone(), self.categories.clone())
  237. );
  238. self.tera.register_global_function(
  239. "get_url",
  240. global_fns::make_get_url(self.permalinks.clone(), self.config.clone())
  241. );
  242. }
  243. /// Add a page to the site
  244. /// The `render` parameter is used in the serve command, when rebuilding a page.
  245. /// If `true`, it will also render the markdown for that page
  246. /// Returns the previous page struct if there was one at the same path
  247. pub fn add_page(&mut self, page: Page, render: bool) -> Result<Option<Page>> {
  248. let path = page.file.path.clone();
  249. self.permalinks.insert(page.file.relative.clone(), page.permalink.clone());
  250. let prev = self.pages.insert(page.file.path.clone(), page);
  251. if render {
  252. let insert_anchor = self.find_parent_section_insert_anchor(&self.pages[&path].file.parent);
  253. let page = self.pages.get_mut(&path).unwrap();
  254. page.render_markdown(&self.permalinks, &self.tera, &self.config, insert_anchor)?;
  255. }
  256. Ok(prev)
  257. }
  258. /// Add a section to the site
  259. /// The `render` parameter is used in the serve command, when rebuilding a page.
  260. /// If `true`, it will also render the markdown for that page
  261. /// Returns the previous section struct if there was one at the same path
  262. pub fn add_section(&mut self, section: Section, render: bool) -> Result<Option<Section>> {
  263. let path = section.file.path.clone();
  264. self.permalinks.insert(section.file.relative.clone(), section.permalink.clone());
  265. let prev = self.sections.insert(section.file.path.clone(), section);
  266. if render {
  267. let section = self.sections.get_mut(&path).unwrap();
  268. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  269. }
  270. Ok(prev)
  271. }
  272. /// Finds the insert_anchor for the parent section of the directory at `path`.
  273. /// Defaults to `AnchorInsert::None` if no parent section found
  274. pub fn find_parent_section_insert_anchor(&self, parent_path: &PathBuf) -> InsertAnchor {
  275. match self.sections.get(&parent_path.join("_index.md")) {
  276. Some(s) => s.meta.insert_anchor_links,
  277. None => InsertAnchor::None
  278. }
  279. }
  280. /// Find out the direct subsections of each subsection if there are some
  281. /// as well as the pages for each section
  282. pub fn populate_sections(&mut self) {
  283. let mut grandparent_paths: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
  284. for section in self.sections.values_mut() {
  285. if let Some(ref grand_parent) = section.file.grand_parent {
  286. grandparent_paths
  287. .entry(grand_parent.to_path_buf())
  288. .or_insert_with(|| vec![])
  289. .push(section.file.path.clone());
  290. }
  291. // Make sure the pages of a section are empty since we can call that many times on `serve`
  292. section.pages = vec![];
  293. section.ignored_pages = vec![];
  294. }
  295. for page in self.pages.values() {
  296. let parent_section_path = page.file.parent.join("_index.md");
  297. if self.sections.contains_key(&parent_section_path) {
  298. // TODO: use references instead of cloning to avoid having to call populate_section on
  299. // content change
  300. self.sections.get_mut(&parent_section_path).unwrap().pages.push(page.clone());
  301. }
  302. }
  303. self.sort_sections_pages(None);
  304. // TODO: remove this clone
  305. let sections = self.sections.clone();
  306. for section in self.sections.values_mut() {
  307. if let Some(paths) = grandparent_paths.get(&section.file.parent) {
  308. section.subsections = paths
  309. .iter()
  310. .map(|p| sections[p].clone())
  311. .collect::<Vec<_>>();
  312. section.subsections
  313. .sort_by(|a, b| a.meta.weight.cmp(&b.meta.weight));
  314. }
  315. }
  316. }
  317. /// Sorts the pages of the section at the given path
  318. /// By default will sort all sections but can be made to only sort a single one by providing a path
  319. pub fn sort_sections_pages(&mut self, only: Option<&Path>) {
  320. for (path, section) in &mut self.sections {
  321. if let Some(p) = only {
  322. if p != path {
  323. continue;
  324. }
  325. }
  326. let pages = mem::replace(&mut section.pages, vec![]);
  327. let (sorted_pages, cannot_be_sorted_pages) = sort_pages(pages, section.meta.sort_by);
  328. section.pages = populate_previous_and_next_pages(&sorted_pages);
  329. section.ignored_pages = cannot_be_sorted_pages;
  330. }
  331. }
  332. /// Find all the tags and categories if it's asked in the config
  333. pub fn populate_tags_and_categories(&mut self) {
  334. let generate_tags_pages = self.config.generate_tags_pages;
  335. let generate_categories_pages = self.config.generate_categories_pages;
  336. if !generate_tags_pages && !generate_categories_pages {
  337. return;
  338. }
  339. // TODO: can we pass a reference?
  340. let (tags, categories) = Taxonomy::find_tags_and_categories(
  341. &self.config,
  342. self.pages
  343. .values()
  344. .filter(|p| !p.is_draft())
  345. .cloned()
  346. .collect::<Vec<_>>()
  347. .as_slice()
  348. );
  349. if generate_tags_pages {
  350. self.tags = Some(tags);
  351. }
  352. if generate_categories_pages {
  353. self.categories = Some(categories);
  354. }
  355. }
  356. /// Inject live reload script tag if in live reload mode
  357. fn inject_livereload(&self, html: String) -> String {
  358. if self.live_reload {
  359. return html.replace(
  360. "</body>",
  361. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  362. );
  363. }
  364. html
  365. }
  366. /// Copy the main `static` folder and the theme `static` folder if a theme is used
  367. pub fn copy_static_directories(&self) -> Result<()> {
  368. // The user files will overwrite the theme files
  369. if let Some(ref theme) = self.config.theme {
  370. copy_directory(
  371. &self.base_path.join("themes").join(theme).join("static"),
  372. &self.output_path
  373. )?;
  374. }
  375. // We're fine with missing static folders
  376. if self.static_path.exists() {
  377. copy_directory(&self.static_path, &self.output_path)?;
  378. }
  379. Ok(())
  380. }
  381. /// Deletes the `public` directory if it exists
  382. pub fn clean(&self) -> Result<()> {
  383. if self.output_path.exists() {
  384. // Delete current `public` directory so we can start fresh
  385. remove_dir_all(&self.output_path).chain_err(|| "Couldn't delete output directory")?;
  386. }
  387. Ok(())
  388. }
  389. /// Renders a single content page
  390. pub fn render_page(&self, page: &Page) -> Result<()> {
  391. ensure_directory_exists(&self.output_path)?;
  392. // Copy the nesting of the content directory if we have sections for that page
  393. let mut current_path = self.output_path.to_path_buf();
  394. for component in page.path.split('/') {
  395. current_path.push(component);
  396. if !current_path.exists() {
  397. create_directory(&current_path)?;
  398. }
  399. }
  400. // Make sure the folder exists
  401. create_directory(&current_path)?;
  402. // Finally, create a index.html file there with the page rendered
  403. let output = page.render_html(&self.tera, &self.config)?;
  404. create_file(&current_path.join("index.html"), &self.inject_livereload(output))?;
  405. // Copy any asset we found previously into the same directory as the index.html
  406. for asset in &page.assets {
  407. let asset_path = asset.as_path();
  408. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  409. }
  410. Ok(())
  411. }
  412. /// Deletes the `public` directory and builds the site
  413. pub fn build(&self) -> Result<()> {
  414. self.clean()?;
  415. // Render aliases first to allow overwriting
  416. self.render_aliases()?;
  417. self.render_sections()?;
  418. self.render_orphan_pages()?;
  419. self.render_sitemap()?;
  420. if self.config.generate_rss {
  421. self.render_rss_feed()?;
  422. }
  423. self.render_robots()?;
  424. // `render_categories` and `render_tags` will check whether the config allows
  425. // them to render or not
  426. self.render_categories()?;
  427. self.render_tags()?;
  428. if let Some(ref theme) = self.config.theme {
  429. let theme_path = self.base_path.join("themes").join(theme);
  430. if theme_path.join("sass").exists() {
  431. self.compile_sass(&theme_path)?;
  432. }
  433. }
  434. if self.config.compile_sass {
  435. self.compile_sass(&self.base_path)?;
  436. }
  437. self.copy_static_directories()?;
  438. if self.config.build_search_index {
  439. self.build_search_index()?;
  440. }
  441. Ok(())
  442. }
  443. pub fn build_search_index(&self) -> Result<()> {
  444. // index first
  445. create_file(
  446. &self.output_path.join(&format!("search_index.{}.js", self.config.default_language)),
  447. &format!(
  448. "window.searchIndex = {};",
  449. search::build_index(&self.sections, &self.config.default_language)?
  450. ),
  451. )?;
  452. // then elasticlunr.min.js
  453. create_file(
  454. &self.output_path.join("elasticlunr.min.js"),
  455. search::ELASTICLUNR_JS,
  456. )?;
  457. Ok(())
  458. }
  459. pub fn compile_sass(&self, base_path: &Path) -> Result<()> {
  460. ensure_directory_exists(&self.output_path)?;
  461. let sass_path = {
  462. let mut sass_path = PathBuf::from(base_path);
  463. sass_path.push("sass");
  464. sass_path
  465. };
  466. let mut options = SassOptions::default();
  467. options.output_style = OutputStyle::Compressed;
  468. let mut compiled_paths = self.compile_sass_glob(&sass_path, "scss", options.clone())?;
  469. options.indented_syntax = true;
  470. compiled_paths.extend(self.compile_sass_glob(&sass_path, "sass", options)?);
  471. compiled_paths.sort();
  472. for window in compiled_paths.windows(2) {
  473. if window[0].1 == window[1].1 {
  474. bail!(
  475. "SASS path conflict: \"{}\" and \"{}\" both compile to \"{}\"",
  476. window[0].0.display(),
  477. window[1].0.display(),
  478. window[0].1.display(),
  479. );
  480. }
  481. }
  482. Ok(())
  483. }
  484. fn compile_sass_glob(&self, sass_path: &Path, extension: &str, options: SassOptions) -> Result<Vec<(PathBuf, PathBuf)>> {
  485. let glob_string = format!("{}/**/*.{}", sass_path.display(), extension);
  486. let files = glob(&glob_string)
  487. .unwrap()
  488. .filter_map(|e| e.ok())
  489. .filter(|entry| !entry.as_path().file_name().unwrap().to_string_lossy().starts_with('_'))
  490. .collect::<Vec<_>>();
  491. let mut compiled_paths = Vec::new();
  492. for file in files {
  493. let css = compile_file(&file, options.clone())?;
  494. let path_inside_sass = file.strip_prefix(&sass_path).unwrap();
  495. let parent_inside_sass = path_inside_sass.parent();
  496. let css_output_path = self.output_path.join(path_inside_sass).with_extension("css");
  497. if parent_inside_sass.is_some() {
  498. create_dir_all(&css_output_path.parent().unwrap())?;
  499. }
  500. create_file(&css_output_path, &css)?;
  501. compiled_paths.push((path_inside_sass.to_owned(), css_output_path));
  502. }
  503. Ok(compiled_paths)
  504. }
  505. pub fn render_aliases(&self) -> Result<()> {
  506. for page in self.pages.values() {
  507. if let Some(ref aliases) = page.meta.aliases {
  508. for alias in aliases {
  509. let mut output_path = self.output_path.to_path_buf();
  510. for component in alias.split('/') {
  511. output_path.push(&component);
  512. if !output_path.exists() {
  513. create_directory(&output_path)?;
  514. }
  515. }
  516. create_file(&output_path.join("index.html"), &render_redirect_template(&page.permalink, &self.tera)?)?;
  517. }
  518. }
  519. }
  520. Ok(())
  521. }
  522. /// Renders robots.txt
  523. pub fn render_robots(&self) -> Result<()> {
  524. ensure_directory_exists(&self.output_path)?;
  525. create_file(
  526. &self.output_path.join("robots.txt"),
  527. &render_template("robots.txt", &self.tera, &Context::new(), self.config.theme.clone())?
  528. )
  529. }
  530. /// Renders all categories and the single category pages if there are some
  531. pub fn render_categories(&self) -> Result<()> {
  532. if let Some(ref categories) = self.categories {
  533. self.render_taxonomy(categories)?;
  534. }
  535. Ok(())
  536. }
  537. /// Renders all tags and the single tag pages if there are some
  538. pub fn render_tags(&self) -> Result<()> {
  539. if let Some(ref tags) = self.tags {
  540. self.render_taxonomy(tags)?;
  541. }
  542. Ok(())
  543. }
  544. fn render_taxonomy(&self, taxonomy: &Taxonomy) -> Result<()> {
  545. if taxonomy.items.is_empty() {
  546. return Ok(())
  547. }
  548. ensure_directory_exists(&self.output_path)?;
  549. let output_path = self.output_path.join(&taxonomy.get_list_name());
  550. let list_output = taxonomy.render_list(&self.tera, &self.config)?;
  551. create_directory(&output_path)?;
  552. create_file(&output_path.join("index.html"), &self.inject_livereload(list_output))?;
  553. taxonomy
  554. .items
  555. .par_iter()
  556. .map(|item| {
  557. let single_output = taxonomy.render_single_item(item, &self.tera, &self.config)?;
  558. create_directory(&output_path.join(&item.slug))?;
  559. create_file(
  560. &output_path.join(&item.slug).join("index.html"),
  561. &self.inject_livereload(single_output)
  562. )
  563. })
  564. .fold(|| Ok(()), Result::and)
  565. .reduce(|| Ok(()), Result::and)
  566. }
  567. /// What it says on the tin
  568. pub fn render_sitemap(&self) -> Result<()> {
  569. ensure_directory_exists(&self.output_path)?;
  570. let mut context = Context::new();
  571. let mut pages = self.pages
  572. .values()
  573. .filter(|p| !p.is_draft())
  574. .map(|p| {
  575. let date = match p.meta.date {
  576. Some(ref d) => Some(d.to_string()),
  577. None => None,
  578. };
  579. SitemapEntry::new(p.permalink.clone(), date)
  580. })
  581. .collect::<Vec<_>>();
  582. pages.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  583. context.add("pages", &pages);
  584. let mut sections = self.sections
  585. .values()
  586. .map(|s| SitemapEntry::new(s.permalink.clone(), None))
  587. .collect::<Vec<_>>();
  588. sections.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  589. context.add("sections", &sections);
  590. let mut categories = vec![];
  591. if let Some(ref c) = self.categories {
  592. let name = c.get_list_name();
  593. categories.push(SitemapEntry::new(self.config.make_permalink(&name), None));
  594. for item in &c.items {
  595. categories.push(
  596. SitemapEntry::new(self.config.make_permalink(&format!("{}/{}", &name, item.slug)), None),
  597. );
  598. }
  599. }
  600. categories.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  601. context.add("categories", &categories);
  602. let mut tags = vec![];
  603. if let Some(ref t) = self.tags {
  604. let name = t.get_list_name();
  605. tags.push(SitemapEntry::new(self.config.make_permalink(&name), None));
  606. for item in &t.items {
  607. tags.push(
  608. SitemapEntry::new(self.config.make_permalink(&format!("{}/{}", &name, item.slug)), None),
  609. );
  610. }
  611. }
  612. tags.sort_by(|a, b| a.permalink.cmp(&b.permalink));
  613. context.add("tags", &tags);
  614. context.add("config", &self.config);
  615. let sitemap = &render_template("sitemap.xml", &self.tera, &context, self.config.theme.clone())?;
  616. create_file(&self.output_path.join("sitemap.xml"), sitemap)?;
  617. Ok(())
  618. }
  619. pub fn render_rss_feed(&self) -> Result<()> {
  620. ensure_directory_exists(&self.output_path)?;
  621. let mut context = Context::new();
  622. let pages = self.pages.values()
  623. .filter(|p| p.meta.date.is_some() && !p.is_draft())
  624. .cloned()
  625. .collect::<Vec<Page>>();
  626. // Don't generate a RSS feed if none of the pages has a date
  627. if pages.is_empty() {
  628. return Ok(());
  629. }
  630. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  631. context.add("last_build_date", &sorted_pages[0].meta.date.clone().map(|d| d.to_string()));
  632. // limit to the last n elements)
  633. context.add("pages", &sorted_pages.iter().take(self.config.rss_limit).collect::<Vec<_>>());
  634. context.add("config", &self.config);
  635. let rss_feed_url = if self.config.base_url.ends_with('/') {
  636. format!("{}{}", self.config.base_url, "rss.xml")
  637. } else {
  638. format!("{}/{}", self.config.base_url, "rss.xml")
  639. };
  640. context.add("feed_url", &rss_feed_url);
  641. let feed = &render_template("rss.xml", &self.tera, &context, self.config.theme.clone())?;
  642. create_file(&self.output_path.join("rss.xml"), feed)?;
  643. Ok(())
  644. }
  645. /// Renders a single section
  646. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  647. ensure_directory_exists(&self.output_path)?;
  648. let public = self.output_path.clone();
  649. let mut output_path = public.to_path_buf();
  650. for component in &section.file.components {
  651. output_path.push(component);
  652. if !output_path.exists() {
  653. create_directory(&output_path)?;
  654. }
  655. }
  656. if render_pages {
  657. section
  658. .pages
  659. .par_iter()
  660. .map(|p| self.render_page(p))
  661. .fold(|| Ok(()), Result::and)
  662. .reduce(|| Ok(()), Result::and)?;
  663. }
  664. if !section.meta.render {
  665. return Ok(());
  666. }
  667. if let Some(ref redirect_to) = section.meta.redirect_to {
  668. let permalink = self.config.make_permalink(redirect_to);
  669. create_file(&output_path.join("index.html"), &render_redirect_template(&permalink, &self.tera)?)?;
  670. return Ok(());
  671. }
  672. if section.meta.is_paginated() {
  673. self.render_paginated(&output_path, section)?;
  674. } else {
  675. let output = section.render_html(&self.tera, &self.config)?;
  676. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  677. }
  678. Ok(())
  679. }
  680. /// Used only on reload
  681. pub fn render_index(&self) -> Result<()> {
  682. self.render_section(
  683. &self.sections[&self.base_path.join("content").join("_index.md")],
  684. false
  685. )
  686. }
  687. /// Renders all sections
  688. pub fn render_sections(&self) -> Result<()> {
  689. self.sections
  690. .values()
  691. .collect::<Vec<_>>()
  692. .into_par_iter()
  693. .map(|s| self.render_section(s, true))
  694. .fold(|| Ok(()), Result::and)
  695. .reduce(|| Ok(()), Result::and)
  696. }
  697. /// Renders all pages that do not belong to any sections
  698. pub fn render_orphan_pages(&self) -> Result<()> {
  699. ensure_directory_exists(&self.output_path)?;
  700. for page in self.get_all_orphan_pages() {
  701. self.render_page(page)?;
  702. }
  703. Ok(())
  704. }
  705. /// Renders a list of pages when the section/index is wanting pagination.
  706. pub fn render_paginated(&self, output_path: &Path, section: &Section) -> Result<()> {
  707. ensure_directory_exists(&self.output_path)?;
  708. let paginator = Paginator::new(&section.pages, section);
  709. let folder_path = output_path.join(&section.meta.paginate_path);
  710. create_directory(&folder_path)?;
  711. paginator
  712. .pagers
  713. .par_iter()
  714. .enumerate()
  715. .map(|(i, pager)| {
  716. let page_path = folder_path.join(&format!("{}", i + 1));
  717. create_directory(&page_path)?;
  718. let output = paginator.render_pager(pager, &self.config, &self.tera)?;
  719. if i > 0 {
  720. create_file(&page_path.join("index.html"), &self.inject_livereload(output))?;
  721. } else {
  722. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  723. create_file(&page_path.join("index.html"), &render_redirect_template(&section.permalink, &self.tera)?)?;
  724. }
  725. Ok(())
  726. })
  727. .fold(|| Ok(()), Result::and)
  728. .reduce(|| Ok(()), Result::and)
  729. }
  730. }