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.

532 lines
18KB

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