Delete all but the newest `keep` ` .YYYY-MM-DD. ` files in `dir`, leaving every other file alone. Several processes can prune at once, so a file that is already gone is not a failure; other failures are returned for the caller to report.
(
dir: &Path,
prefix: &str,
suffix: &str,
keep: usize,
)
| 9 | /// so a file that is already gone is not a failure; other failures are |
| 10 | /// returned for the caller to report. |
| 11 | pub(super) fn prune( |
| 12 | dir: &Path, |
| 13 | prefix: &str, |
| 14 | suffix: &str, |
| 15 | keep: usize, |
| 16 | ) -> Vec<(PathBuf, io::Error)> { |
| 17 | let entries = match fs::read_dir(dir) { |
| 18 | Ok(entries) => entries, |
| 19 | Err(error) => return vec![(dir.to_path_buf(), error)], |
| 20 | }; |
| 21 | let mut daily: Vec<PathBuf> = entries |
| 22 | .filter_map(Result::ok) |
| 23 | .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) |
| 24 | .map(|entry| entry.path()) |
| 25 | .filter(|path| is_daily_file(path, prefix, suffix)) |
| 26 | .collect(); |
| 27 | // ISO dates sort by name. |
| 28 | daily.sort(); |
| 29 | let excess = daily.len().saturating_sub(keep); |
| 30 | daily |
| 31 | .into_iter() |
| 32 | .take(excess) |
| 33 | .filter_map(|path| match fs::remove_file(&path) { |
| 34 | Ok(()) => None, |
| 35 | Err(error) if error.kind() == io::ErrorKind::NotFound => None, |
| 36 | Err(error) => Some((path, error)), |
| 37 | }) |
| 38 | .collect() |
| 39 | } |
| 40 | |
| 41 | fn is_daily_file(path: &Path, prefix: &str, suffix: &str) -> bool { |
| 42 | let Some(name) = path.file_name().and_then(|name| name.to_str()) else { |