1#[cfg(test)]
7#[path = "cache_test.rs"]
8mod cache_test;
9
10use crate::storage;
11use crate::types::Cache;
12use fsio::file::{read_text_file, write_text_file};
13use std::path::{Path, PathBuf};
14
15static CACHE_FILE: &'static str = "cache.toml";
16
17fn load_from_path(directory: PathBuf) -> Cache {
18    let file_path = Path::new(&directory).join(CACHE_FILE);
19
20    let mut cache_data = if file_path.exists() {
21        match read_text_file(&file_path) {
22            Ok(cache_str) => {
23                let cache_data: Cache = match toml::from_str(&cache_str) {
24                    Ok(value) => value,
25                    Err(error) => {
26                        info!("Unable to parse cache file, {}", error);
27                        Cache::new()
28                    }
29                };
30
31                cache_data
32            }
33            Err(error) => {
34                info!(
35                    "Unable to read cache file: {:?} error: {}",
36                    &file_path,
37                    error.to_string()
38                );
39                Cache::new()
40            }
41        }
42    } else {
43        Cache::new()
44    };
45
46    match file_path.to_str() {
47        Some(value) => cache_data.file_name = Some(value.to_string()),
48        None => cache_data.file_name = None,
49    };
50
51    cache_data
52}
53
54fn get_cache_directory(migrate: bool) -> Option<PathBuf> {
55    let os_directory = dirs_next::cache_dir();
56    storage::get_storage_directory(os_directory, CACHE_FILE, migrate)
57}
58
59pub(crate) fn load() -> Cache {
61    match get_cache_directory(true) {
62        Some(directory) => load_from_path(directory),
63        None => Cache::new(),
64    }
65}
66
67pub(crate) fn store(cache_data: &Cache) {
69    match get_cache_directory(false) {
70        Some(directory) => {
71            let exists = if directory.exists() {
72                true
73            } else {
74                match fsio::directory::create(&directory) {
75                    Ok(_) => true,
76                    _ => false,
77                }
78            };
79
80            if exists {
81                let file_name = directory.join(CACHE_FILE);
82
83                match toml::to_string_pretty(cache_data) {
84                    Ok(toml_str) => match write_text_file(&file_name, &toml_str) {
85                        Err(error) => info!(
86                            "Error while writing to cache file: {:#?}, error: {:#?}",
87                            &file_name, error
88                        ),
89                        _ => (),
90                    },
91                    Err(error) => info!(
92                        "Error during serialization of cache, file: {:#?}, error: {:#?}",
93                        &file_name, error
94                    ),
95                };
96            }
97        }
98        None => (),
99    }
100}