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.

151 lines
4.7KB

  1. use std::io::prelude::*;
  2. use std::fs::{File, create_dir_all, read_dir, copy};
  3. use std::path::{Path, PathBuf};
  4. use walkdir::WalkDir;
  5. use errors::{Result, ResultExt};
  6. /// Create a file with the content given
  7. pub fn create_file(path: &Path, content: &str) -> Result<()> {
  8. let mut file = File::create(&path)?;
  9. file.write_all(content.as_bytes())?;
  10. Ok(())
  11. }
  12. /// Create a directory at the given path if it doesn't exist already
  13. pub fn ensure_directory_exists(path: &Path) -> Result<()> {
  14. if !path.exists() {
  15. create_directory(path)?;
  16. }
  17. Ok(())
  18. }
  19. /// Very similar to `create_dir` from the std except it checks if the folder
  20. /// exists before creating it
  21. pub fn create_directory(path: &Path) -> Result<()> {
  22. if !path.exists() {
  23. create_dir_all(path)
  24. .chain_err(|| format!("Was not able to create folder {}", path.display()))?;
  25. }
  26. Ok(())
  27. }
  28. /// Return the content of a file, with error handling added
  29. pub fn read_file(path: &Path) -> Result<String> {
  30. let mut content = String::new();
  31. File::open(path)
  32. .chain_err(|| format!("Failed to open '{:?}'", path.display()))?
  33. .read_to_string(&mut content)?;
  34. // Remove utf-8 BOM if any.
  35. if content.starts_with("\u{feff}") {
  36. content.drain(..3);
  37. }
  38. Ok(content)
  39. }
  40. /// Looks into the current folder for the path and see if there's anything that is not a .md
  41. /// file. Those will be copied next to the rendered .html file
  42. pub fn find_related_assets(path: &Path) -> Vec<PathBuf> {
  43. let mut assets = vec![];
  44. for entry in read_dir(path).unwrap().filter_map(|e| e.ok()) {
  45. let entry_path = entry.path();
  46. if entry_path.is_file() {
  47. match entry_path.extension() {
  48. Some(e) => match e.to_str() {
  49. Some("md") => continue,
  50. _ => assets.push(entry_path.to_path_buf()),
  51. },
  52. None => continue,
  53. }
  54. }
  55. }
  56. assets
  57. }
  58. /// Copy a file but takes into account where to start the copy as
  59. /// there might be folders we need to create on the way
  60. pub fn copy_file(src: &Path, dest: &PathBuf, base_path: &PathBuf) -> Result<()> {
  61. let relative_path = src.strip_prefix(base_path).unwrap();
  62. let target_path = dest.join(relative_path);
  63. if let Some(parent_directory) = target_path.parent() {
  64. create_dir_all(parent_directory)?;
  65. }
  66. copy(src, target_path)?;
  67. Ok(())
  68. }
  69. pub fn copy_directory(src: &PathBuf, dest: &PathBuf) -> Result<()> {
  70. for entry in WalkDir::new(src).into_iter().filter_map(|e| e.ok()) {
  71. let relative_path = entry.path().strip_prefix(src).unwrap();
  72. let target_path = dest.join(relative_path);
  73. if entry.path().is_dir() {
  74. if !target_path.exists() {
  75. create_directory(&target_path)?;
  76. }
  77. } else {
  78. copy_file(entry.path(), dest, src)?;
  79. }
  80. }
  81. Ok(())
  82. }
  83. /// Compares source and target files' timestamps and returns true if the source file
  84. /// has been created _or_ updated after the target file has
  85. pub fn file_stale<PS, PT>(p_source: PS, p_target: PT) -> bool where PS: AsRef<Path>, PT: AsRef<Path> {
  86. let p_source = p_source.as_ref();
  87. let p_target = p_target.as_ref();
  88. if !p_target.exists() {
  89. return true;
  90. }
  91. let get_time = |path: &Path| path.metadata().ok().and_then(|meta| {
  92. Some(match (meta.created().ok(), meta.modified().ok()) {
  93. (Some(tc), Some(tm)) => tc.max(tm),
  94. (Some(tc), None) => tc,
  95. (None, Some(tm)) => tm,
  96. (None, None) => return None,
  97. })
  98. });
  99. let time_source = get_time(p_source);
  100. let time_target = get_time(p_target);
  101. time_source.and_then(|ts| time_target.map(|tt| ts > tt)).unwrap_or(true)
  102. }
  103. #[cfg(test)]
  104. mod tests {
  105. use std::fs::File;
  106. use tempfile::tempdir;
  107. use super::find_related_assets;
  108. #[test]
  109. fn can_find_related_assets() {
  110. let tmp_dir = tempdir().expect("create temp dir");
  111. File::create(tmp_dir.path().join("index.md")).unwrap();
  112. File::create(tmp_dir.path().join("example.js")).unwrap();
  113. File::create(tmp_dir.path().join("graph.jpg")).unwrap();
  114. File::create(tmp_dir.path().join("fail.png")).unwrap();
  115. let assets = find_related_assets(tmp_dir.path());
  116. assert_eq!(assets.len(), 3);
  117. assert_eq!(assets.iter().filter(|p| p.extension().unwrap() != "md").count(), 3);
  118. assert_eq!(assets.iter().filter(|p| p.file_name().unwrap() == "example.js").count(), 1);
  119. assert_eq!(assets.iter().filter(|p| p.file_name().unwrap() == "graph.jpg").count(), 1);
  120. assert_eq!(assets.iter().filter(|p| p.file_name().unwrap() == "fail.png").count(), 1);
  121. }
  122. }