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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#![cfg_attr(
test,
allow(clippy::expect_used, clippy::indexing_slicing, clippy::unwrap_used)
)]
use std::collections::HashMap;
use std::fmt;
use std::num::NonZeroU32;
use std::time::Duration;
use serde::Deserialize;
use serde::de::IgnoredAny;
#[derive(Debug)]
pub struct NonEmptyString(String);
impl NonEmptyString {
pub fn new(value: String) -> Option<Self> {
(!value.is_empty()).then_some(NonEmptyString(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for NonEmptyString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for NonEmptyString {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
NonEmptyString::new(value).ok_or_else(|| serde::de::Error::custom("empty string"))
}
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Scheme {
#[default]
Light,
Dark,
}
#[derive(Debug)]
pub struct Variant {
pub name: NonEmptyString,
pub width: NonZeroU32,
pub height: NonZeroU32,
pub scheme: Scheme,
}
/// Deserialized with mlua's strict defaults, so a stray function is an error.
#[derive(Debug)]
pub(crate) struct Spec {
pub(crate) variants: Vec<Variant>,
#[cfg_attr(
not(test),
expect(dead_code, reason = "read once the GitHub task lands")
)]
pub(crate) baseline: Option<BaselineSource>,
pub(crate) name: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SpecTable {
variants: HashMap<String, VariantTable>,
#[serde(default)]
baseline: Option<BaselineSource>,
#[serde(default)]
name: Option<String>,
// Already taken by the caller; declared so unknown-field errors list them.
#[serde(default, rename = "server")]
_server: Option<IgnoredAny>,
#[serde(default, rename = "flow")]
_flow: Option<IgnoredAny>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct VariantTable {
viewport: (NonZeroU32, NonZeroU32),
#[serde(default)]
scheme: Scheme,
}
impl<'de> Deserialize<'de> for Spec {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let SpecTable {
variants,
baseline,
name,
..
} = SpecTable::deserialize(deserializer)?;
if variants.is_empty() {
return Err(serde::de::Error::custom("variants must not be empty"));
}
let mut parsed = Vec::with_capacity(variants.len());
for (key, variant) in &variants {
let name = NonEmptyString::new(key.clone())
.ok_or_else(|| serde::de::Error::custom("empty variant name"))?;
parsed.push(Variant {
name,
width: variant.viewport.0,
height: variant.viewport.1,
scheme: variant.scheme,
});
}
// Lua tables are unordered, so sorted names are the run order.
parsed.sort_unstable_by(|a, b| a.name.as_str().cmp(b.name.as_str()));
Ok(Spec {
variants: parsed,
baseline,
name,
})
}
}
/// See the design doc's GitHub releases section.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[expect(dead_code, reason = "read once the GitHub task lands")]
pub(crate) struct BaselineSource {
pub(crate) repo: NonEmptyString,
#[serde(default)]
pub(crate) asset: Option<NonEmptyString>,
}
#[derive(Clone, Debug)]
pub struct ServerSpec {
pub program: String,
pub args: Vec<String>,
pub timeout: Duration,
}
impl ServerSpec {
pub fn command_line(&self) -> String {
std::iter::once(&self.program)
.chain(&self.args)
.map(String::as_str)
.collect::<Vec<_>>()
.join(" ")
}
}
impl<'de> Deserialize<'de> for ServerSpec {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Table {
cmd: Vec<String>,
#[serde(default = "default_timeout")]
timeout: f64,
}
let table = Table::deserialize(deserializer)?;
let mut words = table.cmd.into_iter();
let Some(program) = words.next() else {
return Err(serde::de::Error::custom("cmd must not be empty"));
};
let Some(timeout) = Duration::try_from_secs_f64(table.timeout)
.ok()
.filter(|timeout| !timeout.is_zero())
else {
return Err(serde::de::Error::custom(
"timeout must be a positive number of seconds",
));
};
Ok(ServerSpec {
program,
args: words.collect(),
timeout,
})
}
}
fn default_timeout() -> f64 {
30.0
}
#[cfg(test)]
mod tests {
use super::*;
use mlua::Lua;
use mlua::LuaSerdeExt as _;
use mlua::Value;
fn with_value<T>(body: &str, check: impl FnOnce(&Lua, Value) -> T) -> T {
let lua = unsafe { Lua::unsafe_new() };
let value: Value = lua.load(body).eval().expect("lua source");
check(&lua, value)
}
#[test]
fn parses_a_setup_table() {
with_value(
r#"return {
variants = {
mobile = {viewport = {375, 812}},
desktop = {viewport = {1280, 900}, scheme = "dark"},
},
baseline = {repo = "kejadlen/ketchup"},
}"#,
|lua, value| {
let setup: Spec = lua.from_value(value).expect("setup table");
assert_eq!(setup.variants.len(), 2);
assert_eq!(setup.variants[0].name.as_str(), "desktop");
assert_eq!(setup.variants[0].scheme, Scheme::Dark);
assert_eq!(setup.variants[1].name.as_str(), "mobile");
assert_eq!(setup.variants[1].scheme, Scheme::Light);
assert_eq!(
setup.baseline.as_ref().expect("baseline").repo.as_str(),
"kejadlen/ketchup"
);
assert_eq!(setup.name, None);
},
);
}
#[test]
fn rejects_setup_shapes() {
let cases = [
(r#"return {baseline = nil}"#, "missing field `variants`"),
(r#"return {variants = {}, extra = 1}"#, "unknown field"),
(r#"return {variants = {}}"#, "variants must not be empty"),
(
r#"return {variants = {desktop = {viewport = {1280, 900}}}, extra = 1}"#,
"`server`, `flow`",
),
(
r#"return {variants = {desktop = {viewport = {1280, 900}, extra = 1}}}"#,
"unknown field",
),
(
r#"return {variants = {[""] = {viewport = {1280, 900}}}}"#,
"empty variant name",
),
(
r#"return {variants = {desktop = {viewport = {0, 900}}}}"#,
"invalid value",
),
(
r#"return {variants = {desktop = {scheme = "dark"}}}"#,
"missing field `viewport`",
),
(
r#"return {variants = {desktop = {viewport = {1280, 900}, scheme = "sepia"}}}"#,
"unknown variant",
),
(
r#"return {variants = {desktop = {viewport = {1280, 900}}}, baseline = {asset = "x.tar.gz"}}"#,
"missing field `repo`",
),
];
for (body, fragment) in cases {
with_value(body, |lua, value| {
let error = lua
.from_value::<Spec>(value)
.expect_err("expected an invalid setup table");
assert!(
error.to_string().contains(fragment),
"expected {error:?} to contain {fragment:?}"
);
});
}
}
#[test]
fn rejects_functions_in_setup() {
with_value(
r#"return {variants = {desktop = {viewport = {1280, 900}}}, name = (function() end)}"#,
|lua, value| {
let error = lua
.from_value::<Spec>(value)
.expect_err("functions cannot appear in setup");
assert!(error.to_string().contains("unsupported"));
},
);
}
#[test]
fn parses_a_server_table_with_defaults() {
with_value(r#"return {cmd = {"true"}}"#, |lua, value| {
let server: ServerSpec = lua.from_value(value).expect("server table");
assert_eq!(server.program, "true");
assert!(server.args.is_empty());
assert_eq!(server.timeout, Duration::from_secs(30));
});
}
#[test]
fn parses_a_server_table_with_a_timeout() {
with_value(
r#"return {cmd = {"app", "serve"}, timeout = 5}"#,
|lua, value| {
let server: ServerSpec = lua.from_value(value).expect("server table");
assert_eq!(server.program, "app");
assert_eq!(server.args, vec!["serve".to_owned()]);
assert_eq!(server.command_line(), "app serve");
assert_eq!(server.timeout, Duration::from_secs(5));
},
);
}
#[test]
fn rejects_bad_server_tables() {
let cases = [
(r#"return {timeout = 5}"#, "missing field `cmd`"),
(r#"return {cmd = {}}"#, "cmd must not be empty"),
(r#"return {cmd = {"true"}, extra = 1}"#, "unknown field"),
(r#"return {cmd = "true"}"#, "invalid type"),
(
r#"return {cmd = {"true"}, timeout = 0}"#,
"timeout must be a positive",
),
(
r#"return {cmd = {"true"}, timeout = -1}"#,
"timeout must be a positive",
),
(
r#"return {cmd = {"true"}, timeout = 1e30}"#,
"timeout must be a positive",
),
];
for (body, fragment) in cases {
with_value(body, |lua, value| {
let error = lua
.from_value::<ServerSpec>(value)
.expect_err("expected an invalid server table");
assert!(
error.to_string().contains(fragment),
"expected {error:?} to contain {fragment:?}"
);
});
}
}
}