summaryrefslogtreecommitdiff
path: root/src/parse/de.rs
blob: 4b312a4efd4f59cca4fadaa84ff77a2523015a6d (plain)
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! Deserialize an iris structure from a string.

use crate::{Config, Plugin};

use serde::de;
use std::collections::HashSet;
use std::fmt;
use std::str::FromStr;

/// Errors that can occur when deserializing a type
#[derive(thiserror::Error, Debug)]
pub enum Error {
	/// Occurs when toml could not be deserialized
	#[error(transparent)]
	Toml(#[from] toml::de::Error),
}

macro_rules! error {
    ($($arg:tt)*) => {
        de::Error::custom(format!($($arg)*))
    };
}

struct PluginIDsVisitor;
impl<'de> de::Visitor<'de> for PluginIDsVisitor {
	type Value = Vec<String>;

	fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "single or list of plugin ids")
	}

	fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
	where
		E: de::Error,
	{
		self.visit_string(v.to_string())
	}

	fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
	where
		E: de::Error,
	{
		Ok(vec![v])
	}

	fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
	where
		A: de::SeqAccess<'de>,
	{
		let mut values =
			seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);
		while let Some(value) = seq.next_element::<String>()? {
			values.push(value);
		}
		Ok(values)
	}
}

struct PluginIDsSeed;
impl<'de> de::DeserializeSeed<'de> for PluginIDsSeed {
	type Value = HashSet<String>;

	fn deserialize<D>(self, d: D) -> Result<Self::Value, D::Error>
	where
		D: de::Deserializer<'de>,
	{
		let values = d.deserialize_any(PluginIDsVisitor)?;
		Ok(HashSet::from_iter(values))
	}
}

// plugin visitor with seeded plugin id
struct PluginVisitor(Option<String>);
impl<'de> de::Visitor<'de> for PluginVisitor {
	type Value = Plugin;

	fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match &self.0 {
			Some(id) => write!(f, "arguments for plugin '{id}'"),
			None => write!(f, "plugin id and arguments"),
		}
	}

	fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
	where
		E: de::Error,
	{
		self.visit_string(v.to_string())
	}

	fn visit_borrowed_str<E>(self, v: &'_ str) -> Result<Self::Value, E>
	where
		E: de::Error,
	{
		self.visit_string(v.to_string())
	}

	fn visit_string<E>(self, url: String) -> Result<Self::Value, E>
	where
		E: de::Error,
	{
		let Some(id) = self.0 else {
			return Err(de::Error::missing_field("id"));
		};
		Self::Value::new(id, &url).map_err(E::custom)
	}

	fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
	where
		A: de::MapAccess<'de>,
	{
		// parse each map value as a possbile field for the plugin
		let mut id = self.0; // plugin id (required)
		let mut url = None; // repository url (required)
		let mut commit = None; // commit to lock to
		let mut branch = None; // branch to lock to
		let mut run = None; // command to run on launch
		let mut before = HashSet::new(); // plugins to load before
		let mut after = HashSet::new(); // plugins to load after

		while let Some(key) = map.next_key::<String>()? {
			match key.as_str() {
				// plugin id
				"id" => {
					id = Some(map.next_value::<String>()?);
				}
				// repo url
				"url" => {
					url = Some(map.next_value::<String>()?);
				}
				// locked commit
				"commit" => {
					commit = Some(map.next_value::<String>()?);
				}
				// locked branch
				"branch" => {
					branch = Some(map.next_value::<String>()?);
				}
				// vim command to run on launch
				"run" => {
					run = Some(map.next_value::<String>()?);
				}
				// plugins to load before
				"before" => {
					before = map.next_value_seed(PluginIDsSeed)?;
				}
				// plugins to load after
				"after" => {
					after = map.next_value_seed(PluginIDsSeed)?;
				}
				// invalid key!
				key => return Err(error!("unknown plugin field '{key}'")),
			};
		}

		// id is a required field
		let Some(id) = id else {
			return Err(de::Error::missing_field("id"));
		};

		// url is a required field
		let Some(url) = url else {
			return Err(de::Error::missing_field("url"));
		};

		let mut plugin =
			Self::Value::new(id, &url).map_err(de::Error::custom)?;
		plugin.commit = commit;
		plugin.branch = branch;
		plugin.run = run;
		plugin.before = before;
		plugin.after = after;
		Ok(plugin)
	}
}

// deserialize plugin with possible id
struct PluginSeed(Option<String>);
impl<'de> de::DeserializeSeed<'de> for PluginSeed {
	type Value = Plugin;

	fn deserialize<D>(self, d: D) -> Result<Self::Value, D::Error>
	where
		D: de::Deserializer<'de>,
	{
		d.deserialize_any(PluginVisitor(self.0))
	}
}

// plugins visitor
struct PluginsVisitor;
impl<'de> de::Visitor<'de> for PluginsVisitor {
	type Value = Vec<Plugin>;

	fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str("map of plugin id's to their arguments")
	}

	fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
	where
		A: de::MapAccess<'de>,
	{
		let mut plugins =
			map.size_hint().map_or_else(Vec::new, Vec::with_capacity);
		while let Some(id) = map.next_key()? {
			let plugin = map.next_value_seed(PluginSeed(Some(id)))?;
			plugins.push(plugin);
		}
		Ok(plugins)
	}

	fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
	where
		A: de::SeqAccess<'de>,
	{
		let mut plugins =
			seq.size_hint().map_or_else(Vec::new, Vec::with_capacity);
		while let Some(plugin) = seq.next_element_seed(PluginSeed(None))? {
			plugins.push(plugin);
		}
		Ok(plugins)
	}
}

// plugins seed
struct PluginsSeed;
impl<'de> de::DeserializeSeed<'de> for PluginsSeed {
	type Value = Vec<Plugin>;

	fn deserialize<D>(self, d: D) -> Result<Self::Value, D::Error>
	where
		D: de::Deserializer<'de>,
	{
		d.deserialize_any(PluginsVisitor)
	}
}

// config visitor
struct ConfigVisitor;
impl<'de> de::Visitor<'de> for ConfigVisitor {
	type Value = Config;

	fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str("iris config value")
	}

	fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
	where
		A: de::MapAccess<'de>,
	{
		let mut plugins = None; // list of plugins (required)
		while let Some(key) = map.next_key::<String>()? {
			match key.as_str() {
				"plugins" => {
					plugins = Some(map.next_value_seed(PluginsSeed)?);
				}
				key => return Err(error!("unknown config field '{key}'")),
			};
		}
		// plugins is a required field
		let Some(mut plugins) = plugins else {
			return Err(de::Error::missing_field("plugins"));
		};
        plugins.sort();
		Ok(Config { plugins })
	}
}

impl<'de> de::Deserialize<'de> for Config {
	fn deserialize<D>(d: D) -> Result<Self, D::Error>
	where
		D: de::Deserializer<'de>,
	{
		d.deserialize_map(ConfigVisitor)
	}
}

impl Config {
	pub fn parse(s: &str) -> crate::Result<Self> {
		toml::from_str(s)
			.map_err(Error::from)
			.map_err(crate::Error::from)
	}
}

impl FromStr for Config {
	type Err = crate::Error;
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::parse(s)
	}
}