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.

545 lines
19KB

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