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.

180 lines
5.7KB

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