A library for writing host-specific, single-binary configuration management and deployment tools
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.

57 lines
1.4 KiB

7 years ago
7 years ago
5 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
5 years ago
5 years ago
7 years ago
  1. use std::error::Error;
  2. use std::fs::read_dir;
  3. use std::path::PathBuf;
  4. use std::str::FromStr;
  5. use std::time::{SystemTime, UNIX_EPOCH};
  6. pub trait Storage {
  7. fn write_filename(&self) -> PathBuf;
  8. fn read_filename(&self) -> Result<PathBuf, Box<dyn Error>>;
  9. fn recent_date(&self) -> Result<u64, Box<dyn Error>>;
  10. }
  11. #[derive(Debug, Clone)]
  12. pub struct SimpleStorage(PathBuf);
  13. impl SimpleStorage {
  14. pub const fn new(base: PathBuf) -> Self {
  15. Self(base)
  16. }
  17. fn get_path(&self, date: Option<u64>) -> PathBuf {
  18. match date {
  19. Some(d) => self.0.join(d.to_string()),
  20. None => self.0.clone(),
  21. }
  22. }
  23. }
  24. impl Storage for SimpleStorage {
  25. fn write_filename(&self) -> PathBuf {
  26. self.get_path(Some(
  27. SystemTime::now()
  28. .duration_since(UNIX_EPOCH)
  29. .unwrap()
  30. .as_secs(),
  31. ))
  32. }
  33. fn read_filename(&self) -> Result<PathBuf, Box<dyn Error>> {
  34. Ok(self.get_path(Some(self.recent_date()?)))
  35. }
  36. fn recent_date(&self) -> Result<u64, Box<dyn Error>> {
  37. let dir = self.get_path(None);
  38. read_dir(dir)?
  39. .map(|entry| {
  40. entry
  41. .ok()
  42. .and_then(|e| e.file_name().into_string().ok())
  43. .and_then(|filename| u64::from_str(&filename).ok())
  44. })
  45. .fold(None, |maybe_newest, maybe_time| {
  46. maybe_newest.into_iter().chain(maybe_time).max()
  47. })
  48. .ok_or_else(|| "Not found".to_string().into())
  49. }
  50. }