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.

77 lines
2.6KB

  1. use std::fs::read_dir;
  2. use std::path::{Path, PathBuf};
  3. /// Looks into the current folder for the path and see if there's anything that is not a .md
  4. /// file. Those will be copied next to the rendered .html file
  5. pub fn find_related_assets(path: &Path) -> Vec<PathBuf> {
  6. let mut assets = vec![];
  7. for entry in read_dir(path).unwrap().filter_map(|e| e.ok()) {
  8. let entry_path = entry.path();
  9. if entry_path.is_file() {
  10. match entry_path.extension() {
  11. Some(e) => match e.to_str() {
  12. Some("md") => continue,
  13. _ => assets.push(entry_path.to_path_buf()),
  14. },
  15. None => continue,
  16. }
  17. }
  18. }
  19. assets
  20. }
  21. /// Get word count and estimated reading time
  22. pub fn get_reading_analytics(content: &str) -> (usize, usize) {
  23. // Only works for latin language but good enough for a start
  24. let word_count: usize = content.split_whitespace().count();
  25. // https://help.medium.com/hc/en-us/articles/214991667-Read-time
  26. // 275 seems a bit too high though
  27. (word_count, (word_count / 200))
  28. }
  29. #[cfg(test)]
  30. mod tests {
  31. use std::fs::File;
  32. use tempdir::TempDir;
  33. use super::{find_related_assets, get_reading_analytics};
  34. #[test]
  35. fn can_find_related_assets() {
  36. let tmp_dir = TempDir::new("example").expect("create temp dir");
  37. File::create(tmp_dir.path().join("index.md")).unwrap();
  38. File::create(tmp_dir.path().join("example.js")).unwrap();
  39. File::create(tmp_dir.path().join("graph.jpg")).unwrap();
  40. File::create(tmp_dir.path().join("fail.png")).unwrap();
  41. let assets = find_related_assets(tmp_dir.path());
  42. assert_eq!(assets.len(), 3);
  43. assert_eq!(assets.iter().filter(|p| p.extension().unwrap() != "md").count(), 3);
  44. assert_eq!(assets.iter().filter(|p| p.file_name().unwrap() == "example.js").count(), 1);
  45. assert_eq!(assets.iter().filter(|p| p.file_name().unwrap() == "graph.jpg").count(), 1);
  46. assert_eq!(assets.iter().filter(|p| p.file_name().unwrap() == "fail.png").count(), 1);
  47. }
  48. #[test]
  49. fn reading_analytics_short_text() {
  50. let (word_count, reading_time) = get_reading_analytics("Hello World");
  51. assert_eq!(word_count, 2);
  52. assert_eq!(reading_time, 0);
  53. }
  54. #[test]
  55. fn reading_analytics_long_text() {
  56. let mut content = String::new();
  57. for _ in 0..1000 {
  58. content.push_str(" Hello world");
  59. }
  60. let (word_count, reading_time) = get_reading_analytics(&content);
  61. assert_eq!(word_count, 2000);
  62. assert_eq!(reading_time, 10);
  63. }
  64. }