use std::path::{Path, PathBuf};
use zebra_chain::{common::default_cache_dir, parameters::Network};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum CacheDir {
IsEnabled(bool),
CustomPath(PathBuf),
}
impl From<bool> for CacheDir {
fn from(value: bool) -> Self {
CacheDir::IsEnabled(value)
}
}
impl From<PathBuf> for CacheDir {
fn from(value: PathBuf) -> Self {
CacheDir::CustomPath(value)
}
}
impl CacheDir {
pub fn default_path() -> Self {
Self::IsEnabled(true)
}
pub fn disabled() -> Self {
Self::IsEnabled(false)
}
pub fn custom_path(path: impl AsRef<Path>) -> Self {
Self::CustomPath(path.as_ref().to_owned())
}
pub fn is_enabled(&self) -> bool {
match self {
CacheDir::IsEnabled(is_enabled) => *is_enabled,
CacheDir::CustomPath(_) => true,
}
}
pub fn peer_cache_file_path(&self, network: &Network) -> Option<PathBuf> {
Some(
self.cache_dir()?
.join("network")
.join(format!("{}.peers", network.lowercase_name())),
)
}
pub fn cache_dir(&self) -> Option<PathBuf> {
match self {
Self::IsEnabled(is_enabled) => is_enabled.then(default_cache_dir),
Self::CustomPath(cache_dir) => Some(cache_dir.to_owned()),
}
}
}
impl Default for CacheDir {
fn default() -> Self {
Self::default_path()
}
}