forgeFRENBrowse the repositories

roneocratesroneo-coresrcfs_util.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

179 lines · 5.1 KiBRustRaw
  1. use std::fs;
  2. use std::path::{Path, PathBuf};
  3. use std::sync::atomic::{AtomicU64, Ordering};
  4. use crate::error::{Result, RoneoError};
  5. static TEMP_COUNTER: AtomicU64 = AtomicU64::new(0);
  6. /// Lightweight zero-dependency RAII temporary directory (automatically deleted on `Drop`).
  7. #[derive(Debug)]
  8. pub struct TempDir {
  9. path: PathBuf,
  10. }
  11. impl TempDir {
  12. pub fn new() -> Result<Self> {
  13. Self::with_prefix("roneo")
  14. }
  15. pub fn with_prefix(prefix: &str) -> Result<Self> {
  16. let base = std::env::temp_dir();
  17. let pid = std::process::id();
  18. let nanos = std::time::SystemTime::now()
  19. .duration_since(std::time::UNIX_EPOCH)
  20. .map_or(0, |d| d.as_nanos());
  21. for _ in 0..64 {
  22. let seq = TEMP_COUNTER.fetch_add(1, Ordering::Relaxed);
  23. let candidate = base.join(format!("{prefix}-{pid}-{nanos:x}-{seq}"));
  24. match create_private_dir(&candidate) {
  25. Ok(()) => return Ok(Self { path: candidate }),
  26. Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
  27. Err(e) => return Err(RoneoError::io(&candidate, e)),
  28. }
  29. }
  30. Err(RoneoError::TemplateSource(
  31. "Failed to allocate a unique temporary directory".into(),
  32. ))
  33. }
  34. pub fn path(&self) -> &Path {
  35. &self.path
  36. }
  37. }
  38. impl Drop for TempDir {
  39. fn drop(&mut self) {
  40. let _ = fs::remove_dir_all(&self.path);
  41. }
  42. }
  43. #[cfg(unix)]
  44. fn create_private_dir(path: &Path) -> std::io::Result<()> {
  45. use std::os::unix::fs::DirBuilderExt;
  46. fs::DirBuilder::new().mode(0o700).create(path)
  47. }
  48. #[cfg(not(unix))]
  49. fn create_private_dir(path: &Path) -> std::io::Result<()> {
  50. fs::create_dir(path)
  51. }
  52. /// Entry yielded while walking a directory tree on disk.
  53. #[derive(Debug, Clone)]
  54. pub struct DiskEntry {
  55. pub abs_path: PathBuf,
  56. pub rel_path: PathBuf,
  57. pub is_dir: bool,
  58. pub is_symlink: bool,
  59. }
  60. /// Recursively walk `root` in deterministic sorted filename order, calling `visitor` on each entry.
  61. /// When `visitor` returns `Ok(false)` for a directory, that directory's subtree is skipped.
  62. pub fn walk_dir_sorted<F>(root: &Path, follow_symlinks: bool, mut visitor: F) -> Result<()>
  63. where
  64. F: FnMut(DiskEntry) -> Result<bool>,
  65. {
  66. walk_recursive(root, root, follow_symlinks, &mut visitor)
  67. }
  68. fn walk_recursive<F>(
  69. root: &Path,
  70. current: &Path,
  71. follow_symlinks: bool,
  72. visitor: &mut F,
  73. ) -> Result<()>
  74. where
  75. F: FnMut(DiskEntry) -> Result<bool>,
  76. {
  77. let mut entries: Vec<_> = fs::read_dir(current)
  78. .map_err(|e| RoneoError::io(current, e))?
  79. .collect::<std::result::Result<Vec<_>, _>>()
  80. .map_err(|e| RoneoError::io(current, e))?;
  81. entries.sort_by_key(fs::DirEntry::file_name);
  82. for entry in entries {
  83. let abs_path = entry.path();
  84. let rel_path = abs_path
  85. .strip_prefix(root)
  86. .map_or_else(|_| PathBuf::from(entry.file_name()), Path::to_path_buf);
  87. let sym_meta = fs::symlink_metadata(&abs_path).map_err(|e| RoneoError::io(&abs_path, e))?;
  88. let is_symlink = sym_meta.file_type().is_symlink();
  89. let is_dir = if is_symlink && follow_symlinks {
  90. fs::metadata(&abs_path).is_ok_and(|m| m.is_dir())
  91. } else {
  92. sym_meta.is_dir()
  93. };
  94. let enter = visitor(DiskEntry {
  95. abs_path: abs_path.clone(),
  96. rel_path,
  97. is_dir,
  98. is_symlink,
  99. })?;
  100. if is_dir && enter {
  101. walk_recursive(root, &abs_path, follow_symlinks, visitor)?;
  102. }
  103. }
  104. Ok(())
  105. }
  106. #[cfg(unix)]
  107. pub fn set_executable(dst: &Path) -> Result<()> {
  108. use std::os::unix::fs::PermissionsExt;
  109. fs::set_permissions(dst, fs::Permissions::from_mode(0o755)).map_err(|e| RoneoError::io(dst, e))
  110. }
  111. #[cfg(not(unix))]
  112. pub fn set_executable(_dst: &Path) -> Result<()> {
  113. Ok(())
  114. }
  115. #[cfg(unix)]
  116. pub fn file_mode_from_metadata(meta: &fs::Metadata) -> Option<u32> {
  117. use std::os::unix::fs::PermissionsExt;
  118. Some(meta.permissions().mode())
  119. }
  120. #[cfg(not(unix))]
  121. pub fn file_mode_from_metadata(_meta: &fs::Metadata) -> Option<u32> {
  122. None
  123. }
  124. #[cfg(unix)]
  125. pub fn set_file_mode(dst: &Path, mode: u32) -> Result<()> {
  126. use std::os::unix::fs::PermissionsExt;
  127. fs::set_permissions(dst, fs::Permissions::from_mode(mode)).map_err(|e| RoneoError::io(dst, e))
  128. }
  129. #[cfg(not(unix))]
  130. pub fn set_file_mode(_dst: &Path, _mode: u32) -> Result<()> {
  131. Ok(())
  132. }
  133. #[cfg(unix)]
  134. pub fn copy_permissions(src: &Path, dst: &Path) -> Result<()> {
  135. let perms = fs::metadata(src)
  136. .map_err(|e| RoneoError::io(src, e))?
  137. .permissions();
  138. fs::set_permissions(dst, perms).map_err(|e| RoneoError::io(dst, e))
  139. }
  140. #[cfg(not(unix))]
  141. pub fn copy_permissions(_src: &Path, _dst: &Path) -> Result<()> {
  142. Ok(())
  143. }
  144. #[cfg(unix)]
  145. pub fn create_symlink(target: &Path, link: &Path) -> Result<()> {
  146. std::os::unix::fs::symlink(target, link).map_err(|e| RoneoError::io(link, e))
  147. }
  148. #[cfg(windows)]
  149. pub fn create_symlink(target: &Path, link: &Path) -> Result<()> {
  150. std::os::windows::fs::symlink_file(target, link).map_err(|e| RoneoError::io(link, e))
  151. }