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.

444 lines
16KB

  1. extern crate site;
  2. #[macro_use]
  3. extern crate errors;
  4. extern crate front_matter;
  5. extern crate library;
  6. use std::path::{Component, Path};
  7. use errors::Result;
  8. use front_matter::{PageFrontMatter, SectionFrontMatter};
  9. use library::{Page, Section};
  10. use site::Site;
  11. #[derive(Debug, Clone, Copy, PartialEq)]
  12. pub enum PageChangesNeeded {
  13. /// Editing `taxonomies`
  14. Taxonomies,
  15. /// Editing `date`, `order` or `weight`
  16. Sort,
  17. /// Editing anything causes a re-render of the page
  18. Render,
  19. }
  20. #[derive(Debug, Clone, Copy, PartialEq)]
  21. pub enum SectionChangesNeeded {
  22. /// Editing `sort_by`
  23. Sort,
  24. /// Editing `title`, `description`, `extra`, `template` or setting `render` to true
  25. Render,
  26. /// Editing `paginate_by`, `paginate_path` or `insert_anchor_links`
  27. RenderWithPages,
  28. /// Setting `render` to false
  29. Delete,
  30. /// Changing `transparent`
  31. Transparent,
  32. }
  33. /// Evaluates all the params in the front matter that changed so we can do the smallest
  34. /// delta in the serve command
  35. /// Order matters as the actions will be done in insertion order
  36. fn find_section_front_matter_changes(
  37. current: &SectionFrontMatter,
  38. new: &SectionFrontMatter,
  39. ) -> Vec<SectionChangesNeeded> {
  40. let mut changes_needed = vec![];
  41. if current.sort_by != new.sort_by {
  42. changes_needed.push(SectionChangesNeeded::Sort);
  43. }
  44. if current.transparent != new.transparent {
  45. changes_needed.push(SectionChangesNeeded::Transparent);
  46. }
  47. // We want to hide the section
  48. // TODO: what to do on redirect_path change?
  49. if current.render && !new.render {
  50. changes_needed.push(SectionChangesNeeded::Delete);
  51. // Nothing else we can do
  52. return changes_needed;
  53. }
  54. if current.paginate_by != new.paginate_by
  55. || current.paginate_path != new.paginate_path
  56. || current.insert_anchor_links != new.insert_anchor_links
  57. {
  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(
  70. current: &PageFrontMatter,
  71. other: &PageFrontMatter,
  72. ) -> Vec<PageChangesNeeded> {
  73. let mut changes_needed = vec![];
  74. if current.taxonomies != other.taxonomies {
  75. changes_needed.push(PageChangesNeeded::Taxonomies);
  76. }
  77. if current.date != other.date || current.order != other.order || current.weight != other.weight
  78. {
  79. changes_needed.push(PageChangesNeeded::Sort);
  80. }
  81. changes_needed.push(PageChangesNeeded::Render);
  82. changes_needed
  83. }
  84. /// Handles a path deletion: could be a page, a section, a folder
  85. fn delete_element(site: &mut Site, path: &Path, is_section: bool) -> Result<()> {
  86. {
  87. let mut library = site.library.write().unwrap();
  88. // Ignore the event if this path was not known
  89. if !library.contains_section(&path.to_path_buf())
  90. && !library.contains_page(&path.to_path_buf())
  91. {
  92. return Ok(());
  93. }
  94. if is_section {
  95. if let Some(s) = library.remove_section(&path.to_path_buf()) {
  96. site.permalinks.remove(&s.file.relative);
  97. }
  98. } else if let Some(p) = library.remove_page(&path.to_path_buf()) {
  99. site.permalinks.remove(&p.file.relative);
  100. }
  101. }
  102. site.populate_sections();
  103. site.populate_taxonomies()?;
  104. // Ensure we have our fn updated so it doesn't contain the permalink(s)/section/page deleted
  105. site.register_early_global_fns();
  106. site.register_tera_global_fns();
  107. // Deletion is something that doesn't happen all the time so we
  108. // don't need to optimise it too much
  109. site.build()
  110. }
  111. /// Handles a `_index.md` (a section) being edited in some ways
  112. fn handle_section_editing(site: &mut Site, path: &Path) -> Result<()> {
  113. let section = Section::from_file(path, &site.config)?;
  114. let pathbuf = path.to_path_buf();
  115. match site.add_section(section, true)? {
  116. // Updating a section
  117. Some(prev) => {
  118. site.populate_sections();
  119. {
  120. let library = site.library.read().unwrap();
  121. if library.get_section(&pathbuf).unwrap().meta == prev.meta {
  122. // Front matter didn't change, only content did
  123. // so we render only the section page, not its pages
  124. return site.render_section(&library.get_section(&pathbuf).unwrap(), false);
  125. }
  126. }
  127. // Front matter changed
  128. let changes = find_section_front_matter_changes(
  129. &site.library.read().unwrap().get_section(&pathbuf).unwrap().meta,
  130. &prev.meta,
  131. );
  132. for change in changes {
  133. // Sort always comes first if present so the rendering will be fine
  134. match change {
  135. SectionChangesNeeded::Sort => {
  136. site.register_tera_global_fns();
  137. }
  138. SectionChangesNeeded::Render => {
  139. site.render_section(&site.library.read().unwrap().get_section(&pathbuf).unwrap(), false)?
  140. }
  141. SectionChangesNeeded::RenderWithPages => {
  142. site.render_section(&site.library.read().unwrap().get_section(&pathbuf).unwrap(), true)?
  143. }
  144. // not a common enough operation to make it worth optimizing
  145. SectionChangesNeeded::Delete | SectionChangesNeeded::Transparent => {
  146. site.build()?;
  147. }
  148. };
  149. }
  150. Ok(())
  151. }
  152. // New section, only render that one
  153. None => {
  154. site.populate_sections();
  155. site.register_tera_global_fns();
  156. site.render_section(&site.library.read().unwrap().get_section(&pathbuf).unwrap(), true)
  157. }
  158. }
  159. }
  160. macro_rules! render_parent_section {
  161. ($site: expr, $path: expr) => {
  162. if let Some(s) = $site.library.read().unwrap().find_parent_section($path) {
  163. $site.render_section(s, false)?;
  164. };
  165. };
  166. }
  167. /// Handles a page being edited in some ways
  168. fn handle_page_editing(site: &mut Site, path: &Path) -> Result<()> {
  169. let page = Page::from_file(path, &site.config)?;
  170. let pathbuf = path.to_path_buf();
  171. match site.add_page(page, true)? {
  172. // Updating a page
  173. Some(prev) => {
  174. site.populate_sections();
  175. site.populate_taxonomies()?;
  176. site.register_tera_global_fns();
  177. {
  178. let library = site.library.read().unwrap();
  179. // Front matter didn't change, only content did
  180. if library.get_page(&pathbuf).unwrap().meta == prev.meta {
  181. // Other than the page itself, the summary might be seen
  182. // on a paginated list for a blog for example
  183. if library.get_page(&pathbuf).unwrap().summary.is_some() {
  184. render_parent_section!(site, path);
  185. }
  186. return site.render_page(&library.get_page(&pathbuf).unwrap());
  187. }
  188. }
  189. // Front matter changed
  190. let changes = find_page_front_matter_changes(
  191. &site.library.read().unwrap().get_page(&pathbuf).unwrap().meta,
  192. &prev.meta,
  193. );
  194. for change in changes {
  195. site.register_tera_global_fns();
  196. // Sort always comes first if present so the rendering will be fine
  197. match change {
  198. PageChangesNeeded::Taxonomies => {
  199. site.populate_taxonomies()?;
  200. site.render_taxonomies()?;
  201. }
  202. PageChangesNeeded::Sort => {
  203. site.render_index()?;
  204. }
  205. PageChangesNeeded::Render => {
  206. render_parent_section!(site, path);
  207. site.render_page(&site.library.read().unwrap().get_page(&path.to_path_buf()).unwrap())?;
  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_early_global_fns();
  218. site.register_tera_global_fns();
  219. // No need to optimise that yet, we can revisit if it becomes an issue
  220. site.build()
  221. }
  222. }
  223. }
  224. /// What happens when we rename a file/folder in the content directory.
  225. /// Note that this is only called for folders when it isn't empty
  226. pub fn after_content_rename(site: &mut Site, old: &Path, new: &Path) -> Result<()> {
  227. let new_path = if new.is_dir() {
  228. if new.join("_index.md").exists() {
  229. // This is a section keep the dir folder to differentiate from renaming _index.md
  230. // which doesn't do the same thing
  231. new.to_path_buf()
  232. } else if new.join("index.md").exists() {
  233. new.join("index.md")
  234. } else {
  235. bail!("Got unexpected folder {:?} while handling renaming that was not expected", new);
  236. }
  237. } else {
  238. new.to_path_buf()
  239. };
  240. // A section folder has been renamed: just reload the whole site and rebuild it as we
  241. // do not really know what needs to be rendered
  242. if new_path.is_dir() {
  243. site.load()?;
  244. return site.build();
  245. }
  246. // We ignore renames on non-markdown files for now
  247. if let Some(ext) = new_path.extension() {
  248. if ext != "md" {
  249. return Ok(());
  250. }
  251. }
  252. // Renaming a file to _index.md, let the section editing do something and hope for the best
  253. if new_path.file_name().unwrap() == "_index.md" {
  254. // We aren't entirely sure where the original thing was so just try to delete whatever was
  255. // at the old path
  256. {
  257. let mut library = site.library.write().unwrap();
  258. library.remove_page(&old.to_path_buf());
  259. library.remove_section(&old.to_path_buf());
  260. }
  261. return handle_section_editing(site, &new_path);
  262. }
  263. // If it is a page, just delete what was there before and
  264. // fake it's a new page
  265. let old_path = if new_path.file_name().unwrap() == "index.md" {
  266. old.join("index.md")
  267. } else {
  268. old.to_path_buf()
  269. };
  270. site.library.write().unwrap().remove_page(&old_path);
  271. handle_page_editing(site, &new_path)
  272. }
  273. /// What happens when a section or a page is created/edited
  274. pub fn after_content_change(site: &mut Site, path: &Path) -> Result<()> {
  275. let is_section = path.file_name().unwrap() == "_index.md";
  276. let is_md = path.extension().unwrap() == "md";
  277. let index = path.parent().unwrap().join("index.md");
  278. let mut potential_indices = vec![path.parent().unwrap().join("index.md")];
  279. for language in &site.config.languages {
  280. potential_indices.push(path.parent().unwrap().join(format!("index.{}.md", language.code)));
  281. }
  282. let colocated_index = potential_indices.contains(&path.to_path_buf());
  283. // A few situations can happen:
  284. // 1. Change on .md files
  285. // a. Is there already an `index.md`? Return an error if it's something other than delete
  286. // b. Deleted? remove the element
  287. // c. Edited?
  288. // 1. filename is `_index.md`, this is a section
  289. // 1. it's a page otherwise
  290. // 2. Change on non .md files
  291. // a. Try to find a corresponding `_index.md`
  292. // 1. Nothing? Return Ok
  293. // 2. Something? Update the page
  294. if is_md {
  295. // only delete if it was able to be added in the first place
  296. if !index.exists() && !path.exists() {
  297. return delete_element(site, path, is_section);
  298. }
  299. // Added another .md in a assets directory
  300. if index.exists() && path.exists() && !colocated_index {
  301. bail!(
  302. "Change on {:?} detected but only files named `index.md` with an optional language code are allowed",
  303. path.display()
  304. );
  305. } else if index.exists() && !path.exists() {
  306. // deleted the wrong .md, do nothing
  307. return Ok(());
  308. }
  309. if is_section {
  310. handle_section_editing(site, path)
  311. } else {
  312. handle_page_editing(site, path)
  313. }
  314. } else if index.exists() {
  315. handle_page_editing(site, &index)
  316. } else {
  317. Ok(())
  318. }
  319. }
  320. /// What happens when a template is changed
  321. pub fn after_template_change(site: &mut Site, path: &Path) -> Result<()> {
  322. site.tera.full_reload()?;
  323. let filename = path.file_name().unwrap().to_str().unwrap();
  324. match filename {
  325. "sitemap.xml" => site.render_sitemap(),
  326. "rss.xml" => site.render_rss_feed(site.library.read().unwrap().pages_values(), None),
  327. "robots.txt" => site.render_robots(),
  328. "single.html" | "list.html" => site.render_taxonomies(),
  329. "page.html" => {
  330. site.render_sections()?;
  331. site.render_orphan_pages()
  332. }
  333. "section.html" => site.render_sections(),
  334. "404.html" => site.render_404(),
  335. // Either the index or some unknown template changed
  336. // We can't really know what this change affects so rebuild all
  337. // the things
  338. _ => {
  339. // If we are updating a shortcode, re-render the markdown of all pages/site
  340. // because we have no clue which one needs rebuilding
  341. // TODO: look if there the shortcode is used in the markdown instead of re-rendering
  342. // everything
  343. if path.components().any(|x| x == Component::Normal("shortcodes".as_ref())) {
  344. site.render_markdown()?;
  345. }
  346. site.populate_sections();
  347. site.populate_taxonomies()?;
  348. site.render_sections()?;
  349. site.render_orphan_pages()?;
  350. site.render_taxonomies()
  351. }
  352. }
  353. }
  354. #[cfg(test)]
  355. mod tests {
  356. use std::collections::HashMap;
  357. use super::{
  358. find_page_front_matter_changes, find_section_front_matter_changes, PageChangesNeeded,
  359. SectionChangesNeeded,
  360. };
  361. use front_matter::{PageFrontMatter, SectionFrontMatter, SortBy};
  362. #[test]
  363. fn can_find_taxonomy_changes_in_page_frontmatter() {
  364. let mut taxonomies = HashMap::new();
  365. taxonomies.insert("tags".to_string(), vec!["a tag".to_string()]);
  366. let new = PageFrontMatter { taxonomies, ..PageFrontMatter::default() };
  367. let changes = find_page_front_matter_changes(&PageFrontMatter::default(), &new);
  368. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Render]);
  369. }
  370. #[test]
  371. fn can_find_multiple_changes_in_page_frontmatter() {
  372. let mut taxonomies = HashMap::new();
  373. taxonomies.insert("categories".to_string(), vec!["a category".to_string()]);
  374. let current = PageFrontMatter { taxonomies, order: Some(1), ..PageFrontMatter::default() };
  375. let changes = find_page_front_matter_changes(&current, &PageFrontMatter::default());
  376. assert_eq!(
  377. changes,
  378. vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Sort, PageChangesNeeded::Render]
  379. );
  380. }
  381. #[test]
  382. fn can_find_sort_changes_in_section_frontmatter() {
  383. let new = SectionFrontMatter { sort_by: SortBy::Date, ..SectionFrontMatter::default() };
  384. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  385. assert_eq!(changes, vec![SectionChangesNeeded::Sort, SectionChangesNeeded::Render]);
  386. }
  387. #[test]
  388. fn can_find_render_changes_in_section_frontmatter() {
  389. let new = SectionFrontMatter { render: false, ..SectionFrontMatter::default() };
  390. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  391. assert_eq!(changes, vec![SectionChangesNeeded::Delete]);
  392. }
  393. #[test]
  394. fn can_find_paginate_by_changes_in_section_frontmatter() {
  395. let new = SectionFrontMatter { paginate_by: Some(10), ..SectionFrontMatter::default() };
  396. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  397. assert_eq!(changes, vec![SectionChangesNeeded::RenderWithPages]);
  398. }
  399. }