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.

43 lines
1.3 KiB

7 years ago
  1. use std::error::Error;
  2. use std::fs::read_dir;
  3. use std::str::FromStr;
  4. use std::time::{SystemTime, UNIX_EPOCH};
  5. pub trait Storage {
  6. fn write_filename(&self) -> String;
  7. fn read_filename(&self) -> Result<String, Box<Error>>;
  8. fn recent_date(&self) -> Result<u64, Box<Error>>;
  9. }
  10. pub struct SimpleStorage(String, String);
  11. impl SimpleStorage {
  12. pub fn new(base: String, filename: String) -> Self {
  13. SimpleStorage(base, filename)
  14. }
  15. fn get_path(&self, date: Option<u64>) -> String {
  16. match date {
  17. Some(d) => format!("{}/_{}/{}", self.0, self.1, d),
  18. None => format!("{}/_{}", self.0, self.1)
  19. }
  20. }
  21. }
  22. impl Storage for SimpleStorage {
  23. fn write_filename(&self) -> String {
  24. self.get_path(Some(SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs()))
  25. }
  26. fn read_filename(&self) -> Result<String, Box<Error>> {
  27. Ok(self.get_path(Some(try!(self.recent_date()))))
  28. }
  29. fn recent_date(&self) -> Result<u64, Box<Error>> {
  30. let dir = self.get_path(None);
  31. try!(read_dir(dir))
  32. .map(|entry| entry.ok().and_then(|e| e.file_name().into_string().ok()).and_then(|filename| u64::from_str(&filename).ok()))
  33. .fold(None, |maybe_newest, maybe_time| maybe_newest.into_iter().chain(maybe_time).max())
  34. .ok_or("Not found".to_string().into())
  35. }
  36. }