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.

1238 lines
45KB

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