configurant 0.8.15

Schema-first configuration: declare values in a TOML schema, layer schema defaults with the file, environment and arguments your code hands in, validate with named errors, explain where each value came from. No generated code; secrets never printed.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! A serialisable view-model of an editing [`Session`], for renderers on any platform.
//!
//! A [`Driver`] owns a session. A renderer (terminal, desktop, browser, phone) asks for a [`View`] (plain
//! data: every field with its question, example, hint and choices, and what a confirmation would do),
//! sends [`Event`]s back, and gets a [`Reply`] with the new view. Everything here derives `Serialize`
//! (or `Deserialize` for events), so the renderer can live in another process or language. The rules are
//! the session's own: a secret is `<redacted>` and cannot be set, a bad value is refused with a named
//! error, and nothing is written or executed. The host takes the [`Confirmed`] from
//! [`Driver::take_confirmed`] after a `confirm` event and does the writing and the plan itself.
//!
//! A form draws `sections` (a title and the keys under it) and looks each key up in `fields`. A section's title
//! is the key's first segment (`server` for `server.port`) unless the schema gives the value `section = "Network"`;
//! a schema author marks a rarely-changed value with `advanced = true`, and the renderer decides how to fold it
//! (the view only says which fields are advanced). `file_only` lists tables and maps, which are edited in the file.
//!
//! In short: a renderer shows `view()`, turns each click or keystroke into an [`Event`] (JSON works), and
//! calls `apply`; the host writes the file once `take_confirmed` returns something.
//!
//! ```
//! use configurant::{Loader, Needs, Schema, edit::Session, view::{Driver, Event}};
//! let toml = r#"
//! project = { name = "app", version = "1", summary = "demo", schema_version = 1 }
//! value = [{ key = "server.port", type = "int", default = 8080, prompt = "Which port?", description = "port" }]
//! "#;
//! let schema = Schema::parse(toml).unwrap();
//! let config = Loader::new(&schema).build().unwrap();
//! // `Needs` ranks a provider module's choices (none here); `None` is the module registry (none here).
//! let mut driver = Driver::new(Session::new(&config, None), Needs::default());
//! println!("{}", driver.view().fields[0].prompt); // Which port?
//! println!("{}", driver.view().sections[0].title); // server: fields are grouped for a form
//! let event: Event = serde_json::from_str(r#"{"event":"set","key":"server.port","text":"9000"}"#).unwrap();
//! assert!(driver.apply(event).refused.is_none());
//! assert!(driver.apply(Event::Confirm).confirmed);
//! // `file_text` takes the config file's current text (empty for a new file) and keeps its comments.
//! let text = driver.take_confirmed().unwrap().file_text("").unwrap();
//! assert!(text.contains("port = 9000")); // the host writes this text to the config file
//! ```

use serde::{Deserialize, Serialize};

use crate::edit::{Confirmed, Session};
use crate::module::{ActionKind, Needs};

/// One selectable value and why it is (or is not) a good fit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ChoiceView {
    /// The text to send in a `set` event.
    pub id: String,
    /// Why it is, or is not, a good fit.
    pub reason: String,
}

/// One value, as a form shows it. A secret's `current` is `<redacted>` and it is not editable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FieldView {
    /// Dotted key to send back in events.
    pub key: String,
    /// The type's name: `string`, `int`, `float`, `bool`, `path`, `enum` or `list`.
    pub ty: &'static str,
    /// The schema's description.
    pub description: String,
    /// The question to ask: the schema's `prompt`, else the description.
    pub prompt: String,
    /// A sample value as it would be typed.
    pub example: Option<String>,
    /// A sentence of help for the person answering.
    pub hint: Option<String>,
    /// The section it is listed under (one of the view's `sections`).
    pub section: String,
    /// A form may fold it away until asked.
    pub advanced: bool,
    /// Marked secret in the schema.
    pub secret: bool,
    /// The `<source>:<reference>` a secret declares; never the secret.
    pub source: Option<String>,
    /// Changing it needs a restart.
    pub restart: bool,
    /// A `set` event may change it; false for a secret.
    pub editable: bool,
    /// The allowed values (an enum's, or the provider module's list for the session's needs).
    pub choices: Vec<ChoiceView>,
    /// The module whose list the value is chosen from.
    pub provider: Option<String>,
    /// The value now in force, as shown.
    pub current: Option<String>,
    /// The staged value, as shown.
    pub staged: Option<String>,
}

/// One staged change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ChangeView {
    /// Dotted key being changed.
    pub key: String,
    /// The value now in force, as shown.
    pub from: Option<String>,
    /// The new value, as shown.
    pub to: String,
}

/// One step of a module's plan, for display.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ActionView {
    /// What the action would do, in words.
    pub description: String,
    /// `note`, `data-transfer` or `step`.
    pub kind: &'static str,
    /// Source id of a data transfer.
    pub from: Option<String>,
    /// Target id of a data transfer.
    pub to: Option<String>,
}

/// What a confirmation would do.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ReviewView {
    /// The staged changes.
    pub changes: Vec<ChangeView>,
    /// Changed keys that need a restart.
    pub restart: Vec<String>,
    /// The provider modules' plan for these changes.
    pub actions: Vec<ActionView>,
}

/// A group of fields in a form. It names keys only; the values are in `fields`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SectionView {
    /// The section's heading.
    pub title: String,
    /// The keys listed under it.
    pub keys: Vec<String>,
}

/// A table or map, which only the configuration file can set.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FileOnlyView {
    /// Dotted key of the table or map.
    pub key: String,
    /// `table` or `map`.
    pub kind: &'static str,
    /// The schema's description.
    pub description: String,
}

/// Everything a renderer draws.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct View {
    /// Every `[[value]]`, in schema order.
    pub fields: Vec<FieldView>,
    /// The fields grouped for a form: sections in order of first appearance, keys in schema order.
    pub sections: Vec<SectionView>,
    /// Tables and maps: show where they are edited, not an editor.
    pub file_only: Vec<FileOnlyView>,
    /// What confirming would do now.
    pub review: ReviewView,
    /// Where the person is in the steps; present only in a [`Wizard`](crate::wizard::Wizard)'s view.
    pub wizard: Option<WizardView>,
}

/// What a renderer can ask for.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case", deny_unknown_fields)]
pub enum Event {
    /// Stage `text` as the new value of `key`.
    Set {
        /// Dotted key to change.
        key: String,
        /// The new value, written as on the command line.
        text: String,
    },
    /// Forget a staged change.
    Unset {
        /// Dotted key to restore.
        key: String,
    },
    /// The user said yes to the review.
    Confirm,
    /// To the next step that is shown, or the review after the last. A wizard only.
    Next,
    /// To the previous step that is shown. A wizard only.
    Back,
    /// Back to a step already reached. A wizard only.
    Goto {
        /// Id of the step to return to.
        step: String,
    },
}

/// Why an event changed nothing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Refusal {
    /// The key the event named (empty when it named none).
    pub key: String,
    /// The error in words.
    pub error: String,
}

/// The answer to one event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Reply {
    /// The state after the event.
    pub view: View,
    /// Set when the event changed nothing.
    pub refused: Option<Refusal>,
    /// True when this event confirmed the review; the host then calls [`Driver::take_confirmed`].
    pub confirmed: bool,
}

/// An editing session driven by events.
pub struct Driver<'a> {
    session: Session<'a>,
    needs: Needs,
    confirmed: Option<Confirmed>,
}

impl<'a> Driver<'a> {
    /// `needs` is what provider modules rank their choices for.
    pub fn new(session: Session<'a>, needs: Needs) -> Self {
        Driver {
            session,
            needs,
            confirmed: None,
        }
    }

    /// The value in force for `key` as plain text (see [`Session::plain`]).
    pub fn plain(&self, key: &str) -> Option<String> {
        self.session.plain(key)
    }

    /// The schema being edited.
    pub fn schema(&self) -> &crate::schema::Schema {
        self.session.schema()
    }

    /// The current state, as data.
    pub fn view(&self) -> View {
        let fields: Vec<FieldView> = self
            .session
            .fields()
            .into_iter()
            .map(|f| FieldView {
                choices: self
                    .session
                    .choices(&f.key, &self.needs)
                    .into_iter()
                    .map(|c| ChoiceView {
                        id: c.id,
                        reason: c.reason,
                    })
                    .collect(),
                ty: f.ty.name(),
                key: f.key,
                description: f.description,
                prompt: f.prompt,
                example: f.example,
                hint: f.hint,
                section: f.section,
                advanced: f.advanced,
                secret: f.secret,
                source: f.source,
                restart: f.restart,
                editable: f.editable,
                provider: f.provider,
                current: f.current,
                staged: f.staged,
            })
            .collect();
        let mut sections: Vec<SectionView> = Vec::new();
        for f in &fields {
            match sections.iter_mut().find(|s| s.title == f.section) {
                Some(s) => s.keys.push(f.key.clone()),
                None => sections.push(SectionView {
                    title: f.section.clone(),
                    keys: vec![f.key.clone()],
                }),
            }
        }
        let file_only = self
            .session
            .file_only()
            .into_iter()
            .map(|t| FileOnlyView {
                key: t.key,
                kind: t.kind,
                description: t.description,
            })
            .collect();
        let review = self.session.review();
        let actions = review
            .plan()
            .actions
            .iter()
            .map(|a| {
                let (kind, from, to) = match &a.kind {
                    ActionKind::Note => ("note", None, None),
                    ActionKind::DataTransfer { from, to } => {
                        ("data-transfer", Some(from.clone()), Some(to.clone()))
                    }
                    ActionKind::Step(_) => ("step", None, None),
                };
                ActionView {
                    description: a.description.clone(),
                    kind,
                    from,
                    to,
                }
            })
            .collect();
        View {
            wizard: None,
            fields,
            sections,
            file_only,
            review: ReviewView {
                changes: review
                    .changes()
                    .iter()
                    .map(|c| ChangeView {
                        key: c.key.clone(),
                        from: c.from.clone(),
                        to: c.to.clone(),
                    })
                    .collect(),
                restart: review.restart_needed().to_vec(),
                actions,
            },
        }
    }

    /// Handle one event. A refused event changes nothing and the reply says why.
    #[must_use = "a refused event is reported only in the reply"]
    pub fn apply(&mut self, event: Event) -> Reply {
        let mut refused = None;
        let mut confirmed = false;
        match event {
            Event::Set { key, text } => {
                self.confirmed = None;
                if let Err(e) = self.session.stage(&key, &text) {
                    refused = Some(Refusal {
                        key,
                        error: e.to_string(),
                    });
                }
            }
            Event::Unset { key } => {
                self.confirmed = None;
                self.session.unstage(&key);
            }
            Event::Next | Event::Back | Event::Goto { .. } => {
                refused = Some(Refusal {
                    key: String::new(),
                    error: "this session has no steps: wrap the driver in a Wizard to use next, back and goto"
                        .into(),
                });
            }
            Event::Confirm => {
                let review = self.session.review();
                if review.is_empty() {
                    refused = Some(Refusal {
                        key: String::new(),
                        error: "there is nothing to confirm: no value has been changed".into(),
                    });
                } else {
                    self.confirmed = Some(review.confirm());
                    confirmed = true;
                }
            }
        }
        Reply {
            view: self.view(),
            refused,
            confirmed,
        }
    }

    /// The confirmed changes, once, after a `confirm` event. The host writes the file and runs the plan.
    pub fn take_confirmed(&mut self) -> Option<Confirmed> {
        self.confirmed.take()
    }
}

/// One step in the list a renderer draws as progress.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StepView {
    /// The step's id, as `goto` takes it.
    pub id: String,
    /// The step's heading.
    pub title: String,
    /// `done`, `current`, `todo` or `hidden` (its `when` does not hold now).
    pub state: &'static str,
}

/// Where the person is, and what they can do next.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct WizardView {
    /// Every step, in order.
    pub steps: Vec<StepView>,
    /// The current step's id; `None` at the review.
    pub current: Option<String>,
    /// No step is current: only here does `confirm` work.
    pub at_review: bool,
    /// The current step's title, plain intro and keys (empty at the review).
    pub title: String,
    /// Sentences shown above the current step's questions.
    pub intro: String,
    /// Keys asked in the current step.
    pub keys: Vec<String>,
    /// `back` has somewhere to go.
    pub can_back: bool,
    /// `next` has somewhere to go.
    pub can_next: bool,
    /// Why the position is not the one saved (a stale step id on resume), once.
    pub note: Option<String>,
}