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.

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