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.

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