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.

1249 lines
45KB

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