zakura_network/config/
cache_dir.rs1use std::path::{Path, PathBuf};
4
5use zakura_chain::{common::default_cache_dir, parameters::Network};
6
7const DEFAULT_NETWORK_IDENTITY_DIR: &str = ".zakura";
10
11#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
17#[serde(untagged)]
18pub enum CacheDir {
19 IsEnabled(bool),
22
23 CustomPath(PathBuf),
25}
26
27impl From<bool> for CacheDir {
28 fn from(value: bool) -> Self {
29 CacheDir::IsEnabled(value)
30 }
31}
32
33impl From<PathBuf> for CacheDir {
34 fn from(value: PathBuf) -> Self {
35 CacheDir::CustomPath(value)
36 }
37}
38
39impl CacheDir {
40 pub fn default_path() -> Self {
42 Self::IsEnabled(true)
43 }
44
45 pub fn disabled() -> Self {
47 Self::IsEnabled(false)
48 }
49
50 pub fn custom_path(path: impl AsRef<Path>) -> Self {
52 Self::CustomPath(path.as_ref().to_owned())
53 }
54
55 pub fn is_enabled(&self) -> bool {
57 match self {
58 CacheDir::IsEnabled(is_enabled) => *is_enabled,
59 CacheDir::CustomPath(_) => true,
60 }
61 }
62
63 pub fn peer_cache_file_path(&self, network: &Network) -> Option<PathBuf> {
65 Some(
66 self.cache_dir()?
67 .join("network")
68 .join(format!("{}.peers", network.lowercase_name())),
69 )
70 }
71
72 pub fn zakura_node_secret_key_file_path(&self, network: &Network) -> PathBuf {
77 zakura_node_secret_key_file_path(&default_network_identity_dir(), network)
78 }
79
80 pub fn cache_dir(&self) -> Option<PathBuf> {
82 match self {
83 Self::IsEnabled(is_enabled) => is_enabled.then(default_cache_dir),
84 Self::CustomPath(cache_dir) => Some(cache_dir.to_owned()),
85 }
86 }
87}
88
89impl Default for CacheDir {
90 fn default() -> Self {
91 Self::default_path()
92 }
93}
94
95pub(crate) fn default_network_identity_dir() -> PathBuf {
97 dirs::home_dir()
98 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
99 .join(DEFAULT_NETWORK_IDENTITY_DIR)
100}
101
102pub(crate) fn zakura_node_secret_key_file_path(identity_dir: &Path, network: &Network) -> PathBuf {
105 identity_dir.join(format!(
106 "{}.zakura-iroh-secret-key",
107 network.lowercase_name()
108 ))
109}