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.

705 lines
25KB

  1. use std::collections::HashMap;
  2. use std::fs::{remove_dir_all, copy, create_dir_all};
  3. use std::path::{Path, PathBuf};
  4. use glob::glob;
  5. use tera::{Tera, Context};
  6. use walkdir::WalkDir;
  7. use errors::{Result, ResultExt};
  8. use config::{Config, get_config};
  9. use fs::{create_file, create_directory, ensure_directory_exists};
  10. use content::{Page, Section, Paginator, SortBy, Taxonomy, populate_previous_and_next_pages, sort_pages};
  11. use templates::{GUTENBERG_TERA, global_fns, render_redirect_template};
  12. use front_matter::InsertAnchor;
  13. use rayon::prelude::*;
  14. #[derive(Debug)]
  15. pub struct Site {
  16. /// The base path of the gutenberg site
  17. pub base_path: PathBuf,
  18. /// The parsed config for the site
  19. pub config: Config,
  20. pub pages: HashMap<PathBuf, Page>,
  21. pub sections: HashMap<PathBuf, Section>,
  22. pub tera: Tera,
  23. live_reload: bool,
  24. output_path: PathBuf,
  25. static_path: PathBuf,
  26. pub tags: Option<Taxonomy>,
  27. pub categories: Option<Taxonomy>,
  28. /// A map of all .md files (section and pages) and their permalink
  29. /// We need that if there are relative links in the content that need to be resolved
  30. pub permalinks: HashMap<String, String>,
  31. }
  32. impl Site {
  33. /// Parse a site at the given path. Defaults to the current dir
  34. /// Passing in a path is only used in tests
  35. pub fn new<P: AsRef<Path>>(path: P, config_file: &str) -> Result<Site> {
  36. let path = path.as_ref();
  37. let tpl_glob = format!("{}/{}", path.to_string_lossy().replace("\\", "/"), "templates/**/*.*ml");
  38. let mut tera = Tera::new(&tpl_glob).chain_err(|| "Error parsing templates")?;
  39. tera.extend(&GUTENBERG_TERA)?;
  40. let site = Site {
  41. base_path: path.to_path_buf(),
  42. config: get_config(path, config_file),
  43. pages: HashMap::new(),
  44. sections: HashMap::new(),
  45. tera: tera,
  46. live_reload: false,
  47. output_path: path.join("public"),
  48. static_path: path.join("static"),
  49. tags: None,
  50. categories: None,
  51. permalinks: HashMap::new(),
  52. };
  53. Ok(site)
  54. }
  55. /// What the function name says
  56. pub fn enable_live_reload(&mut self) {
  57. self.live_reload = true;
  58. }
  59. /// Get all the orphan (== without section) pages in the site
  60. pub fn get_all_orphan_pages(&self) -> Vec<&Page> {
  61. let mut pages_in_sections = vec![];
  62. let mut orphans = vec![];
  63. for s in self.sections.values() {
  64. pages_in_sections.extend(s.all_pages_path());
  65. }
  66. for page in self.pages.values() {
  67. if !pages_in_sections.contains(&page.file.path) {
  68. orphans.push(page);
  69. }
  70. }
  71. orphans
  72. }
  73. /// Used by tests to change the output path to a tmp dir
  74. #[doc(hidden)]
  75. pub fn set_output_path<P: AsRef<Path>>(&mut self, path: P) {
  76. self.output_path = path.as_ref().to_path_buf();
  77. }
  78. /// Reads all .md files in the `content` directory and create pages/sections
  79. /// out of them
  80. pub fn load(&mut self) -> Result<()> {
  81. let base_path = self.base_path.to_string_lossy().replace("\\", "/");
  82. let content_glob = format!("{}/{}", base_path, "content/**/*.md");
  83. let (section_entries, page_entries): (Vec<_>, Vec<_>) = glob(&content_glob)
  84. .unwrap()
  85. .filter_map(|e| e.ok())
  86. .partition(|ref entry| entry.as_path().file_name().unwrap() == "_index.md");
  87. let sections = {
  88. let config = &self.config;
  89. section_entries
  90. .into_par_iter()
  91. .filter(|entry| entry.as_path().file_name().unwrap() == "_index.md")
  92. .map(|entry| {
  93. let path = entry.as_path();
  94. Section::from_file(path, &config)
  95. }).collect::<Vec<_>>()
  96. };
  97. let pages = {
  98. let config = &self.config;
  99. page_entries
  100. .into_par_iter()
  101. .filter(|entry| entry.as_path().file_name().unwrap() != "_index.md")
  102. .map(|entry| {
  103. let path = entry.as_path();
  104. Page::from_file(path, &config)
  105. }).collect::<Vec<_>>()
  106. };
  107. // Kinda duplicated code for add_section/add_page but necessary to do it that
  108. // way because of the borrow checker
  109. for section in sections {
  110. let s = section?;
  111. self.add_section(s, false)?;
  112. }
  113. // Insert a default index section if necessary so we don't need to create
  114. // a _index.md to render the index page
  115. let index_path = self.base_path.join("content").join("_index.md");
  116. if !self.sections.contains_key(&index_path) {
  117. let mut index_section = Section::default();
  118. index_section.permalink = self.config.make_permalink("");
  119. // TODO: need to insert into permalinks too
  120. self.sections.insert(index_path, index_section);
  121. }
  122. let mut pages_insert_anchors = HashMap::new();
  123. for page in pages {
  124. let p = page?;
  125. pages_insert_anchors.insert(p.file.path.clone(), self.find_parent_section_insert_anchor(&p.file.parent.clone()));
  126. self.add_page(p, false)?;
  127. }
  128. {
  129. // Another silly thing needed to not borrow &self in parallel and
  130. // make the borrow checker happy
  131. let permalinks = &self.permalinks;
  132. let tera = &self.tera;
  133. let config = &self.config;
  134. self.pages.par_iter_mut()
  135. .map(|(_, page)| page)
  136. .map(|page| {
  137. let insert_anchor = pages_insert_anchors[&page.file.path];
  138. page.render_markdown(&permalinks, &tera, &config, insert_anchor)
  139. })
  140. .fold(|| Ok(()), Result::and)
  141. .reduce(|| Ok(()), Result::and)?;
  142. self.sections.par_iter_mut()
  143. .map(|(_, section)| section)
  144. .map(|section| section.render_markdown(permalinks, tera, config))
  145. .fold(|| Ok(()), Result::and)
  146. .reduce(|| Ok(()), Result::and)?;
  147. }
  148. self.populate_sections();
  149. self.populate_tags_and_categories();
  150. self.tera.register_global_function("get_page", global_fns::make_get_page(&self.pages));
  151. self.tera.register_global_function("get_section", global_fns::make_get_section(&self.sections));
  152. self.register_get_url_fn();
  153. Ok(())
  154. }
  155. /// Separate fn as it can be called in the serve command
  156. pub fn register_get_url_fn(&mut self) {
  157. self.tera.register_global_function("get_url", global_fns::make_get_url(self.permalinks.clone()));
  158. }
  159. /// Add a page to the site
  160. /// The `render` parameter is used in the serve command, when rebuilding a page.
  161. /// If `true`, it will also render the markdown for that page
  162. /// Returns the previous page struct if there was one
  163. pub fn add_page(&mut self, page: Page, render: bool) -> Result<Option<Page>> {
  164. let path = page.file.path.clone();
  165. self.permalinks.insert(page.file.relative.clone(), page.permalink.clone());
  166. let prev = self.pages.insert(page.file.path.clone(), page);
  167. if render {
  168. let insert_anchor = self.find_parent_section_insert_anchor(&self.pages[&path].file.parent);
  169. let mut page = self.pages.get_mut(&path).unwrap();
  170. page.render_markdown(&self.permalinks, &self.tera, &self.config, insert_anchor)?;
  171. }
  172. Ok(prev)
  173. }
  174. /// Add a section to the site
  175. /// The `render` parameter is used in the serve command, when rebuilding a page.
  176. /// If `true`, it will also render the markdown for that page
  177. /// Returns the previous section struct if there was one
  178. pub fn add_section(&mut self, section: Section, render: bool) -> Result<Option<Section>> {
  179. let path = section.file.path.clone();
  180. self.permalinks.insert(section.file.relative.clone(), section.permalink.clone());
  181. let prev = self.sections.insert(section.file.path.clone(), section);
  182. if render {
  183. let mut section = self.sections.get_mut(&path).unwrap();
  184. section.render_markdown(&self.permalinks, &self.tera, &self.config)?;
  185. }
  186. Ok(prev)
  187. }
  188. /// Finds the insert_anchor for the parent section of the directory at `path`.
  189. /// Defaults to `AnchorInsert::None` if no parent section found
  190. pub fn find_parent_section_insert_anchor(&self, parent_path: &PathBuf) -> InsertAnchor {
  191. match self.sections.get(&parent_path.join("_index.md")) {
  192. Some(s) => s.meta.insert_anchor.unwrap(),
  193. None => InsertAnchor::None
  194. }
  195. }
  196. /// Find out the direct subsections of each subsection if there are some
  197. /// as well as the pages for each section
  198. pub fn populate_sections(&mut self) {
  199. let mut grandparent_paths = HashMap::new();
  200. for section in self.sections.values_mut() {
  201. if let Some(ref grand_parent) = section.file.grand_parent {
  202. grandparent_paths.entry(grand_parent.to_path_buf()).or_insert_with(|| vec![]).push(section.clone());
  203. }
  204. // Make sure the pages of a section are empty since we can call that many times on `serve`
  205. section.pages = vec![];
  206. section.ignored_pages = vec![];
  207. }
  208. for page in self.pages.values() {
  209. let parent_section_path = page.file.parent.join("_index.md");
  210. if self.sections.contains_key(&parent_section_path) {
  211. self.sections.get_mut(&parent_section_path).unwrap().pages.push(page.clone());
  212. }
  213. }
  214. for section in self.sections.values_mut() {
  215. match grandparent_paths.get(&section.file.parent) {
  216. Some(paths) => section.subsections.extend(paths.clone()),
  217. None => continue,
  218. };
  219. }
  220. self.sort_sections_pages(None);
  221. }
  222. /// Sorts the pages of the section at the given path
  223. /// By default will sort all sections but can be made to only sort a single one by providing a path
  224. pub fn sort_sections_pages(&mut self, only: Option<&Path>) {
  225. for (path, section) in &mut self.sections {
  226. if let Some(p) = only {
  227. if p != path {
  228. continue;
  229. }
  230. }
  231. let (sorted_pages, cannot_be_sorted_pages) = sort_pages(section.pages.clone(), section.meta.sort_by());
  232. section.pages = populate_previous_and_next_pages(&sorted_pages);
  233. section.ignored_pages = cannot_be_sorted_pages;
  234. }
  235. }
  236. /// Find all the tags and categories if it's asked in the config
  237. pub fn populate_tags_and_categories(&mut self) {
  238. let generate_tags_pages = self.config.generate_tags_pages.unwrap();
  239. let generate_categories_pages = self.config.generate_categories_pages.unwrap();
  240. if !generate_tags_pages && !generate_categories_pages {
  241. return;
  242. }
  243. // TODO: can we pass a reference?
  244. let (tags, categories) = Taxonomy::find_tags_and_categories(
  245. self.pages.values().cloned().collect::<Vec<_>>()
  246. );
  247. if generate_tags_pages {
  248. self.tags = Some(tags);
  249. }
  250. if generate_categories_pages {
  251. self.categories = Some(categories);
  252. }
  253. }
  254. /// Inject live reload script tag if in live reload mode
  255. fn inject_livereload(&self, html: String) -> String {
  256. if self.live_reload {
  257. return html.replace(
  258. "</body>",
  259. r#"<script src="/livereload.js?port=1112&mindelay=10"></script></body>"#
  260. );
  261. }
  262. html
  263. }
  264. /// Copy static file to public directory.
  265. pub fn copy_static_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
  266. let relative_path = path.as_ref().strip_prefix(&self.static_path).unwrap();
  267. let target_path = self.output_path.join(relative_path);
  268. if let Some(parent_directory) = target_path.parent() {
  269. create_dir_all(parent_directory)?;
  270. }
  271. copy(path.as_ref(), &target_path)?;
  272. Ok(())
  273. }
  274. /// Copy the content of the `static` folder into the `public` folder
  275. pub fn copy_static_directory(&self) -> Result<()> {
  276. for entry in WalkDir::new(&self.static_path).into_iter().filter_map(|e| e.ok()) {
  277. let relative_path = entry.path().strip_prefix(&self.static_path).unwrap();
  278. let target_path = self.output_path.join(relative_path);
  279. if entry.path().is_dir() {
  280. if !target_path.exists() {
  281. create_directory(&target_path)?;
  282. }
  283. } else {
  284. let entry_fullpath = self.base_path.join(entry.path());
  285. self.copy_static_file(entry_fullpath)?;
  286. }
  287. }
  288. Ok(())
  289. }
  290. /// Deletes the `public` directory if it exists
  291. pub fn clean(&self) -> Result<()> {
  292. if self.output_path.exists() {
  293. // Delete current `public` directory so we can start fresh
  294. remove_dir_all(&self.output_path).chain_err(|| "Couldn't delete `public` directory")?;
  295. }
  296. Ok(())
  297. }
  298. /// Renders a single content page
  299. pub fn render_page(&self, page: &Page, section: Option<&Section>) -> Result<()> {
  300. ensure_directory_exists(&self.output_path)?;
  301. // Copy the nesting of the content directory if we have sections for that page
  302. let mut current_path = self.output_path.to_path_buf();
  303. for component in page.path.split('/') {
  304. current_path.push(component);
  305. if !current_path.exists() {
  306. create_directory(&current_path)?;
  307. }
  308. }
  309. // Make sure the folder exists
  310. create_directory(&current_path)?;
  311. // Finally, create a index.html file there with the page rendered
  312. let output = page.render_html(&self.tera, &self.config, section)?;
  313. create_file(&current_path.join("index.html"), &self.inject_livereload(output))?;
  314. // Copy any asset we found previously into the same directory as the index.html
  315. for asset in &page.assets {
  316. let asset_path = asset.as_path();
  317. copy(&asset_path, &current_path.join(asset_path.file_name().unwrap()))?;
  318. }
  319. Ok(())
  320. }
  321. /// Deletes the `public` directory and builds the site
  322. pub fn build(&self) -> Result<()> {
  323. self.clean()?;
  324. // Render aliases first to allow overwriting
  325. self.render_aliases()?;
  326. self.render_sections()?;
  327. self.render_orphan_pages()?;
  328. // TODO: render_sitemap is slow
  329. self.render_sitemap()?;
  330. if self.config.generate_rss.unwrap() {
  331. self.render_rss_feed()?;
  332. }
  333. self.render_robots()?;
  334. // `render_categories` and `render_tags` will check whether the config allows
  335. // them to render or not
  336. self.render_categories()?;
  337. self.render_tags()?;
  338. self.copy_static_directory()
  339. }
  340. pub fn render_aliases(&self) -> Result<()> {
  341. for page in self.pages.values() {
  342. if let Some(ref aliases) = page.meta.aliases {
  343. for alias in aliases {
  344. let mut output_path = self.output_path.to_path_buf();
  345. for component in alias.split("/") {
  346. output_path.push(&component);
  347. if !output_path.exists() {
  348. create_directory(&output_path)?;
  349. }
  350. }
  351. create_file(&output_path.join("index.html"), &render_redirect_template(&page.permalink, &self.tera)?)?;
  352. }
  353. }
  354. }
  355. Ok(())
  356. }
  357. /// Renders robots.txt
  358. pub fn render_robots(&self) -> Result<()> {
  359. ensure_directory_exists(&self.output_path)?;
  360. create_file(
  361. &self.output_path.join("robots.txt"),
  362. &self.tera.render("robots.txt", &Context::new())?
  363. )
  364. }
  365. /// Renders all categories and the single category pages if there are some
  366. pub fn render_categories(&self) -> Result<()> {
  367. if let Some(ref categories) = self.categories {
  368. self.render_taxonomy(categories)?;
  369. }
  370. Ok(())
  371. }
  372. /// Renders all tags and the single tag pages if there are some
  373. pub fn render_tags(&self) -> Result<()> {
  374. if let Some(ref tags) = self.tags {
  375. self.render_taxonomy(tags)?;
  376. }
  377. Ok(())
  378. }
  379. fn render_taxonomy(&self, taxonomy: &Taxonomy) -> Result<()> {
  380. if taxonomy.items.is_empty() {
  381. return Ok(())
  382. }
  383. ensure_directory_exists(&self.output_path)?;
  384. let output_path = self.output_path.join(&taxonomy.get_list_name());
  385. let list_output = taxonomy.render_list(&self.tera, &self.config)?;
  386. create_directory(&output_path)?;
  387. create_file(&output_path.join("index.html"), &self.inject_livereload(list_output))?;
  388. for item in &taxonomy.items {
  389. let single_output = taxonomy.render_single_item(item, &self.tera, &self.config)?;
  390. create_directory(&output_path.join(&item.slug))?;
  391. create_file(
  392. &output_path.join(&item.slug).join("index.html"),
  393. &self.inject_livereload(single_output)
  394. )?;
  395. }
  396. Ok(())
  397. }
  398. /// What it says on the tin
  399. pub fn render_sitemap(&self) -> Result<()> {
  400. ensure_directory_exists(&self.output_path)?;
  401. let mut context = Context::new();
  402. context.add("pages", &self.pages.values().collect::<Vec<&Page>>());
  403. context.add("sections", &self.sections.values().collect::<Vec<&Section>>());
  404. let mut categories = vec![];
  405. if let Some(ref c) = self.categories {
  406. let name = c.get_list_name();
  407. categories.push(self.config.make_permalink(&name));
  408. for item in &c.items {
  409. categories.push(
  410. self.config.make_permalink(&format!("{}/{}", &name, item.slug))
  411. );
  412. }
  413. }
  414. context.add("categories", &categories);
  415. let mut tags = vec![];
  416. if let Some(ref t) = self.tags {
  417. let name = t.get_list_name();
  418. tags.push(self.config.make_permalink(&name));
  419. for item in &t.items {
  420. tags.push(
  421. self.config.make_permalink(&format!("{}/{}", &name, item.slug))
  422. );
  423. }
  424. }
  425. context.add("tags", &tags);
  426. let sitemap = self.tera.render("sitemap.xml", &context)?;
  427. create_file(&self.output_path.join("sitemap.xml"), &sitemap)?;
  428. Ok(())
  429. }
  430. pub fn render_rss_feed(&self) -> Result<()> {
  431. ensure_directory_exists(&self.output_path)?;
  432. let mut context = Context::new();
  433. let pages = self.pages.values()
  434. .filter(|p| p.meta.date.is_some())
  435. .take(self.config.rss_limit.unwrap()) // limit to the last n elements
  436. .cloned()
  437. .collect::<Vec<Page>>();
  438. // Don't generate a RSS feed if none of the pages has a date
  439. if pages.is_empty() {
  440. return Ok(());
  441. }
  442. context.add("last_build_date", &pages[0].meta.date);
  443. let (sorted_pages, _) = sort_pages(pages, SortBy::Date);
  444. context.add("pages", &sorted_pages);
  445. context.add("config", &self.config);
  446. let rss_feed_url = if self.config.base_url.ends_with('/') {
  447. format!("{}{}", self.config.base_url, "rss.xml")
  448. } else {
  449. format!("{}/{}", self.config.base_url, "rss.xml")
  450. };
  451. context.add("feed_url", &rss_feed_url);
  452. let sitemap = self.tera.render("rss.xml", &context)?;
  453. create_file(&self.output_path.join("rss.xml"), &sitemap)?;
  454. Ok(())
  455. }
  456. /// Create a hashmap of paths to section
  457. /// For example `content/posts/_index.md` key will be `posts`
  458. /// The index section will always be called `index` so don't use a path such as
  459. /// `content/index/_index.md` yourself
  460. fn get_sections_map(&self) -> HashMap<String, Section> {
  461. self.sections
  462. .values()
  463. .map(|s| (if s.is_index() { "index".to_string() } else { s.file.components.join("/") }, s.clone()))
  464. .collect()
  465. }
  466. /// Renders a single section
  467. pub fn render_section(&self, section: &Section, render_pages: bool) -> Result<()> {
  468. ensure_directory_exists(&self.output_path)?;
  469. let public = self.output_path.clone();
  470. let mut output_path = public.to_path_buf();
  471. for component in &section.file.components {
  472. output_path.push(component);
  473. if !output_path.exists() {
  474. create_directory(&output_path)?;
  475. }
  476. }
  477. if render_pages {
  478. section
  479. .pages
  480. .par_iter()
  481. .map(|p| self.render_page(&p, Some(section)))
  482. .fold(|| Ok(()), Result::and)
  483. .reduce(|| Ok(()), Result::and)?;
  484. }
  485. if !section.meta.should_render() {
  486. return Ok(());
  487. }
  488. if section.meta.is_paginated() {
  489. self.render_paginated(&output_path, section)?;
  490. } else {
  491. let output = section.render_html(
  492. if section.is_index() { self.get_sections_map() } else { HashMap::new() },
  493. &self.tera,
  494. &self.config,
  495. )?;
  496. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  497. }
  498. Ok(())
  499. }
  500. pub fn render_index(&self) -> Result<()> {
  501. self.render_section(&self.sections[&self.base_path.join("content").join("_index.md")], false)
  502. }
  503. /// Renders all sections
  504. pub fn render_sections(&self) -> Result<()> {
  505. self.sections
  506. .values()
  507. .collect::<Vec<_>>()
  508. .into_par_iter()
  509. .map(|s| self.render_section(s, true))
  510. .fold(|| Ok(()), Result::and)
  511. .reduce(|| Ok(()), Result::and)
  512. }
  513. /// Renders all pages that do not belong to any sections
  514. pub fn render_orphan_pages(&self) -> Result<()> {
  515. ensure_directory_exists(&self.output_path)?;
  516. for page in self.get_all_orphan_pages() {
  517. self.render_page(page, None)?;
  518. }
  519. Ok(())
  520. }
  521. /// Renders a list of pages when the section/index is wanting pagination.
  522. fn render_paginated(&self, output_path: &Path, section: &Section) -> Result<()> {
  523. ensure_directory_exists(&self.output_path)?;
  524. let paginate_path = match section.meta.paginate_path {
  525. Some(ref s) => s.clone(),
  526. None => unreachable!()
  527. };
  528. let paginator = Paginator::new(&section.pages, section);
  529. let folder_path = output_path.join(&paginate_path);
  530. create_directory(&folder_path)?;
  531. paginator
  532. .pagers
  533. .par_iter()
  534. .enumerate()
  535. .map(|(i, pager)| {
  536. let page_path = folder_path.join(&format!("{}", i + 1));
  537. create_directory(&page_path)?;
  538. let output = paginator.render_pager(pager, self)?;
  539. if i > 0 {
  540. create_file(&page_path.join("index.html"), &self.inject_livereload(output))?;
  541. } else {
  542. create_file(&output_path.join("index.html"), &self.inject_livereload(output))?;
  543. create_file(&page_path.join("index.html"), &render_redirect_template(&section.permalink, &self.tera)?)?;
  544. }
  545. Ok(())
  546. })
  547. .fold(|| Ok(()), Result::and)
  548. .reduce(|| Ok(()), Result::and)
  549. }
  550. }
  551. /// Resolves an internal link (of the `./posts/something.md#hey` sort) to its absolute link
  552. pub fn resolve_internal_link(link: &str, permalinks: &HashMap<String, String>) -> Result<String> {
  553. // First we remove the ./ since that's gutenberg specific
  554. let clean_link = link.replacen("./", "", 1);
  555. // Then we remove any potential anchor
  556. // parts[0] will be the file path and parts[1] the anchor if present
  557. let parts = clean_link.split('#').collect::<Vec<_>>();
  558. match permalinks.get(parts[0]) {
  559. Some(p) => {
  560. if parts.len() > 1 {
  561. Ok(format!("{}#{}", p, parts[1]))
  562. } else {
  563. Ok(p.to_string())
  564. }
  565. },
  566. None => bail!(format!("Relative link {} not found.", link)),
  567. }
  568. }
  569. #[cfg(test)]
  570. mod tests {
  571. use std::collections::HashMap;
  572. use super::resolve_internal_link;
  573. #[test]
  574. fn can_resolve_valid_internal_link() {
  575. let mut permalinks = HashMap::new();
  576. permalinks.insert("pages/about.md".to_string(), "https://vincent.is/about".to_string());
  577. let res = resolve_internal_link("./pages/about.md", &permalinks).unwrap();
  578. assert_eq!(res, "https://vincent.is/about");
  579. }
  580. #[test]
  581. fn can_resolve_internal_links_with_anchors() {
  582. let mut permalinks = HashMap::new();
  583. permalinks.insert("pages/about.md".to_string(), "https://vincent.is/about".to_string());
  584. let res = resolve_internal_link("./pages/about.md#hello", &permalinks).unwrap();
  585. assert_eq!(res, "https://vincent.is/about#hello");
  586. }
  587. #[test]
  588. fn errors_resolve_inexistant_internal_link() {
  589. let res = resolve_internal_link("./pages/about.md#hello", &HashMap::new());
  590. assert!(res.is_err());
  591. }
  592. }