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
use crate::{Resource, YyResourceHandler, YypBoss};
use serde::{Deserialize, Serialize};
use std::{
fmt::Debug,
path::{Path, PathBuf},
};
use yy_typings::ViewPath;
pub trait YyResource: Serialize + for<'de> Deserialize<'de> + Clone + Default {
type AssociatedData: Debug;
const SUBPATH_NAME: &'static str;
const RESOURCE: Resource;
fn name(&self) -> &str;
fn set_name(&mut self, name: String);
fn parent_path(&self) -> ViewPath;
fn get_handler(yyp_boss: &mut YypBoss) -> &mut YyResourceHandler<Self>;
fn deserialize_associated_data(
&self,
directory_path: Option<&Path>,
data: SerializedData,
) -> anyhow::Result<Self::AssociatedData>;
fn serialize_associated_data(
&self,
directory_path: &Path,
data: &Self::AssociatedData,
) -> anyhow::Result<()>;
fn cleanup_on_replace(
&self,
files_to_delete: &mut Vec<PathBuf>,
folders_to_delete: &mut Vec<PathBuf>,
);
}
#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[serde(tag = "dataType")]
pub enum SerializedData {
Value { data: String },
Filepath { data: PathBuf },
DefaultValue,
}
#[derive(Debug, thiserror::Error)]
pub enum SerializedDataError {
#[error(
"given a `Data::File` tag, but was not given a working directory on startup. cannot parse"
)]
NoFileMode,
#[error("given a `Data::File` tag, but path didn't exist, wasn't a file, or couldn't be read. path was {}", .0.to_string_lossy())]
BadDataFile(std::path::PathBuf),
#[error(transparent)]
CouldNotParseData(#[from] serde_json::Error),
#[error(
"cannot be represented with utf8 encoding; must use `Data::File` or `Data::DefaultValue`"
)]
CannotUseValue,
}
impl SerializedData {
pub fn read_data_as_file<T>(
self,
working_directory: Option<&std::path::Path>,
) -> Result<T, SerializedDataError>
where
for<'de> T: serde::Deserialize<'de> + Default,
{
match self {
SerializedData::Value { data } => {
serde_json::from_str(&data).map_err(SerializedDataError::CouldNotParseData)
}
SerializedData::Filepath { data } => {
if let Some(wd) = working_directory {
let path = wd.join(data);
std::fs::read_to_string(&path).map_or_else(
|_| Err(SerializedDataError::BadDataFile(path)),
|data| {
serde_json::from_str(&data)
.map_err(SerializedDataError::CouldNotParseData)
},
)
} else {
Err(SerializedDataError::NoFileMode)
}
}
SerializedData::DefaultValue => Ok(T::default()),
}
}
}