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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
// 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::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

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};
use crate::module::{Choice, Modules, Needs, Plan};
use crate::typo::suggestion;
use crate::value::{Value, ValueType};

use redactant::PLACEHOLDER as 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 {
    /// Dotted key in the schema.
    pub key: String,
    /// The type the schema gives it.
    pub ty: ValueType,
    /// The schema's description.
    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,
    /// Marked secret in the schema.
    pub secret: bool,
    /// The `<source>:<reference>` a secret declares: a name, never the secret.
    pub source: Option<String>,
    /// Changing it needs a restart.
    pub restart: bool,
    /// A session may stage a new value; false for a secret.
    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 {
    /// Dotted key of the table or map.
    pub key: String,
    /// `table` or `map`.
    pub kind: &'static str,
    /// The schema's description.
    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> {
    /// A session with nothing staged; `modules` supplies provider choices, rules and plans.
    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,
            markers: Markers {
                app: schema.project.config_version,
                mounts: schema
                    .mount_versions()
                    .iter()
                    .map(|m| (m.name.clone(), m.config_version))
                    .collect(),
            },
        }
    }
}

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 {
    /// Dotted key being changed.
    pub key: String,
    /// The value now in force, as shown; `None` if it is unset.
    pub from: Option<String>,
    /// The new value, as shown.
    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)>,
    markers: Markers,
}

/// The format versions this schema writes into a file it creates: the application's and each mounted
/// library's (`docs/SCHEMA-FRAGMENTS.md` item 5).
#[derive(Debug, Clone)]
struct Markers {
    app: u32,
    mounts: Vec<(String, u32)>,
}

impl Review {
    /// True when no value was staged.
    pub fn is_empty(&self) -> bool {
        self.changes.is_empty()
    }

    /// The staged changes, in schema order.
    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,
            markers: self.markers,
        }
    }
}

/// 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)>,
    markers: Markers,
}

/// Why new file text could not be made.
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum EditError {
    /// The text is too large or does not parse; holds the parser's message.
    #[error("the file is not valid TOML: {0}")]
    Parse(String),
    /// Holds the dotted key that could not be written.
    #[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.
///
/// The file is replaced, never rewritten in place: the new text goes to a temporary file beside it, is flushed
/// to disk and renamed over it, so a crash leaves the old text or the new, not a part of either. A symlink stays a
/// link (its target is replaced), the file's permissions are kept on it and on the backup, and a read-only file
/// is refused. The owner becomes the saving user, and other hard links keep the old text.
pub fn save_with_backup(file: &Path, existing: &str, text: &str) -> Result<(), String> {
    let cannot = |p: &Path, e: std::io::Error| format!("cannot write {}: {e}", p.display());
    let (target, keep) = match std::fs::metadata(file) {
        Ok(m) if !m.is_file() => return Err(format!("{} is not a file", file.display())),
        Ok(m) if m.permissions().readonly() => {
            return Err(format!("{} is read-only", file.display()));
        }
        Ok(m) => (
            std::fs::canonicalize(file).map_err(|e| cannot(file, e))?,
            Some(m.permissions()),
        ),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => (file.to_path_buf(), None),
        Err(e) => return Err(cannot(file, e)),
    };
    if let Some(keep) = &keep {
        let mut bak = file.to_path_buf().into_os_string();
        bak.push(".bak");
        let bak = PathBuf::from(bak);
        let exists = || format!("{} exists; move it away first", bak.display());
        write_new(&bak, existing, Some(keep)).map_err(|e| match e.kind() {
            std::io::ErrorKind::AlreadyExists => exists(),
            _ => cannot(&bak, e),
        })?;
    }
    replace(&target, text, keep.as_ref()).map_err(|e| cannot(file, e))
}

/// Create `path` (never over an existing one), with `keep`'s permissions, and flush it. A failed write
/// removes what it created.
fn write_new(path: &Path, text: &str, keep: Option<&std::fs::Permissions>) -> std::io::Result<()> {
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    // Not readable by others, even for the moment before `keep` is applied.
    #[cfg(unix)]
    if keep.is_some() {
        std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
    }
    let mut f = options.open(path)?;
    let written = (|| {
        f.write_all(text.as_bytes())?;
        if let Some(p) = keep {
            f.set_permissions(p.clone())?;
        }
        f.sync_all()
    })();
    if written.is_err() {
        drop(f);
        let _ = std::fs::remove_file(path);
    }
    written
}

fn replace(target: &Path, text: &str, keep: Option<&std::fs::Permissions>) -> std::io::Result<()> {
    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
    let mut name = std::ffi::OsString::from(".");
    name.push(target.file_name().unwrap_or_default());
    name.push(format!(
        ".{}.{}.tmp",
        std::process::id(),
        SEQUENCE.fetch_add(1, Ordering::Relaxed)
    ));
    let temporary = target.with_file_name(name);
    write_new(&temporary, text, keep)?;
    let renamed = std::fs::rename(&temporary, target);
    if renamed.is_err() {
        let _ = std::fs::remove_file(&temporary);
    }
    renamed
}

impl Confirmed {
    /// The confirmed changes, in schema order.
    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).
    ///
    /// The editor owns the format version of what it creates: a file with no content yet gets the
    /// application's `config_version`, and a table for a mounted library that the edit creates gets that
    /// library's. A file that already has content is never stamped, since the editor cannot know which
    /// version an unmarked file is at (`configurant migrate --from N` is how it gets a marker), and a marker
    /// that is already there is never changed.
    pub fn file_text(&self, existing: &str) -> Result<String, EditError> {
        if let Some(reason) = crate::too_large(existing) {
            return Err(EditError::Parse(reason));
        }
        let mut doc: DocumentMut = existing
            .parse()
            .map_err(|e: toml_edit::TomlError| EditError::Parse(e.message().to_owned()))?;
        let new_file = doc.as_table().is_empty();
        let had: Vec<bool> = self
            .markers
            .mounts
            .iter()
            .map(|(name, _)| doc.contains_key(name))
            .collect();
        for (key, value) in &self.values {
            set(doc.as_table_mut(), key, value)?;
        }
        if !self.values.is_empty() {
            if new_file {
                doc["config_version"] = Item::Value(EditValue::from(i64::from(self.markers.app)));
            }
            for ((name, version), had) in self.markers.mounts.iter().zip(had) {
                if had {
                    continue;
                }
                if let Some(table) = doc.get_mut(name).and_then(Item::as_table_like_mut)
                    && !table.contains_key("config_version")
                {
                    table.insert(
                        "config_version",
                        Item::Value(EditValue::from(i64::from(*version))),
                    );
                }
            }
        }
        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(())
}