opys-bundle 0.3.1

The opys bundle: a manifest and the blobs it names, as one zip.
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Options: what a bundle lets whoever launches it choose.
//!
//! A manifest's rules test features and its strings name variables, and
//! nothing in it says which of those are a player's to set. A bundle's head
//! does: a tree of options, each with what a launcher needs to draw it. An
//! option fills a variable, except a `feature`, which switches a feature on
//! and holds the options that only matter while it is.
//!
//! This is the schema alone. What was chosen, and turning that into the
//! `vars` and `features` an install takes, belongs to whoever shows the form.

use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

/// One value a `select` offers, and what to call it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Choice {
    pub value: String,
    pub label: String,
}

/// What every option says about itself to the person choosing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Label {
    pub title: String,
    pub subtitle: Option<String>,
}

/// One option. `name` is the variable it fills or, for a `Feature`, the
/// feature it switches.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "OptionWire", into = "OptionWire")]
pub enum OptionDef {
    Slider {
        name: String,
        label: Label,
        min: f64,
        max: f64,
        step: f64,
        default: f64,
        unit: Option<String>,
    },
    Select {
        name: String,
        label: Label,
        choices: Vec<Choice>,
        default: String,
    },
    Text {
        name: String,
        label: Label,
        placeholder: Option<String>,
        default: Option<String>,
    },
    File {
        name: String,
        label: Label,
    },
    Directory {
        name: String,
        label: Label,
    },
    Feature {
        name: String,
        label: Label,
        default: bool,
        options: Vec<OptionDef>,
    },
}

impl OptionDef {
    pub fn name(&self) -> &str {
        match self {
            OptionDef::Slider { name, .. }
            | OptionDef::Select { name, .. }
            | OptionDef::Text { name, .. }
            | OptionDef::File { name, .. }
            | OptionDef::Directory { name, .. }
            | OptionDef::Feature { name, .. } => name,
        }
    }

    pub fn label(&self) -> &Label {
        match self {
            OptionDef::Slider { label, .. }
            | OptionDef::Select { label, .. }
            | OptionDef::Text { label, .. }
            | OptionDef::File { label, .. }
            | OptionDef::Directory { label, .. }
            | OptionDef::Feature { label, .. } => label,
        }
    }
}

/// Discriminated by which field is present, like every wire shape here, and
/// that field holds the name: `{ "slider": "xmx", … }`. A struct of options
/// rather than an untagged enum, so a field on the wrong kind is named.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct OptionWire {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    slider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    select: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    text: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    file: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    directory: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    feature: Option<String>,

    title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    subtitle: Option<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    min: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    max: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    step: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    unit: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    choices: Option<Vec<Choice>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    placeholder: Option<String>,
    /// A number on a slider, a string on a select or a text, a boolean on a
    /// feature: the one field whose type depends on the kind.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    default: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    options: Option<Vec<OptionDef>>,
}

const KINDS: &str = "`slider`, `select`, `text`, `file`, `directory`, `feature`";

impl TryFrom<OptionWire> for OptionDef {
    type Error = String;

    fn try_from(raw: OptionWire) -> Result<Self, Self::Error> {
        let kinds = [
            ("slider", &raw.slider),
            ("select", &raw.select),
            ("text", &raw.text),
            ("file", &raw.file),
            ("directory", &raw.directory),
            ("feature", &raw.feature),
        ];
        let mut named = kinds
            .iter()
            .filter_map(|(kind, name)| name.as_ref().map(|name| (*kind, name.clone())));
        let (kind, name) = named
            .next()
            .ok_or_else(|| format!("an option is one of {KINDS}, and this names none"))?;
        if let Some((other, _)) = named.next() {
            return Err(format!(
                "an option is one kind, and this is both `{kind}` and `{other}`"
            ));
        }

        // Each kind takes what is its own and refuses the rest, so a `min` on
        // a select is an error rather than a field nothing reads.
        let present = [
            ("min", raw.min.is_some()),
            ("max", raw.max.is_some()),
            ("step", raw.step.is_some()),
            ("unit", raw.unit.is_some()),
            ("choices", raw.choices.is_some()),
            ("placeholder", raw.placeholder.is_some()),
            ("default", raw.default.is_some()),
            ("options", raw.options.is_some()),
        ];
        let allowed: &[&str] = match kind {
            "slider" => &["min", "max", "step", "unit", "default"],
            "select" => &["choices", "default"],
            "text" => &["placeholder", "default"],
            "feature" => &["default", "options"],
            _ => &[],
        };
        if let Some((field, _)) = present
            .iter()
            .find(|(field, is)| *is && !allowed.contains(field))
        {
            return Err(format!("`{field}` does not belong on a {kind} (`{name}`)"));
        }

        let missing = |field: &str| format!("{kind} `{name}` has no `{field}`");
        let label = Label {
            title: raw.title,
            subtitle: raw.subtitle,
        };
        Ok(match kind {
            "slider" => OptionDef::Slider {
                min: raw.min.ok_or_else(|| missing("min"))?,
                max: raw.max.ok_or_else(|| missing("max"))?,
                step: raw.step.ok_or_else(|| missing("step"))?,
                default: raw
                    .default
                    .ok_or_else(|| missing("default"))?
                    .as_f64()
                    .ok_or_else(|| format!("the `default` of slider `{name}` is a number"))?,
                unit: raw.unit,
                name,
                label,
            },
            "select" => OptionDef::Select {
                choices: raw.choices.ok_or_else(|| missing("choices"))?,
                default: match raw.default.ok_or_else(|| missing("default"))? {
                    serde_json::Value::String(value) => value,
                    _ => return Err(format!("the `default` of select `{name}` is a string")),
                },
                name,
                label,
            },
            "text" => OptionDef::Text {
                placeholder: raw.placeholder,
                default: match raw.default {
                    None => None,
                    Some(serde_json::Value::String(value)) => Some(value),
                    Some(_) => return Err(format!("the `default` of text `{name}` is a string")),
                },
                name,
                label,
            },
            "file" => OptionDef::File { name, label },
            "directory" => OptionDef::Directory { name, label },
            _ => OptionDef::Feature {
                default: match raw.default {
                    None => false,
                    Some(serde_json::Value::Bool(value)) => value,
                    Some(_) => {
                        return Err(format!("the `default` of feature `{name}` is a boolean"))
                    }
                },
                options: raw.options.unwrap_or_default(),
                name,
                label,
            },
        })
    }
}

impl From<OptionDef> for OptionWire {
    fn from(option: OptionDef) -> Self {
        let labelled = |label: Label| OptionWire {
            title: label.title,
            subtitle: label.subtitle,
            ..OptionWire::default()
        };
        match option {
            OptionDef::Slider {
                name,
                label,
                min,
                max,
                step,
                default,
                unit,
            } => OptionWire {
                slider: Some(name),
                min: Some(min),
                max: Some(max),
                step: Some(step),
                default: Some(default.into()),
                unit,
                ..labelled(label)
            },
            OptionDef::Select {
                name,
                label,
                choices,
                default,
            } => OptionWire {
                select: Some(name),
                choices: Some(choices),
                default: Some(default.into()),
                ..labelled(label)
            },
            OptionDef::Text {
                name,
                label,
                placeholder,
                default,
            } => OptionWire {
                text: Some(name),
                placeholder,
                default: default.map(Into::into),
                ..labelled(label)
            },
            OptionDef::File { name, label } => OptionWire {
                file: Some(name),
                ..labelled(label)
            },
            OptionDef::Directory { name, label } => OptionWire {
                directory: Some(name),
                ..labelled(label)
            },
            // What a feature leaves out reads back as what it was: off, and
            // holding nothing.
            OptionDef::Feature {
                name,
                label,
                default,
                options,
            } => OptionWire {
                feature: Some(name),
                default: default.then_some(true.into()),
                options: (!options.is_empty()).then_some(options),
                ..labelled(label)
            },
        }
    }
}

/// A bundle's options, checked as a whole: a tree that has been read is one a
/// form can be drawn from without looking at it twice.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "Vec<OptionDef>", into = "Vec<OptionDef>")]
pub struct Options(Vec<OptionDef>);

impl Options {
    /// Refuses a tree that would mean two things or nothing: a variable or a
    /// feature named twice, a slider with no range, a select whose default is
    /// not among its choices.
    pub fn new(options: Vec<OptionDef>) -> Result<Self, String> {
        let mut seen = Seen::default();
        options
            .iter()
            .try_for_each(|option| check(option, &mut seen))?;
        Ok(Options(options))
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn as_slice(&self) -> &[OptionDef] {
        &self.0
    }
}

impl TryFrom<Vec<OptionDef>> for Options {
    type Error = String;

    fn try_from(options: Vec<OptionDef>) -> Result<Self, Self::Error> {
        Options::new(options)
    }
}

impl From<Options> for Vec<OptionDef> {
    fn from(options: Options) -> Self {
        options.0
    }
}

/// The names taken so far. A variable and a feature are named apart, since
/// nothing reads one where it reads the other.
#[derive(Default)]
struct Seen<'a> {
    vars: BTreeSet<&'a str>,
    features: BTreeSet<&'a str>,
}

fn check<'a>(option: &'a OptionDef, seen: &mut Seen<'a>) -> Result<(), String> {
    let name = option.name();
    if name.is_empty() {
        return Err("an option has an empty name".to_owned());
    }
    let (taken, what) = match option {
        OptionDef::Feature { .. } => (&mut seen.features, "feature"),
        _ => (&mut seen.vars, "variable"),
    };
    if !taken.insert(name) {
        return Err(format!("{what} `{name}` is an option twice"));
    }

    match option {
        OptionDef::Slider {
            min,
            max,
            step,
            default,
            ..
        } => {
            if ![min, max, step, default].iter().all(|n| n.is_finite()) {
                return Err(format!("slider `{name}` has a number that is not finite"));
            }
            if min >= max {
                return Err(format!("slider `{name}` has no range: {min} to {max}"));
            }
            if *step <= 0.0 {
                return Err(format!("slider `{name}` has a step of {step}"));
            }
            if default < min || default > max {
                return Err(format!(
                    "the default of slider `{name}`, {default}, is outside {min} to {max}"
                ));
            }
        }
        OptionDef::Select {
            choices, default, ..
        } => {
            let mut values = BTreeSet::new();
            if let Some(twice) = choices.iter().find(|c| !values.insert(c.value.as_str())) {
                return Err(format!("select `{name}` offers `{}` twice", twice.value));
            }
            if !values.contains(default.as_str()) {
                return Err(format!(
                    "the default of select `{name}`, `{default}`, is not one of its choices"
                ));
            }
        }
        OptionDef::Feature { options, .. } => {
            options.iter().try_for_each(|child| check(child, seen))?;
        }
        OptionDef::Text { .. } | OptionDef::File { .. } | OptionDef::Directory { .. } => {}
    }
    Ok(())
}