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.

472 lines
17KB

  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. // We might have delete the root _index.md so ensure we have at least the default one
  103. // before populating
  104. site.create_default_index_sections()?;
  105. site.populate_sections();
  106. site.populate_taxonomies()?;
  107. // Ensure we have our fn updated so it doesn't contain the permalink(s)/section/page deleted
  108. site.register_early_global_fns();
  109. site.register_tera_global_fns();
  110. // Deletion is something that doesn't happen all the time so we
  111. // don't need to optimise it too much
  112. site.build()
  113. }
  114. /// Handles a `_index.md` (a section) being edited in some ways
  115. fn handle_section_editing(site: &mut Site, path: &Path) -> Result<()> {
  116. let section = Section::from_file(path, &site.config, &site.base_path)?;
  117. let pathbuf = path.to_path_buf();
  118. match site.add_section(section, true)? {
  119. // Updating a section
  120. Some(prev) => {
  121. site.populate_sections();
  122. site.process_images()?;
  123. {
  124. let library = site.library.read().unwrap();
  125. if library.get_section(&pathbuf).unwrap().meta == prev.meta {
  126. // Front matter didn't change, only content did
  127. // so we render only the section page, not its pages
  128. return site.render_section(&library.get_section(&pathbuf).unwrap(), false);
  129. }
  130. }
  131. // Front matter changed
  132. let changes = find_section_front_matter_changes(
  133. &site.library.read().unwrap().get_section(&pathbuf).unwrap().meta,
  134. &prev.meta,
  135. );
  136. for change in changes {
  137. // Sort always comes first if present so the rendering will be fine
  138. match change {
  139. SectionChangesNeeded::Sort => {
  140. site.register_tera_global_fns();
  141. }
  142. SectionChangesNeeded::Render => site.render_section(
  143. &site.library.read().unwrap().get_section(&pathbuf).unwrap(),
  144. false,
  145. )?,
  146. SectionChangesNeeded::RenderWithPages => site.render_section(
  147. &site.library.read().unwrap().get_section(&pathbuf).unwrap(),
  148. true,
  149. )?,
  150. // not a common enough operation to make it worth optimizing
  151. SectionChangesNeeded::Delete | SectionChangesNeeded::Transparent => {
  152. site.build()?;
  153. }
  154. };
  155. }
  156. Ok(())
  157. }
  158. // New section, only render that one
  159. None => {
  160. site.populate_sections();
  161. site.process_images()?;
  162. site.register_tera_global_fns();
  163. site.render_section(&site.library.read().unwrap().get_section(&pathbuf).unwrap(), true)
  164. }
  165. }
  166. }
  167. macro_rules! render_parent_sections {
  168. ($site: expr, $path: expr) => {
  169. for s in $site.library.read().unwrap().find_parent_sections($path) {
  170. $site.render_section(s, false)?;
  171. }
  172. };
  173. }
  174. /// Handles a page being edited in some ways
  175. fn handle_page_editing(site: &mut Site, path: &Path) -> Result<()> {
  176. let page = Page::from_file(path, &site.config, &site.base_path)?;
  177. let pathbuf = path.to_path_buf();
  178. match site.add_page(page, true)? {
  179. // Updating a page
  180. Some(prev) => {
  181. site.populate_sections();
  182. site.populate_taxonomies()?;
  183. site.register_tera_global_fns();
  184. site.process_images()?;
  185. {
  186. let library = site.library.read().unwrap();
  187. // Front matter didn't change, only content did
  188. if library.get_page(&pathbuf).unwrap().meta == prev.meta {
  189. // Other than the page itself, the summary might be seen
  190. // on a paginated list for a blog for example
  191. if library.get_page(&pathbuf).unwrap().summary.is_some() {
  192. render_parent_sections!(site, path);
  193. }
  194. return site.render_page(&library.get_page(&pathbuf).unwrap());
  195. }
  196. }
  197. // Front matter changed
  198. let changes = find_page_front_matter_changes(
  199. &site.library.read().unwrap().get_page(&pathbuf).unwrap().meta,
  200. &prev.meta,
  201. );
  202. for change in changes {
  203. site.register_tera_global_fns();
  204. // Sort always comes first if present so the rendering will be fine
  205. match change {
  206. PageChangesNeeded::Taxonomies => {
  207. site.populate_taxonomies()?;
  208. site.render_taxonomies()?;
  209. }
  210. PageChangesNeeded::Sort => {
  211. site.render_index()?;
  212. }
  213. PageChangesNeeded::Render => {
  214. render_parent_sections!(site, path);
  215. site.render_page(
  216. &site.library.read().unwrap().get_page(&path.to_path_buf()).unwrap(),
  217. )?;
  218. }
  219. };
  220. }
  221. Ok(())
  222. }
  223. // It's a new page!
  224. None => {
  225. site.populate_sections();
  226. site.populate_taxonomies()?;
  227. site.register_early_global_fns();
  228. site.register_tera_global_fns();
  229. site.process_images()?;
  230. // No need to optimise that yet, we can revisit if it becomes an issue
  231. site.build()
  232. }
  233. }
  234. }
  235. /// What happens when we rename a file/folder in the content directory.
  236. /// Note that this is only called for folders when it isn't empty
  237. pub fn after_content_rename(site: &mut Site, old: &Path, new: &Path) -> Result<()> {
  238. let new_path = if new.is_dir() {
  239. if new.join("_index.md").exists() {
  240. // This is a section keep the dir folder to differentiate from renaming _index.md
  241. // which doesn't do the same thing
  242. new.to_path_buf()
  243. } else if new.join("index.md").exists() {
  244. new.join("index.md")
  245. } else {
  246. bail!("Got unexpected folder {:?} while handling renaming that was not expected", new);
  247. }
  248. } else {
  249. new.to_path_buf()
  250. };
  251. // A section folder has been renamed: just reload the whole site and rebuild it as we
  252. // do not really know what needs to be rendered
  253. if new_path.is_dir() {
  254. site.load()?;
  255. return site.build();
  256. }
  257. // We ignore renames on non-markdown files for now
  258. if let Some(ext) = new_path.extension() {
  259. if ext != "md" {
  260. return Ok(());
  261. }
  262. }
  263. // Renaming a file to _index.md, let the section editing do something and hope for the best
  264. if new_path.file_name().unwrap() == "_index.md" {
  265. // We aren't entirely sure where the original thing was so just try to delete whatever was
  266. // at the old path
  267. {
  268. let mut library = site.library.write().unwrap();
  269. library.remove_page(&old.to_path_buf());
  270. library.remove_section(&old.to_path_buf());
  271. }
  272. return handle_section_editing(site, &new_path);
  273. }
  274. // If it is a page, just delete what was there before and
  275. // fake it's a new page
  276. let old_path = if new_path.file_name().unwrap() == "index.md" {
  277. old.join("index.md")
  278. } else {
  279. old.to_path_buf()
  280. };
  281. site.library.write().unwrap().remove_page(&old_path);
  282. let ignored_content_globset = site.config.ignored_content_globset.clone();
  283. let is_ignored_file = match ignored_content_globset {
  284. Some(gs) => gs.is_match(new),
  285. None => false,
  286. };
  287. if !is_ignored_file {
  288. return handle_page_editing(site, &new_path);
  289. }
  290. Ok(())
  291. }
  292. /// What happens when a section or a page is created/edited
  293. pub fn after_content_change(site: &mut Site, path: &Path) -> Result<()> {
  294. let is_section = path.file_name().unwrap() == "_index.md";
  295. let is_md = path.extension().unwrap() == "md";
  296. let index = path.parent().unwrap().join("index.md");
  297. let mut potential_indices = vec![path.parent().unwrap().join("index.md")];
  298. for language in &site.config.languages {
  299. potential_indices.push(path.parent().unwrap().join(format!("index.{}.md", language.code)));
  300. }
  301. let colocated_index = potential_indices.contains(&path.to_path_buf());
  302. // A few situations can happen:
  303. // 1. Change on .md files
  304. // a. Is there already an `index.md`? Return an error if it's something other than delete
  305. // b. Deleted? remove the element
  306. // c. Edited?
  307. // 1. filename is `_index.md`, this is a section
  308. // 1. it's a page otherwise
  309. // 2. Change on non .md files
  310. // a. Try to find a corresponding `_index.md`
  311. // 1. Nothing? Return Ok
  312. // 2. Something? Update the page
  313. if is_md {
  314. // only delete if it was able to be added in the first place
  315. if !index.exists() && !path.exists() {
  316. return delete_element(site, path, is_section);
  317. }
  318. // Added another .md in a assets directory
  319. if index.exists() && path.exists() && !colocated_index {
  320. bail!(
  321. "Change on {:?} detected but only files named `index.md` with an optional language code are allowed",
  322. path.display()
  323. );
  324. } else if index.exists() && !path.exists() {
  325. // deleted the wrong .md, do nothing
  326. return Ok(());
  327. }
  328. if is_section {
  329. handle_section_editing(site, path)
  330. } else {
  331. handle_page_editing(site, path)
  332. }
  333. } else if index.exists() {
  334. handle_page_editing(site, &index)
  335. } else {
  336. Ok(())
  337. }
  338. }
  339. /// What happens when a template is changed
  340. pub fn after_template_change(site: &mut Site, path: &Path) -> Result<()> {
  341. site.tera.full_reload()?;
  342. let filename = path.file_name().unwrap().to_str().unwrap();
  343. match filename {
  344. "sitemap.xml" => site.render_sitemap(),
  345. "rss.xml" => site.render_rss_feed(site.library.read().unwrap().pages_values(), None),
  346. "split_sitemap_index.xml" => site.render_sitemap(),
  347. "robots.txt" => site.render_robots(),
  348. "single.html" | "list.html" => site.render_taxonomies(),
  349. "page.html" => {
  350. site.render_sections()?;
  351. site.render_orphan_pages()
  352. }
  353. "section.html" => site.render_sections(),
  354. "404.html" => site.render_404(),
  355. // Either the index or some unknown template changed
  356. // We can't really know what this change affects so rebuild all
  357. // the things
  358. _ => {
  359. // If we are updating a shortcode, re-render the markdown of all pages/site
  360. // because we have no clue which one needs rebuilding
  361. // Same for the anchor-link template
  362. // TODO: look if there the shortcode is used in the markdown instead of re-rendering
  363. // everything
  364. if filename == "anchor-link.html"
  365. || path.components().any(|x| x == Component::Normal("shortcodes".as_ref()))
  366. {
  367. println!("Rendering markdown");
  368. site.render_markdown()?;
  369. }
  370. site.populate_sections();
  371. site.populate_taxonomies()?;
  372. site.render_sections()?;
  373. site.process_images()?;
  374. site.render_orphan_pages()?;
  375. site.render_taxonomies()
  376. }
  377. }
  378. }
  379. #[cfg(test)]
  380. mod tests {
  381. use std::collections::HashMap;
  382. use super::{
  383. find_page_front_matter_changes, find_section_front_matter_changes, PageChangesNeeded,
  384. SectionChangesNeeded,
  385. };
  386. use front_matter::{PageFrontMatter, SectionFrontMatter, SortBy};
  387. #[test]
  388. fn can_find_taxonomy_changes_in_page_frontmatter() {
  389. let mut taxonomies = HashMap::new();
  390. taxonomies.insert("tags".to_string(), vec!["a tag".to_string()]);
  391. let new = PageFrontMatter { taxonomies, ..PageFrontMatter::default() };
  392. let changes = find_page_front_matter_changes(&PageFrontMatter::default(), &new);
  393. assert_eq!(changes, vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Render]);
  394. }
  395. #[test]
  396. fn can_find_multiple_changes_in_page_frontmatter() {
  397. let mut taxonomies = HashMap::new();
  398. taxonomies.insert("categories".to_string(), vec!["a category".to_string()]);
  399. let current = PageFrontMatter { taxonomies, order: Some(1), ..PageFrontMatter::default() };
  400. let changes = find_page_front_matter_changes(&current, &PageFrontMatter::default());
  401. assert_eq!(
  402. changes,
  403. vec![PageChangesNeeded::Taxonomies, PageChangesNeeded::Sort, PageChangesNeeded::Render]
  404. );
  405. }
  406. #[test]
  407. fn can_find_sort_changes_in_section_frontmatter() {
  408. let new = SectionFrontMatter { sort_by: SortBy::Date, ..SectionFrontMatter::default() };
  409. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  410. assert_eq!(changes, vec![SectionChangesNeeded::Sort, SectionChangesNeeded::Render]);
  411. }
  412. #[test]
  413. fn can_find_render_changes_in_section_frontmatter() {
  414. let new = SectionFrontMatter { render: false, ..SectionFrontMatter::default() };
  415. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  416. assert_eq!(changes, vec![SectionChangesNeeded::Delete]);
  417. }
  418. #[test]
  419. fn can_find_paginate_by_changes_in_section_frontmatter() {
  420. let new = SectionFrontMatter { paginate_by: Some(10), ..SectionFrontMatter::default() };
  421. let changes = find_section_front_matter_changes(&SectionFrontMatter::default(), &new);
  422. assert_eq!(changes, vec![SectionChangesNeeded::RenderWithPages]);
  423. }
  424. }