config_file_macros/
lib.rs1#[macro_export]
2macro_rules! generate_wrapper_methods {
3 ($wrapper:ident, $deserialize_method:path, $serialize_method:path, $serialize_pretty_method:path, $deserialize_error:expr, $serialize_error:expr) => {
4 impl<T> $wrapper<T>
5 where
6 T: DeserializeOwned + Serialize,
7 {
8 pub fn load(path: &str, ignore_error: bool) -> Option<T> {
10 match std::fs::read_to_string(path) {
11 Ok(text) => Self::loads(&text, ignore_error),
12 Err(e) => {
13 if !ignore_error {
14 tracing::error!(
15 func = "std::fs::read_to_string",
16 path = path,
17 error_tag = "ReadFileError",
18 error_str = e.to_string(),
19 );
20 }
21 None
22 }
23 }
24 }
25
26 pub fn loads(text: &str, ignore_error: bool) -> Option<T> {
28 match $deserialize_method(text) {
29 Ok(c) => Some(c),
30 Err(e) => {
31 if !ignore_error {
32 tracing::error!(
33 func = stringify!($deserialize_method),
34 error_tag = $deserialize_error,
35 error_str = e.to_string(),
36 message = text,
37 );
38 }
39 None
40 }
41 }
42 }
43
44 pub fn dump(&self, pretty: bool, ignore_error: bool) -> bool {
46 Self::dump_data(&self.inner, &self.path, pretty, ignore_error)
47 }
48
49 pub fn dump_data(data: &T, path: &str, pretty: bool, ignore_error: bool) -> bool {
51 let text = Self::dumps_data(data, pretty, ignore_error);
52 if text.is_empty() {
53 return false;
54 }
55
56 match std::fs::write(path, text.as_bytes()) {
57 Ok(_) => true,
58 Err(e) => {
59 if !ignore_error {
60 tracing::error!(
61 func = "std::fs::write",
62 cwd = std::env::current_dir().unwrap().to_str().unwrap(),
63 path = path,
64 error_tag = "WriteFileError",
65 error_str = e.to_string(),
66 message = text,
67 );
68 }
69 false
70 }
71 }
72 }
73
74 pub fn dumps(&self, pretty: bool, ignore_error: bool) -> String {
76 Self::dumps_data(&self.inner, pretty, ignore_error)
77 }
78
79 pub fn dumps_data(data: &T, pretty: bool, ignore_error: bool) -> String {
81 let f = if !pretty {
82 $serialize_method
83 } else {
84 $serialize_pretty_method
85 };
86 match f(data) {
87 Ok(text) => text,
88 Err(e) => {
89 if !ignore_error {
90 tracing::error!(
91 func = if !pretty {
92 stringify!($serialize_method)
93 } else {
94 stringify!($serialize_pretty_method)
95 },
96 error_tag = $serialize_error,
97 error_str = e.to_string(),
98 );
99 }
100 String::new()
101 }
102 }
103 }
104 }
105 };
106}