rustup_available_packages/
cache.rs1use crate::{manifest::Manifest, Error};
4use chrono::NaiveDate;
5use std::{
6 fs,
7 path::{Path, PathBuf},
8};
9
10pub struct FsCache {
12 storage_path: Option<PathBuf>,
13}
14
15impl FsCache {
16 pub fn new(path: impl AsRef<Path>) -> Result<Self, Error> {
20 let path = path.as_ref();
21 if !path.exists() {
22 fs::create_dir_all(path)
23 .map_err(|e| Error::Io(e, format!("creating path {:?}", path)))?;
24 }
25 Ok(FsCache {
26 storage_path: Some(path.into()),
27 })
28 }
29
30 pub fn noop() -> Self {
32 FsCache { storage_path: None }
33 }
34
35 fn make_file_name(&self, day: NaiveDate) -> PathBuf {
36 self.storage_path
37 .as_ref()
38 .unwrap()
39 .join(day.format("%Y-%m-%d.toml").to_string())
40 }
41}
42
43impl FsCache {
44 pub(crate) fn get(&self, day: NaiveDate) -> Option<Manifest> {
45 if self.storage_path.is_none() {
46 return None;
47 }
48
49 let file_name = self.make_file_name(day);
50 if !file_name.exists() {
51 log::debug!("File {:?} doesn't exist", file_name);
52 return None;
53 }
54 Manifest::load_from_fs(&file_name)
55 .map_err(|e| log::warn!("Can't load manifest: {}", e))
56 .ok()
57 }
58
59 pub(crate) fn store(&self, manifest: &Manifest) {
60 if self.storage_path.is_none() {
61 return;
62 }
63
64 let file_name = self.make_file_name(manifest.date);
65 match manifest.save_to_file(&file_name) {
66 Ok(_) => log::debug!("Manifest stored at {:?}", file_name),
67 Err(e) => log::warn!("Can't save a manifest to the disk: {}", e),
68 }
69 }
70}