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.

1022 lines
36KB

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