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.

1177 lines
42KB

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