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.

384 lines
14KB

  1. extern crate site;
  2. #[macro_use]
  3. extern crate errors;
  4. extern crate content;
  5. extern crate front_matter;
  6. use std::path::{Path, Component};
  7. use errors::Result;
  8. use site::Site;
  9. use content::{Page, Section};
  10. use front_matter::{PageFrontMatter, SectionFrontMatter};
  11. /// Finds the section that contains the page given if there is one
  12. pub fn find_parent_section<'a>(site: &'a Site, page: &Page) -> Option<&'a Section> {
  13. for section in site.sections.values() {
  14. if section.is_child_page(&page.file.path) {
  15. return Some(section)
  16. }
  17. }
  18. None
  19. }
  20. #[derive(Debug, Clone, Copy, PartialEq)]
  21. pub enum PageChangesNeeded {
  22. /// Editing `taxonomies`
  23. Taxonomies,
  24. /// Editing `date`, `order` or `weight`
  25. Sort,
  26. /// Editing anything causes a re-render of the page
  27. Render,
  28. }
  29. #[derive(Debug, Clone, Copy, PartialEq)]
  30. pub enum SectionChangesNeeded {
  31. /// Editing `sort_by`
  32. Sort,
  33. /// Editing `title`, `description`, `extra`, `template` or setting `render` to true
  34. Render,
  35. /// Editing `paginate_by`, `paginate_path` or `insert_anchor_links`
  36. RenderWithPages,
  37. /// Setting `render` to false
  38. Delete,
  39. }
  40. /// Evaluates all the params in the front matter that changed so we can do the smallest
  41. /// delta in the serve command
  42. /// Order matters as the actions will be done in insertion order
  43. fn find_section_front_matter_changes(current: &SectionFrontMatter, new: &SectionFrontMatter) -> Vec<SectionChangesNeeded> {
  44. let mut changes_needed = vec![];
  45. if current.sort_by != new.sort_by {
  46. changes_needed.push(SectionChangesNeeded::Sort);
  47. }
  48. // We want to hide the section
  49. // TODO: what to do on redirect_path change?
  50. if current.render && !new.render {
  51. changes_needed.push(SectionChangesNeeded::Delete);
  52. // Nothing else we can do
  53. return changes_needed;
  54. }
  55. if current.paginate_by != new.paginate_by
  56. || current.paginate_path != new.paginate_path
  57. || current.insert_anchor_links != new.insert_anchor_links {
  58. changes_needed.push(SectionChangesNeeded::RenderWithPages);
  59. // Nothing else we can do
  60. return changes_needed;
  61. }
  62. // Any new change will trigger a re-rendering of the section page only
  63. changes_needed.push(SectionChangesNeeded::Render);
  64. changes_needed
  65. }
  66. /// Evaluates all the params in the front matter that changed so we can do the smallest
  67. /// delta in the serve command
  68. /// Order matters as the actions will be done in insertion order
  69. fn find_page_front_matter_changes(current: &PageFrontMatter, other: &PageFrontMatter) -> Vec<PageChangesNeeded> {
  70. let mut changes_needed = vec![];
  71. if current.taxonomies != other.taxonomies {
  72. changes_needed.push(PageChangesNeeded::Taxonomies);
  73. }
  74. if current.date != other.date || current.order != other.order || current.weight != other.weight {
  75. changes_needed.push(PageChangesNeeded::Sort);
  76. }
  77. changes_needed.push(PageChangesNeeded::Render);
  78. changes_needed
  79. }
  80. /// Handles a path deletion: could be a page, a section, a folder
  81. fn delete_element(site: &mut Site, path: &Path, is_section: bool) -> Result<()> {
  82. // Ignore the event if this path was not known
  83. if !site.sections.contains_key(path) && !site.pages.contains_key(path) {
  84. return Ok(());
  85. }
  86. if is_section {
  87. if let Some(s) = site.pages.remove(path) {
  88. site.permalinks.remove(&s.file.relative);
  89. site.populate_sections();
  90. }
  91. } else {
  92. if let Some(p) = site.pages.remove(path) {
  93. site.permalinks.remove(&p.file.relative);
  94. if !p.meta.taxonomies.is_empty() {
  95. site.populate_taxonomies();
  96. }
  97. // if there is a parent section, we will need to re-render it
  98. // most likely
  99. if find_parent_section(site, &p).is_some() {
  100. site.populate_sections();
  101. }
  102. };
  103. }
  104. // Ensure we have our fn updated so it doesn't contain the permalink(s)/section/page deleted
  105. site.register_tera_global_fns();
  106. // Deletion is something that doesn't happen all the time so we
  107. // don't need to optimise it too much
  108. return site.build();
  109. }
  110. /// Handles a `_index.md` (a section) being edited in some ways
  111. fn handle_section_editing(site: &mut Site, path: &Path) -> Result<()> {
  112. let section = Section::from_file(path, &site.config)?;
  113. match site.add_section(section, true)? {
  114. // Updating a section
  115. Some(prev) => {
  116. if site.sections[path].meta == prev.meta {
  117. // Front matter didn't change, only content did
  118. // so we render only the section page, not its pages
  119. return site.render_section(&site.sections[path], false);
  120. }
  121. // Front matter changed
  122. for changes in find_section_front_matter_changes(&site.sections[path].meta, &prev.meta) {
  123. // Sort always comes first if present so the rendering will be fine
  124. match changes {
  125. SectionChangesNeeded::Sort => {
  126. site.sort_sections_pages(Some(path));
  127. site.register_tera_global_fns();
  128. },
  129. SectionChangesNeeded::Render => site.render_section(&site.sections[path], false)?,
  130. SectionChangesNeeded::RenderWithPages => site.render_section(&site.sections[path], true)?,
  131. // not a common enough operation to make it worth optimizing
  132. SectionChangesNeeded::Delete => {
  133. site.populate_sections();
  134. site.build()?;
  135. },
  136. };
  137. }
  138. return Ok(());
  139. },
  140. // New section, only render that one
  141. None => {
  142. site.populate_sections();
  143. site.register_tera_global_fns();
  144. return site.render_section(&site.sections[path], true);
  145. }
  146. };
  147. }
  148. macro_rules! render_parent_section {
  149. ($site: expr, $path: expr) => {
  150. match find_parent_section($site, &$site.pages[$path]) {
  151. Some(s) => {
  152. $site.render_section(s, false)?;
  153. },
  154. None => (),
  155. };
  156. }
  157. }
  158. /// Handles a page being edited in some ways
  159. fn handle_page_editing(site: &mut Site, path: &Path) -> Result<()> {
  160. let page = Page::from_file(path, &site.config)?;
  161. match site.add_page(page, true)? {
  162. // Updating a page
  163. Some(prev) => {
  164. // Front matter didn't change, only content did
  165. if site.pages[path].meta == prev.meta {
  166. // Other than the page itself, the summary might be seen
  167. // on a paginated list for a blog for example
  168. if site.pages[path].summary.is_some() {
  169. render_parent_section!(site, path);
  170. }
  171. // TODO: register_tera_global_fns is expensive as it involves lots of cloning
  172. // I can't think of a valid usecase where you would need the content
  173. // of a page through a global fn so it's commented out for now
  174. // site.register_tera_global_fns();
  175. return site.render_page(& site.pages[path]);
  176. }
  177. // Front matter changed
  178. let mut sections_populated = false;
  179. for changes in find_page_front_matter_changes(&site.pages[path].meta, &prev.meta) {
  180. // Sort always comes first if present so the rendering will be fine
  181. match changes {
  182. PageChangesNeeded::Taxonomies => {
  183. site.populate_taxonomies();
  184. site.register_tera_global_fns();
  185. site.render_taxonomies()?;
  186. },
  187. PageChangesNeeded::Sort => {
  188. let section_path = match find_parent_section(site, &site.pages[path]) {
  189. Some(s) => s.file.path.clone(),
  190. None => continue // Do nothing if it's an orphan page
  191. };
  192. if !sections_populated {
  193. site.populate_sections();
  194. sections_populated = true;
  195. }
  196. site.sort_sections_pages(Some(&section_path));
  197. site.register_tera_global_fns();
  198. site.render_index()?;
  199. },
  200. PageChangesNeeded::Render => {
  201. if !sections_populated {
  202. site.populate_sections();
  203. sections_populated = true;
  204. }
  205. site.register_tera_global_fns();
  206. render_parent_section!(site, path);
  207. site.render_page(&site.pages[path])?;
  208. },
  209. };
  210. }
  211. Ok(())
  212. },
  213. // It's a new page!
  214. None => {
  215. site.populate_sections();
  216. site.populate_taxonomies();
  217. site.register_tera_global_fns();
  218. // No need to optimise that yet, we can revisit if it becomes an issue
  219. site.build()
  220. }
  221. }
  222. }
  223. /// What happens when a section or a page is changed
  224. pub fn after_content_change(site: &mut Site, path: &Path) -> Result<()> {
  225. let is_section = path.file_name().unwrap() == "_index.md";
  226. let is_md = path.extension().unwrap() == "md";
  227. let index = path.parent().unwrap().join("index.md");
  228. // A few situations can happen:
  229. // 1. Change on .md files
  230. // a. Is there an `index.md`? Return an error if it's something other than delete
  231. // b. Deleted? remove the element
  232. // c. Edited?
  233. // 1. filename is `_index.md`, this is a section
  234. // 1. it's a page otherwise
  235. // 2. Change on non .md files
  236. // a. Try to find a corresponding `_index.md`
  237. // 1. Nothing? Return Ok
  238. // 2. Something? Update the page
  239. if is_md {
  240. // only delete if it was able to be added in the first place
  241. if !index.exists() && !path.exists() {
  242. delete_element(site, path, is_section)?;
  243. }
  244. // Added another .md in a assets directory
  245. if index.exists() && path.exists() && path != index {
  246. bail!(
  247. "Change on {:?} detected but there is already an `index.md` in the same folder",
  248. path.display()
  249. );
  250. } else if index.exists() && !path.exists() {
  251. // deleted the wrong .md, do nothing
  252. return Ok(());
  253. }
  254. if is_section {
  255. handle_section_editing(site, path)
  256. } else {
  257. handle_page_editing(site, path)
  258. }
  259. } else {
  260. if index.exists() {
  261. handle_page_editing(site, &index)
  262. } else {
  263. Ok(())
  264. }
  265. }
  266. }
  267. /// What happens when a template is changed
  268. pub fn after_template_change(site: &mut Site, path: &Path) -> Result<()> {
  269. site.tera.full_reload()?;
  270. let filename = path.file_name().unwrap().to_str().unwrap();
  271. match filename {
  272. "sitemap.xml" => site.render_sitemap(),
  273. "rss.xml" => site.render_rss_feed(None, None),
  274. "robots.txt" => site.render_robots(),
  275. "single.html" | "list.html" => site.render_taxonomies(),
  276. "page.html" => {
  277. site.render_sections()?;
  278. site.render_orphan_pages()
  279. },
  280. "section.html" => site.render_sections(),
  281. // Either the index or some unknown template changed
  282. // We can't really know what this change affects so rebuild all
  283. // the things
  284. _ => {
  285. // If we are updating a shortcode, re-render the markdown of all pages/site
  286. // because we have no clue which one needs rebuilding
  287. // TODO: look if there the shortcode is used in the markdown instead of re-rendering
  288. // everything
  289. if path.components().collect::<Vec<_>>().contains(&Component::Normal("shortcodes".as_ref())) {
  290. site.render_markdown()?;
  291. }
  292. site.populate_sections();
  293. site.render_sections()?;
  294. site.render_orphan_pages()?;
  295. site.render_taxonomies()
  296. },
  297. }
  298. }
  299. #[cfg(test)]
  300. mod tests {
  301. use std::collections::HashMap;
  302. use front_matter::{PageFrontMatter, SectionFrontMatter, SortBy};
  303. use super::{
  304. find_page_front_matter_changes, find_section_front_matter_changes,
  305. PageChangesNeeded, SectionChangesNeeded
  306. };
  307. #[test]
  308. fn can_find_taxonomy_changes_in_page_frontmatter() {
  309. let mut taxonomies = HashMap::new();
  310. taxonomies.insert("tags".to_string(), vec!["a tag".to_string()]);
  311. let new = PageFrontMatter { taxonomies, ..PageFrontMatter::default() };
  312. let changes = find_page_front_matter_changes(&PageFrontMatter::default(), &new);
  313. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Render]);
  314. }
  315. #[test]
  316. fn can_find_multiple_changes_in_page_frontmatter() {
  317. let mut taxonomies = HashMap::new();
  318. taxonomies.insert("categories".to_string(), vec!["a category".to_string()]);
  319. let current = PageFrontMatter { taxonomies, order: Some(1), ..PageFrontMatter::default() };
  320. let changes = find_page_front_matter_changes(&current, &PageFrontMatter::default());
  321. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Sort, PageChangesNeeded::Render]);
  322. }
  323. #[test]
  324. fn can_find_sort_changes_in_section_frontmatter() {
  325. let new = SectionFrontMatter { sort_by: SortBy::Date, ..SectionFrontMatter::default() };
  326. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  327. assert_eq!(changes, vec![SectionChangesNeeded::Sort, SectionChangesNeeded::Render]);
  328. }
  329. #[test]
  330. fn can_find_render_changes_in_section_frontmatter() {
  331. let new = SectionFrontMatter { render: false, ..SectionFrontMatter::default() };
  332. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  333. assert_eq!(changes, vec![SectionChangesNeeded::Delete]);
  334. }
  335. #[test]
  336. fn can_find_paginate_by_changes_in_section_frontmatter() {
  337. let new = SectionFrontMatter { paginate_by: Some(10), ..SectionFrontMatter::default() };
  338. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  339. assert_eq!(changes, vec![SectionChangesNeeded::RenderWithPages]);
  340. }
  341. }