1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
|
use async_trait::async_trait;
use bincode2;
use ron;
use serde::{Deserialize, Serialize};
use std::{
borrow::Cow,
env::current_dir,
io::Error,
path::{Path, PathBuf},
};
use tokio::{fs, io::AsyncReadExt};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ConfigFormat {
Yaml,
Toml,
Ron,
Json,
Bincode,
}
impl ConfigFormat {
fn from_filename(filename: &str) -> Option<Self> {
if filename.ends_with(".yaml") || filename.ends_with(".yml") {
Some(Self::Yaml)
} else if filename.ends_with(".toml") || filename.ends_with(".tom") {
Some(Self::Toml)
} else if filename.ends_with(".ron") {
Some(Self::Ron)
} else if filename.ends_with(".json") {
Some(Self::Json)
} else if filename.ends_with(".bcfg") {
Some(Self::Bincode)
} else {
None
}
}
}
/// # Trait - ConfigFile
///
/// Used to implement more convenient persistent storage functionality for structs
///
/// This trait requires the struct to implement Default and serde's Serialize and Deserialize traits
///
/// ## Implementation
///
/// ```ignore
/// // Your struct
/// #[derive(Default, Serialize, Deserialize)]
/// struct YourData;
///
/// impl ConfigFile for YourData {
/// type DataType = YourData;
///
/// // Specify default path
/// fn default_path() -> Result<PathBuf, Error> {
/// Ok(current_dir()?.join("data.json"))
/// }
/// }
/// ```
///
/// > **Using derive macro**
/// >
/// > We provide the derive macro `#[derive(ConfigFile)]`
/// >
/// > You can implement this trait more quickly, please check the module cfg_file::cfg_file_derive
///
#[async_trait]
pub trait ConfigFile: Serialize + for<'a> Deserialize<'a> + Default {
type DataType: Serialize + for<'a> Deserialize<'a> + Default + Send + Sync;
fn default_path() -> Result<PathBuf, Error>;
/// # Read from default path
///
/// Read data from the path specified by default_path()
///
/// ```ignore
/// fn main() -> Result<(), std::io::Error> {
/// let data = YourData::read().await?;
/// }
/// ```
async fn read() -> Result<Self::DataType, std::io::Error>
where
Self: Sized + Send + Sync,
{
let path = Self::default_path()?;
Self::read_from(path).await
}
/// # Read from the given path
///
/// Read data from the path specified by the path parameter
///
/// ```ignore
/// fn main() -> Result<(), std::io::Error> {
/// let data_path = current_dir()?.join("data.json");
/// let data = YourData::read_from(data_path).await?;
/// }
/// ```
async fn read_from(path: impl AsRef<Path> + Send) -> Result<Self::DataType, std::io::Error>
where
Self: Sized + Send + Sync,
{
let path = path.as_ref();
let cwd = current_dir()?;
let file_path = cwd.join(path);
// Check if file exists
if fs::metadata(&file_path).await.is_err() {
return Err(std::io::Error::new(
std::io::ErrorKind::NotFound,
"Config file not found",
));
}
// Open file
let mut file = fs::File::open(&file_path).await?;
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
// Determine file format
let format = file_path
.file_name()
.and_then(|name| name.to_str())
.and_then(ConfigFormat::from_filename)
.unwrap_or(ConfigFormat::Json); // Default to JSON
// Deserialize based on format
let result = match format {
ConfigFormat::Yaml => serde_yaml::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?,
ConfigFormat::Toml => toml::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?,
ConfigFormat::Ron => ron::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?,
ConfigFormat::Json => serde_json::from_str(&contents)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?,
ConfigFormat::Bincode => {
// For Bincode, we need to read the file as bytes
let bytes = fs::read(&file_path).await?;
bincode2::deserialize(&bytes)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?
}
};
Ok(result)
}
/// # Write to default path
///
/// Write data to the path specified by default_path()
///
/// ```ignore
/// fn main() -> Result<(), std::io::Error> {
/// let data = YourData::default();
/// YourData::write(&data).await?;
/// }
/// ```
async fn write(val: &Self::DataType) -> Result<(), std::io::Error>
where
Self: Sized + Send + Sync,
{
let path = Self::default_path()?;
Self::write_to(val, path).await
}
/// # Write to the given path
///
/// Write data to the path specified by the path parameter
///
/// ```ignore
/// fn main() -> Result<(), std::io::Error> {
/// let data = YourData::default();
/// let data_path = current_dir()?.join("data.json");
/// YourData::write_to(&data, data_path).await?;
/// }
/// ```
async fn write_to(
val: &Self::DataType,
path: impl AsRef<Path> + Send,
) -> Result<(), std::io::Error>
where
Self: Sized + Send + Sync,
{
let path = path.as_ref();
if let Some(parent) = path.parent()
&& !parent.exists()
{
tokio::fs::create_dir_all(parent).await?;
}
let cwd = current_dir()?;
let file_path = cwd.join(path);
// Determine file format
let format = file_path
.file_name()
.and_then(|name| name.to_str())
.and_then(ConfigFormat::from_filename)
.unwrap_or(ConfigFormat::Json); // Default to JSON
match format {
ConfigFormat::Yaml => {
let contents = serde_yaml::to_string(val)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
fs::write(&file_path, contents).await?
}
ConfigFormat::Toml => {
let contents = toml::to_string(val)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
fs::write(&file_path, contents).await?
}
ConfigFormat::Ron => {
let mut pretty_config = ron::ser::PrettyConfig::new();
pretty_config.new_line = Cow::from("\n");
pretty_config.indentor = Cow::from(" ");
let contents = ron::ser::to_string_pretty(val, pretty_config)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
fs::write(&file_path, contents).await?
}
ConfigFormat::Json => {
let contents = serde_json::to_string(val)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
fs::write(&file_path, contents).await?
}
ConfigFormat::Bincode => {
let bytes = bincode2::serialize(val)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
fs::write(&file_path, bytes).await?
}
}
Ok(())
}
/// Check if the file returned by `default_path` exists
fn exist() -> bool
where
Self: Sized + Send + Sync,
{
let Ok(path) = Self::default_path() else {
return false;
};
path.exists()
}
}
|