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.

1113 lines
40KB

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