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.

649 lines
23KB

  1. use std::collections::{HashMap};
  2. use std::iter::FromIterator;
  3. use std::fs::{remove_dir_all, copy, create_dir_all};
  4. use std::path::{Path, PathBuf};
  5. use glob::glob;
  6. use tera::{Tera, Context};
  7. use slug::slugify;
  8. use walkdir::WalkDir;
  9. use errors::{Result, ResultExt};
  10. use config::{Config, get_config};
  11. use utils::{create_file, create_directory};
  12. use content::{Page, Section, Paginator, SortBy, populate_previous_and_next_pages, sort_pages};
  13. use templates::{GUTENBERG_TERA, global_fns, render_redirect_template};
  14. #[derive(Debug, PartialEq)]
  15. enum RenderList {
  16. Tags,
  17. Categories,
  18. }
  19. /// A tag or category
  20. #[derive(Debug, Serialize, PartialEq)]
  21. struct ListItem {
  22. name: String,
  23. slug: String,
  24. count: usize,
  25. }
  26. impl ListItem {
  27. pub fn new(name: &str, count: usize) -> ListItem {
  28. ListItem {
  29. name: name.to_string(),
  30. slug: slugify(name),
  31. count: count,
  32. }
  33. }
  34. }
  35. #[derive(Debug)]
  36. pub struct Site {
  37. pub base_path: PathBuf,
  38. pub config: Config,
  39. pub pages: HashMap<PathBuf, Page>,
  40. pub sections: HashMap<PathBuf, Section>,
  41. pub tera: Tera,
  42. live_reload: bool,
  43. output_path: PathBuf,
  44. static_path: PathBuf,
  45. pub tags: HashMap<String, Vec<PathBuf>>,
  46. pub categories: HashMap<String, Vec<PathBuf>>,
  47. /// A map of all .md files (section and pages) and their permalink
  48. /// We need that if there are relative links in the content that need to be resolved
  49. pub permalinks: HashMap<String, String>,
  50. }
  51. impl Site {
  52. /// Parse a site at the given path. Defaults to the current dir
  53. /// Passing in a path is only used in tests
  54. pub fn new<P: AsRef<Path>>(path: P, config_file: &str) -> Result<Site> {
  55. let path = path.as_ref();
  56. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
  57. let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
  58. tera.extend(&GUTENBERG_TERA)?;
  59. let site = Site {
  60. base_path: path.to_path_buf(),
  61. config: get_config(path, config_file),
  62. pages: HashMap::new(),
  63. sections: HashMap::new(),
  64. tera: tera,
  65. live_reload: false,
  66. output_path: path.join("public"),
  67. static_path: path.join("static"),
  68. tags: HashMap::new(),
  69. categories: HashMap::new(),
  70. permalinks: HashMap::new(),
  71. };
  72. Ok(site)
  73. }
  74. /// What the function name says
  75. pub fn enable_live_reload(&mut self) {
  76. self.live_reload = true;
  77. }
  78. /// Gets the path of all ignored pages in the site
  79. /// Used for reporting them in the CLI
  80. pub fn get_ignored_pages(&self) -> Vec<PathBuf> {
  81. self.sections
  82. .values()
  83. .flat_map(|s| s.ignored_pages.iter().map(|p| p.file_path.clone()))
  84. .collect()
  85. }
  86. /// Get all the orphan (== without section) pages in the site
  87. pub fn get_all_orphan_pages(&self) -> Vec<&Page> {
  88. let mut pages_in_sections = vec![];
  89. let mut orphans = vec![];
  90. for s in self.sections.values() {
  91. pages_in_sections.extend(s.all_pages_path());
  92. }
  93. for page in self.pages.values() {
  94. if !pages_in_sections.contains(&page.file_path) {
  95. orphans.push(page);
  96. }
  97. }
  98. orphans
  99. }
  100. /// Finds the section that contains the page given if there is one
  101. pub fn find_parent_section(&self, page: &Page) -> Option<&Section> {
  102. for section in self.sections.values() {
  103. if section.is_child_page(page) {
  104. return Some(section)
  105. }
  106. }
  107. None
  108. }
  109. /// Used by tests to change the output path to a tmp dir
  110. #[doc(hidden)]
  111. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  112. self.output_path = path.as_ref().to_path_buf();
  113. }
  114. /// Reads all .md files in the `content` directory and create pages/sections
  115. /// out of them
  116. pub fn load(&mut self) -> Result<()> {
  117. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  118. let content_glob = format!("{}/{}", base_path, "content/**/*.md");
  119. for entry in glob(&content_glob).unwrap().filter_map(|e| e.ok()) {
  120. let path = entry.as_path();
  121. if path.file_name().unwrap() == "_index.md" {
  122. self.add_section(path, false)?;
  123. } else {
  124. self.add_page(path, false)?;
  125. }
  126. }
  127. // Insert a default index section so we don't need to create a _index.md to render
  128. // the index page
  129. let index_path = self.base_path.join("content").join("_index.md");
  130. if !self.sections.contains_key(&index_path) {
  131. let mut index_section = Section::default();
  132. index_section.permalink = self.config.make_permalink("");
  133. self.sections.insert(index_path, index_section);
  134. }
  135. // TODO: make that parallel
  136. for page in self.pages.values_mut() {
  137. page.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  138. }
  139. // TODO: make that parallel
  140. for section in self.sections.values_mut() {
  141. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  142. }
  143. self.populate_sections();
  144. self.populate_tags_and_categories();
  145. self.tera.register_global_function("get_page", global_fns::make_get_page(&self.pages));
  146. Ok(())
  147. }
  148. /// Add a page to the site
  149. /// The `render` parameter is used in the serve command, when rebuilding a page.
  150. /// If `true`, it will also render the markdown for that page
  151. /// Returns the previous page struct if there was one
  152. pub fn add_page(&mut self, path: &Path, render: bool) -> Result<Option<Page>> {
  153. let page = Page::from_file(&path, &self.config)?;
  154. self.permalinks.insert(page.relative_path.clone(), page.permalink.clone());
  155. let prev = self.pages.insert(page.file_path.clone(), page);
  156. if render {
  157. let mut page = self.pages.get_mut(path).unwrap();
  158. page.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  159. }
  160. Ok(prev)
  161. }
  162. /// Add a section to the site
  163. /// The `render` parameter is used in the serve command, when rebuilding a page.
  164. /// If `true`, it will also render the markdown for that page
  165. /// Returns the previous page struct if there was one
  166. pub fn add_section(&mut self, path: &Path, render: bool) -> Result<Option<Section>> {
  167. let section = Section::from_file(path, &self.config)?;
  168. self.permalinks.insert(section.relative_path.clone(), section.permalink.clone());
  169. let prev = self.sections.insert(section.file_path.clone(), section);
  170. if render {
  171. let mut section = self.sections.get_mut(path).unwrap();
  172. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  173. }
  174. Ok(prev)
  175. }
  176. /// Find out the direct subsections of each subsection if there are some
  177. /// as well as the pages for each section
  178. pub fn populate_sections(&mut self) {
  179. let mut grandparent_paths = HashMap::new();
  180. for section in self.sections.values_mut() {
  181. if let Some(grand_parent) = section.parent_path.parent() {
  182. grandparent_paths.entry(grand_parent.to_path_buf()).or_insert_with(|| vec![]).push(section.clone());
  183. }
  184. // Make sure the pages of a section are empty since we can call that many times on `serve`
  185. section.pages = vec![];
  186. section.ignored_pages = vec![];
  187. }
  188. for page in self.pages.values() {
  189. if self.sections.contains_key(&page.parent_path.join("_index.md")) {
  190. self.sections.get_mut(&page.parent_path.join("_index.md")).unwrap().pages.push(page.clone());
  191. }
  192. }
  193. for section in self.sections.values_mut() {
  194. match grandparent_paths.get(&section.parent_path) {
  195. Some(paths) => section.subsections.extend(paths.clone()),
  196. None => continue,
  197. };
  198. }
  199. self.sort_sections_pages(None);
  200. }
  201. /// Sorts the pages of the section at the given path
  202. /// By default will sort all sections but can be made to only sort a single one by providing a path
  203. pub fn sort_sections_pages(&mut self, only: Option<&Path>) {
  204. for (path, section) in &mut self.sections {
  205. if let Some(p) = only {
  206. if p != path {
  207. continue;
  208. }
  209. }
  210. let (sorted_pages, cannot_be_sorted_pages) = sort_pages(section.pages.clone(), section.meta.sort_by());
  211. section.pages = populate_previous_and_next_pages(&sorted_pages);
  212. section.ignored_pages = cannot_be_sorted_pages;
  213. }
  214. }
  215. /// Separated from `parse` for easier testing
  216. pub fn populate_tags_and_categories(&mut self) {
  217. for page in self.pages.values() {
  218. if let Some(ref category) = page.meta.category {
  219. self.categories
  220. .entry(category.to_string())
  221. .or_insert_with(|| vec![])
  222. .push(page.file_path.clone());
  223. }
  224. if let Some(ref tags) = page.meta.tags {
  225. for tag in tags {
  226. self.tags
  227. .entry(tag.to_string())
  228. .or_insert_with(|| vec![])
  229. .push(page.file_path.clone());
  230. }
  231. }
  232. }
  233. }
  234. /// Inject live reload script tag if in live reload mode
  235. fn inject_livereload(&self, html: String) -> String {
  236. if self.live_reload {
  237. return html.replace(
  238. "</body>",
  239. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  240. );
  241. }
  242. html
  243. }
  244. fn ensure_public_directory_exists(&self) -> Result<()> {
  245. let public = self.output_path.clone();
  246. if !public.exists() {
  247. create_directory(&public)?;
  248. }
  249. Ok(())
  250. }
  251. /// Copy static file to public directory.
  252. pub fn copy_static_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
  253. let relative_path = path.as_ref().strip_prefix(&self.static_path).unwrap();
  254. let target_path = self.output_path.join(relative_path);
  255. if let Some(parent_directory) = target_path.parent() {
  256. create_dir_all(parent_directory)?;
  257. }
  258. copy(path.as_ref(), &target_path)?;
  259. Ok(())
  260. }
  261. /// Copy the content of the `static` folder into the `public` folder
  262. pub fn copy_static_directory(&self) -> Result<()> {
  263. for entry in WalkDir::new(&self.static_path).into_iter().filter_map(|e| e.ok()) {
  264. let relative_path = entry.path().strip_prefix(&self.static_path).unwrap();
  265. let target_path = self.output_path.join(relative_path);
  266. if entry.path().is_dir() {
  267. if !target_path.exists() {
  268. create_directory(&target_path)?;
  269. }
  270. } else {
  271. let entry_fullpath = self.base_path.join(entry.path());
  272. self.copy_static_file(entry_fullpath)?;
  273. }
  274. }
  275. Ok(())
  276. }
  277. /// Deletes the `public` directory if it exists
  278. pub fn clean(&self) -> Result<()> {
  279. if self.output_path.exists() {
  280. // Delete current `public` directory so we can start fresh
  281. remove_dir_all(&self.output_path).chain_err(|| "Couldn't delete `public` directory")?;
  282. }
  283. Ok(())
  284. }
  285. /// Renders a single content page
  286. pub fn render_page(&self, page: &Page) -> Result<()> {
  287. self.ensure_public_directory_exists()?;
  288. // Copy the nesting of the content directory if we have sections for that page
  289. let mut current_path = self.output_path.to_path_buf();
  290. for component in page.path.split('/') {
  291. current_path.push(component);
  292. if !current_path.exists() {
  293. create_directory(&current_path)?;
  294. }
  295. }
  296. // Make sure the folder exists
  297. create_directory(&current_path)?;
  298. // Finally, create a index.html file there with the page rendered
  299. let output = page.render_html(&self.tera, &self.config)?;
  300. create_file(current_path.join("index.html"), &self.inject_livereload(output))?;
  301. // Copy any asset we found previously into the same directory as the index.html
  302. for asset in &page.assets {
  303. let asset_path = asset.as_path();
  304. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  305. }
  306. Ok(())
  307. }
  308. /// Builds the site to the `public` directory after deleting it
  309. pub fn build(&self) -> Result<()> {
  310. self.clean()?;
  311. self.render_sections()?;
  312. self.render_orphan_pages()?;
  313. self.render_sitemap()?;
  314. if self.config.generate_rss.unwrap() {
  315. self.render_rss_feed()?;
  316. }
  317. self.render_robots()?;
  318. // `render_categories` and `render_tags` will check whether the config allows
  319. // them to render or not
  320. self.render_categories()?;
  321. self.render_tags()?;
  322. self.copy_static_directory()
  323. }
  324. /// Renders robots.txt
  325. pub fn render_robots(&self) -> Result<()> {
  326. self.ensure_public_directory_exists()?;
  327. create_file(
  328. self.output_path.join("robots.txt"),
  329. &self.tera.render("robots.txt", &Context::new())?
  330. )
  331. }
  332. /// Renders all categories if the config allows it
  333. pub fn render_categories(&self) -> Result<()> {
  334. if self.config.generate_categories_pages.unwrap() {
  335. self.render_categories_and_tags(RenderList::Categories)
  336. } else {
  337. Ok(())
  338. }
  339. }
  340. /// Renders all tags if the config allows it
  341. pub fn render_tags(&self) -> Result<()> {
  342. if self.config.generate_tags_pages.unwrap() {
  343. self.render_categories_and_tags(RenderList::Tags)
  344. } else {
  345. Ok(())
  346. }
  347. }
  348. /// Render the /{categories, list} pages and each individual category/tag page
  349. /// They are the same thing fundamentally, a list of pages with something in common
  350. /// TODO: revisit this function, lots of things have changed since then
  351. fn render_categories_and_tags(&self, kind: RenderList) -> Result<()> {
  352. let items = match kind {
  353. RenderList::Categories => &self.categories,
  354. RenderList::Tags => &self.tags,
  355. };
  356. if items.is_empty() {
  357. return Ok(());
  358. }
  359. let (list_tpl_name, single_tpl_name, name, var_name) = if kind == RenderList::Categories {
  360. ("categories.html", "category.html", "categories", "category")
  361. } else {
  362. ("tags.html", "tag.html", "tags", "tag")
  363. };
  364. self.ensure_public_directory_exists()?;
  365. // Create the categories/tags directory first
  366. let public = self.output_path.clone();
  367. let mut output_path = public.to_path_buf();
  368. output_path.push(name);
  369. create_directory(&output_path)?;
  370. // Then render the index page for that kind.
  371. // We sort by number of page in that category/tag
  372. let mut sorted_items = vec![];
  373. for (item, count) in Vec::from_iter(items).into_iter().map(|(a, b)| (a, b.len())) {
  374. sorted_items.push(ListItem::new(item, count));
  375. }
  376. sorted_items.sort_by(|a, b| b.count.cmp(&a.count));
  377. let mut context = Context::new();
  378. context.add(name, &sorted_items);
  379. context.add("config", &self.config);
  380. context.add("current_url", &self.config.make_permalink(name));
  381. context.add("current_path", &format!("/{}", name));
  382. // And render it immediately
  383. let list_output = self.tera.render(list_tpl_name, &context)?;
  384. create_file(output_path.join("index.html"), &self.inject_livereload(list_output))?;
  385. // Now, each individual item
  386. for (item_name, pages_paths) in items.iter() {
  387. let pages: Vec<&Page> = self.pages
  388. .iter()
  389. .filter(|&(path, _)| pages_paths.contains(path))
  390. .map(|(_, page)| page)
  391. .collect();
  392. // TODO: how to sort categories and tag content?
  393. // Have a setting in config.toml or a _category.md and _tag.md
  394. // The latter is more in line with the rest of Gutenberg but order ordering
  395. // doesn't really work across sections.
  396. let mut context = Context::new();
  397. let slug = slugify(&item_name);
  398. context.add(var_name, &item_name);
  399. context.add(&format!("{}_slug", var_name), &slug);
  400. context.add("pages", &pages);
  401. context.add("config", &self.config);
  402. context.add("current_url", &self.config.make_permalink(&format!("{}/{}", name, slug)));
  403. context.add("current_path", &format!("/{}/{}", name, slug));
  404. let single_output = self.tera.render(single_tpl_name, &context)?;
  405. create_directory(&output_path.join(&slug))?;
  406. create_file(
  407. output_path.join(&slug).join("index.html"),
  408. &self.inject_livereload(single_output)
  409. )?;
  410. }
  411. Ok(())
  412. }
  413. /// What it says on the tin
  414. pub fn render_sitemap(&self) -> Result<()> {
  415. self.ensure_public_directory_exists()?;
  416. let mut context = Context::new();
  417. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  418. context.add("sections", &self.sections.values().collect::<Vec<&Section>>());
  419. let mut categories = vec![];
  420. if self.config.generate_categories_pages.unwrap() && !self.categories.is_empty() {
  421. categories.push(self.config.make_permalink("categories"));
  422. for category in self.categories.keys() {
  423. categories.push(
  424. self.config.make_permalink(&format!("categories/{}", slugify(category)))
  425. );
  426. }
  427. }
  428. context.add("categories", &categories);
  429. let mut tags = vec![];
  430. if self.config.generate_tags_pages.unwrap() && !self.tags.is_empty() {
  431. tags.push(self.config.make_permalink("tags"));
  432. for tag in self.tags.keys() {
  433. tags.push(
  434. self.config.make_permalink(&format!("tags/{}", slugify(tag)))
  435. );
  436. }
  437. }
  438. context.add("tags", &tags);
  439. let sitemap = self.tera.render("sitemap.xml", &context)?;
  440. create_file(self.output_path.join("sitemap.xml"), &sitemap)?;
  441. Ok(())
  442. }
  443. pub fn render_rss_feed(&self) -> Result<()> {
  444. self.ensure_public_directory_exists()?;
  445. let mut context = Context::new();
  446. let pages = self.pages.values()
  447. .filter(|p| p.meta.date.is_some())
  448. .take(15) // limit to the last 15 elements
  449. .cloned()
  450. .collect::<Vec<Page>>();
  451. // Don't generate a RSS feed if none of the pages has a date
  452. if pages.is_empty() {
  453. return Ok(());
  454. }
  455. context.add("last_build_date", &pages[0].meta.date);
  456. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  457. context.add("pages", &sorted_pages);
  458. context.add("config", &self.config);
  459. let rss_feed_url = if self.config.base_url.ends_with('/') {
  460. format!("{}{}", self.config.base_url, "rss.xml")
  461. } else {
  462. format!("{}/{}", self.config.base_url, "rss.xml")
  463. };
  464. context.add("feed_url", &rss_feed_url);
  465. let sitemap = self.tera.render("rss.xml", &context)?;
  466. create_file(self.output_path.join("rss.xml"), &sitemap)?;
  467. Ok(())
  468. }
  469. /// Create a hashmap of paths to section
  470. /// For example `content/posts/_index.md` key will be `posts`
  471. fn get_sections_map(&self) -> HashMap<String, Section> {
  472. self.sections
  473. .values()
  474. .map(|s| (s.components.join("/"), s.clone()))
  475. .collect()
  476. }
  477. /// Renders a single section
  478. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  479. self.ensure_public_directory_exists()?;
  480. let public = self.output_path.clone();
  481. let mut output_path = public.to_path_buf();
  482. for component in &section.components {
  483. output_path.push(component);
  484. if !output_path.exists() {
  485. create_directory(&output_path)?;
  486. }
  487. }
  488. if render_pages {
  489. for page in &section.pages {
  490. self.render_page(page)?;
  491. }
  492. }
  493. if !section.meta.should_render() {
  494. return Ok(());
  495. }
  496. if section.meta.is_paginated() {
  497. self.render_paginated(&output_path, section)?;
  498. } else {
  499. let output = section.render_html(
  500. if section.is_index() { self.get_sections_map() } else { HashMap::new() },
  501. &self.tera,
  502. &self.config,
  503. )?;
  504. create_file(output_path.join("index.html"), &self.inject_livereload(output))?;
  505. }
  506. Ok(())
  507. }
  508. pub fn render_index(&self) -> Result<()> {
  509. self.render_section(&self.sections[&self.base_path.join("content").join("_index.md")], false)
  510. }
  511. /// Renders all sections
  512. pub fn render_sections(&self) -> Result<()> {
  513. for section in self.sections.values() {
  514. self.render_section(section, true)?;
  515. }
  516. Ok(())
  517. }
  518. /// Renders all pages that do not belong to any sections
  519. pub fn render_orphan_pages(&self) -> Result<()> {
  520. self.ensure_public_directory_exists()?;
  521. for page in self.get_all_orphan_pages() {
  522. self.render_page(page)?;
  523. }
  524. Ok(())
  525. }
  526. /// Renders a list of pages when the section/index is wanting pagination.
  527. fn render_paginated(&self, output_path: &Path, section: &Section) -> Result<()> {
  528. self.ensure_public_directory_exists()?;
  529. let paginate_path = match section.meta.paginate_path {
  530. Some(ref s) => s.clone(),
  531. None => unreachable!()
  532. };
  533. let paginator = Paginator::new(&section.pages, section);
  534. for (i, pager) in paginator.pagers.iter().enumerate() {
  535. let folder_path = output_path.join(&paginate_path);
  536. let page_path = folder_path.join(&format!("{}", i + 1));
  537. create_directory(&folder_path)?;
  538. create_directory(&page_path)?;
  539. let output = paginator.render_pager(pager, self)?;
  540. if i > 0 {
  541. create_file(page_path.join("index.html"), &self.inject_livereload(output))?;
  542. } else {
  543. create_file(output_path.join("index.html"), &self.inject_livereload(output))?;
  544. create_file(page_path.join("index.html"), &render_redirect_template(&section.permalink, &self.tera)?)?;
  545. }
  546. }
  547. Ok(())
  548. }
  549. }