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.

fs.rs 5.7KB

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