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.

620 lines
22KB

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