configurant 0.6.3

Schema-first configuration: declare values in a TOML schema, layer defaults, file, environment and command line, 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Editing for front ends (TUI, GUI): the part of a front end that is not drawing.
//!
//! A [`Session`] stages changes to a loaded [`Config`]. Every change meets the rules a load does
//! (type, range, choices, provider module), a secret is refused (it comes only from the environment),
//! and nothing happens until the user confirms: [`Session::review`] returns a [`Review`] (what would
//! change, what needs a restart, the modules' [`Plan`] for display), and only [`Review::confirm`]
//! yields the [`Confirmed`] that can produce the new file text and hands over the plan to execute.
//! This crate never writes a file or executes a plan; the front end does, after asking.

use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

use toml_edit::{Array, DocumentMut, Item, Table, TableLike, Value as EditValue};

use crate::config::{Config, check_value, cross_key_errors};
use crate::error::{ConfigError, Origin, suggestion};
use crate::module::{Choice, Modules, Needs, Plan};
use crate::value::{Value, ValueType};

const REDACTED: &str = "<redacted>";

/// One value as a front end lists it. A secret's value is `<redacted>` and it is not editable.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Field {
    pub key: String,
    pub ty: ValueType,
    pub description: String,
    /// The question to ask for this value: the schema's `prompt`, else the description.
    pub prompt: String,
    /// A sample value as it would be typed (never present for a secret).
    pub example: Option<String>,
    /// One short sentence of help for the person answering.
    pub hint: Option<String>,
    /// The form section it is listed under.
    pub section: String,
    /// A form may fold it away until asked.
    pub advanced: bool,
    pub secret: bool,
    /// The `<source>:<reference>` a secret declares: a name, never the secret.
    pub source: Option<String>,
    pub restart: bool,
    pub editable: bool,
    /// The schema's `choices` (empty unless it is an enum). A provider's list is [`Session::choices`].
    pub choices: Vec<String>,
    /// The module whose list this 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>,
}

/// A table or map: listed so a form can say it is edited in the configuration file.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct FileOnly {
    pub key: String,
    /// `table` or `map`.
    pub kind: &'static str,
    pub description: String,
}

/// Staged changes to a loaded configuration.
pub struct Session<'a> {
    config: &'a Config,
    modules: Option<&'a Modules>,
    staged: BTreeMap<String, Value>,
}

impl fmt::Debug for Session<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Session")
            .field("config", self.config)
            .field("staged", &self.staged)
            .finish()
    }
}

impl<'a> Session<'a> {
    pub fn new(config: &'a Config, modules: Option<&'a Modules>) -> Self {
        Session {
            config,
            modules,
            staged: BTreeMap::new(),
        }
    }

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

    /// The value in force for `key` (staged if any, else current) as plain text, which is what a step's
    /// `when` compares: no quotes around a string. A secret is `<redacted>`, so a `when` on a secret can only
    /// test that it is set.
    pub fn plain(&self, key: &str) -> Option<String> {
        let def = self.config.schema().get(key)?;
        let v = self.staged.get(key).or_else(|| self.config.value(key))?;
        if def.secret {
            return Some(REDACTED.to_owned());
        }
        Some(match v {
            Value::String(s) | Value::Enum(s) => s.clone(),
            Value::Path(p) => p.display().to_string(),
            other => other.shown(),
        })
    }

    /// Every value of the schema, in schema order.
    pub fn fields(&self) -> Vec<Field> {
        self.config
            .schema()
            .values()
            .iter()
            .map(|d| Field {
                key: d.key.clone(),
                ty: d.ty,
                description: d.description.clone(),
                prompt: d.question().to_owned(),
                example: d.example.clone(),
                hint: d.hint.clone(),
                section: d.section_title().to_owned(),
                advanced: d.advanced,
                secret: d.secret,
                source: d.source.clone(),
                restart: d.restart,
                editable: !d.secret,
                choices: d.choices.clone(),
                provider: d.provider.clone(),
                current: self.config.value(&d.key).map(|v| shown(d.secret, v)),
                staged: self.staged.get(&d.key).map(Value::shown),
            })
            .collect()
    }

    /// The tables and maps, which only a configuration file can set, in schema order (tables first).
    pub fn file_only(&self) -> Vec<FileOnly> {
        let schema = self.config.schema();
        let tables = schema.tables().iter().map(|t| FileOnly {
            key: t.key.clone(),
            kind: "table",
            description: t.description.clone(),
        });
        let maps = schema.maps().iter().map(|m| FileOnly {
            key: m.key.clone(),
            kind: "map",
            description: m.description.clone(),
        });
        tables.chain(maps).collect()
    }

    /// The choices for a key: its provider module's list for `needs`, else the schema's own.
    pub fn choices(&self, key: &str, needs: &Needs) -> Vec<Choice> {
        let Some(def) = self.config.schema().get(key) else {
            return Vec::new();
        };
        if let Some(m) = def
            .provider
            .as_deref()
            .and_then(|p| self.modules.and_then(|m| m.get(p)))
        {
            return m.list_choices(needs);
        }
        def.choices.iter().map(|c| Choice::new(c, "")).collect()
    }

    /// Stage `text` as the new value of `key`. Refused, with a named error and nothing staged, if the
    /// key is unknown or secret or the value does not fit. Staging the value already in force is not a
    /// change and un-stages the key.
    pub fn stage(&mut self, key: &str, text: &str) -> Result<(), ConfigError> {
        let schema = self.config.schema();
        let Some(def) = schema.get(key) else {
            if schema.table(key).is_some() || schema.map(key).is_some() {
                return Err(ConfigError::FileOnly {
                    key: key.to_owned(),
                });
            }
            let known = schema.all_keys();
            return Err(ConfigError::UnknownKey {
                key: key.to_owned(),
                suggestion: suggestion(key, known),
                origin: Origin::Edit,
            });
        };
        if def.secret {
            return Err(ConfigError::SecretInForbiddenSource {
                key: key.to_owned(),
                origin: Origin::Edit,
            });
        }
        let value = Value::parse_text(def.ty, text).ok_or_else(|| ConfigError::WrongType {
            key: key.to_owned(),
            expected: def.ty.name(),
            found: format!("{text:?}"),
            origin: Origin::Edit,
        })?;
        check_value(def, &value, self.modules, &Origin::Edit)?;
        self.check_across_keys(key, &value)?;
        if self.config.value(key) == Some(&value) {
            self.staged.remove(key);
        } else {
            self.staged.insert(key.to_owned(), value);
        }
        Ok(())
    }

    /// Interface version 2: the modules' rules that compare keys (two ports that collide), run over the values
    /// that would be in force if `value` were staged for `key`. Only an error on `key` is returned: the
    /// configuration loaded and every earlier edit passed, so any other key at fault is the same collision.
    /// (Swapping two values therefore needs a free value in between.)
    fn check_across_keys(&self, key: &str, value: &Value) -> Result<(), ConfigError> {
        let Some(modules) = self.modules else {
            return Ok(());
        };
        let errors = cross_key_errors(self.config.schema(), modules, |k| {
            if k == key {
                Some((Origin::Edit, value))
            } else if let Some(v) = self.staged.get(k) {
                Some((Origin::Edit, v))
            } else {
                self.config.value(k).map(|v| (Origin::Default, v))
            }
        });
        match errors
            .into_iter()
            .find(|e| matches!(e, ConfigError::ModuleRejected { key: k, .. } if k == key))
        {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// Forget a staged change.
    pub fn unstage(&mut self, key: &str) {
        self.staged.remove(key);
    }

    /// What confirming would do. Changes nothing.
    pub fn review(&self) -> Review {
        let schema = self.config.schema();
        let mut changes = Vec::new();
        let mut restart = Vec::new();
        let mut plan = Plan::default();
        let mut values = Vec::new();
        for def in schema.values() {
            let Some(new) = self.staged.get(&def.key) else {
                continue;
            };
            let old = self.config.value(&def.key);
            changes.push(Change {
                key: def.key.clone(),
                from: old.map(Value::shown),
                to: new.shown(),
            });
            if def.restart {
                restart.push(def.key.clone());
            }
            if let (Some(old), Some(m)) = (
                old,
                def.provider
                    .as_deref()
                    .and_then(|p| self.modules.and_then(|m| m.get(p))),
            ) {
                plan.actions.extend(m.on_change(old, new).actions);
            }
            values.push((def.key.clone(), new.clone()));
        }
        Review {
            changes,
            restart,
            plan,
            values,
        }
    }
}

fn shown(secret: bool, v: &Value) -> String {
    if secret {
        REDACTED.to_owned()
    } else {
        v.shown()
    }
}

/// One staged change, as shown (staged values are never secrets).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Change {
    pub key: String,
    pub from: Option<String>,
    pub to: String,
}

/// What a confirmation would do: shown to the user, who then confirms or not.
#[derive(Debug, Clone)]
pub struct Review {
    changes: Vec<Change>,
    restart: Vec<String>,
    plan: Plan,
    values: Vec<(String, Value)>,
}

impl Review {
    pub fn is_empty(&self) -> bool {
        self.changes.is_empty()
    }

    pub fn changes(&self) -> &[Change] {
        &self.changes
    }

    /// Keys among the changes whose schema entry says changing them needs a restart.
    pub fn restart_needed(&self) -> &[String] {
        &self.restart
    }

    /// The modules' plan, for display. It is executed only from [`Confirmed::plan`].
    pub fn plan(&self) -> &Plan {
        &self.plan
    }

    /// The user said yes.
    pub fn confirm(self) -> Confirmed {
        Confirmed {
            changes: self.changes,
            plan: self.plan,
            values: self.values,
        }
    }
}

/// Changes the user has confirmed. The only source of new file text and of a plan to execute.
#[derive(Debug, Clone)]
pub struct Confirmed {
    changes: Vec<Change>,
    plan: Plan,
    values: Vec<(String, Value)>,
}

/// Why new file text could not be made.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EditError {
    #[error("the file is not valid TOML: {0}")]
    Parse(String),
    #[error("`{0}` cannot be set: part of its path is not a table in the file")]
    NotATable(String),
}

/// Write `text` over `file`, saving `existing` (the file's current text) to `<file>.bak` first when the file
/// exists. A backup that is already there is never overwritten: the call is refused and `file` is untouched. The
/// one save function every front end shares; the error is a sentence for the person.
pub fn save_with_backup(file: &Path, existing: &str, text: &str) -> Result<(), String> {
    if file.exists() {
        let mut bak = file.to_path_buf().into_os_string();
        bak.push(".bak");
        let bak = PathBuf::from(bak);
        if bak.exists() {
            return Err(format!("{} exists; move it away first", bak.display()));
        }
        std::fs::write(&bak, existing)
            .map_err(|e| format!("cannot write {}: {e}", bak.display()))?;
    }
    std::fs::write(file, text).map_err(|e| format!("cannot write {}: {e}", file.display()))
}

impl Confirmed {
    pub fn changes(&self) -> &[Change] {
        &self.changes
    }

    /// The plan to execute (the front end does, with both endpoints in hand).
    pub fn plan(&self) -> &Plan {
        &self.plan
    }

    /// `existing` (a configuration file's text; empty is fine) with the changes applied. Comments and
    /// layout survive; the caller writes the result (keeping a backup is the caller's job).
    pub fn file_text(&self, existing: &str) -> Result<String, EditError> {
        let mut doc: DocumentMut = existing
            .parse()
            .map_err(|e: toml_edit::TomlError| EditError::Parse(e.message().to_owned()))?;
        for (key, value) in &self.values {
            set(doc.as_table_mut(), key, value)?;
        }
        Ok(doc.to_string())
    }
}

fn edit_value(v: &Value) -> EditValue {
    match v {
        Value::String(s) | Value::Enum(s) => EditValue::from(s.as_str()),
        Value::Path(p) => EditValue::from(p.to_string_lossy().as_ref()),
        Value::Int(i) => EditValue::from(*i),
        Value::Float(f) => EditValue::from(*f),
        Value::Bool(b) => EditValue::from(*b),
        Value::List(l) => EditValue::Array(l.iter().map(String::as_str).collect::<Array>()),
        // Never staged (`Session::stage` refuses these keys); kept total rather than a panic.
        Value::Rows(_) | Value::Map(_) => v
            .to_toml()
            .to_string()
            .parse::<EditValue>()
            .unwrap_or_else(|_| EditValue::from("")),
    }
}

fn set(root: &mut Table, key: &str, value: &Value) -> Result<(), EditError> {
    let mut parts: Vec<&str> = key.split('.').collect();
    let leaf = parts.pop().unwrap_or_default();
    let mut table: &mut dyn TableLike = root;
    for part in parts {
        let item = table.entry(part).or_insert_with(|| {
            let mut t = Table::new();
            t.set_implicit(true);
            Item::Table(t)
        });
        table = item
            .as_table_like_mut()
            .ok_or_else(|| EditError::NotATable(key.to_owned()))?;
    }
    let mut new = edit_value(value);
    if let Some(old) = table.get(leaf).and_then(Item::as_value) {
        *new.decor_mut() = old.decor().clone();
    }
    table.insert(leaf, Item::Value(new));
    Ok(())
}