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.

1025 lines
37KB

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