Skip to main content

stratum_node_config/
edit.rs

1//! Change previews: comment-preserving edits, diffs and change lists.
2
3use std::collections::{HashMap, VecDeque};
4use std::fmt;
5
6use serde::ser::{Serialize, SerializeStruct, Serializer};
7use toml_edit::{DocumentMut, Item, Table};
8
9use crate::document::{analyse, parse_toml, ConfigDocument, MAX_DOCUMENT_BYTES};
10use crate::error::{PreviewError, ValidationError};
11use crate::schema::{schema, ApplyClass, FieldDescriptor};
12use crate::value::Value;
13
14/// The text that stands in for a secret-reference value in change lists and
15/// `Debug` output.
16pub const REDACTED: &str = "<redacted>";
17
18/// File name used in both headers of the unified diff.
19const DIFF_FILE_NAME: &str = "stratum.toml";
20
21/// Lines of unchanged context around each hunk of the unified diff.
22const DIFF_CONTEXT_LINES: usize = 3;
23
24/// A requested edit: set the field at `path` to `value`.
25///
26/// Deserialises from `{"path": "...", "value": ...}`, the shape of each entry
27/// in the HTTP `changes` array. The path is checked by [`preview`], not here.
28///
29/// # Serialisation and redaction
30///
31/// `Serialize` writes the same shape back with the value **verbatim**, a
32/// secret reference included, so a request round-trips unchanged. `Debug`
33/// redacts the value of a secret-reference field to [`REDACTED`], so a
34/// change can be logged with `{:?}`. Do not log or persist the serialised
35/// form where secret references must not appear; build a [`FieldChange`]
36/// list through [`preview`] instead, which is redacted. A reference names a
37/// secret held by a custody service and is not the secret itself, but it
38/// still tells a reader where to look, so it stays out of logs by default.
39///
40/// # Examples
41///
42/// ```
43/// use stratum_node_config::Change;
44///
45/// let change = Change::new("limits.max_body_bytes", 65_536);
46/// assert_eq!(change.path(), "limits.max_body_bytes");
47/// ```
48#[derive(Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
49pub struct Change {
50    path: String,
51    value: Value,
52}
53
54impl Change {
55    /// Creates a change.
56    pub fn new(path: impl Into<String>, value: impl Into<Value>) -> Self {
57        Self {
58            path: path.into(),
59            value: value.into(),
60        }
61    }
62
63    /// Returns the dotted path the change targets.
64    pub fn path(&self) -> &str {
65        &self.path
66    }
67
68    /// Returns the requested value.
69    pub fn value(&self) -> &Value {
70        &self.value
71    }
72}
73
74/// Redacts the value when the path names a secret-reference field.
75impl fmt::Debug for Change {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let secret = schema()
78            .field(&self.path)
79            .is_some_and(FieldDescriptor::is_secret_ref);
80        let mut s = f.debug_struct("Change");
81        s.field("path", &self.path);
82        if secret {
83            s.field("value", &REDACTED);
84        } else {
85            s.field("value", &self.value);
86        }
87        s.finish()
88    }
89}
90
91/// One entry of a preview's change list: a field whose effective value the
92/// edit changes.
93///
94/// For secret-reference fields both values are replaced by
95/// `Value::String("<redacted>")` (see [`REDACTED`]) when the entry is built,
96/// so the reference never enters the change list.
97#[derive(Debug, Clone, PartialEq, Eq, Hash)]
98pub struct FieldChange {
99    path: &'static str,
100    apply_class: ApplyClass,
101    old: Option<Value>,
102    new: Value,
103    redacted: bool,
104}
105
106impl FieldChange {
107    fn new(field: &'static FieldDescriptor, old: Option<Value>, new: Value) -> Self {
108        let redacted = field.is_secret_ref();
109        let hide = |v: Value| if redacted { Value::from(REDACTED) } else { v };
110        Self {
111            path: field.path(),
112            apply_class: field.apply_class(),
113            old: old.map(hide),
114            new: hide(new),
115            redacted,
116        }
117    }
118
119    /// Returns the dotted path of the changed field.
120    pub fn path(&self) -> &'static str {
121        self.path
122    }
123
124    /// Returns when this change takes effect.
125    pub fn apply_class(&self) -> ApplyClass {
126        self.apply_class
127    }
128
129    /// Returns the effective value before the edit (the default when the
130    /// base omitted the field), or `None` when the base held a value of a
131    /// type that has no [`Value`] shape, such as a float.
132    pub fn old(&self) -> Option<&Value> {
133        self.old.as_ref()
134    }
135
136    /// Returns the value after the edit.
137    pub fn new_value(&self) -> &Value {
138        &self.new
139    }
140
141    /// Returns `true` if the values were replaced by [`REDACTED`].
142    pub fn is_redacted(&self) -> bool {
143        self.redacted
144    }
145}
146
147impl Serialize for FieldChange {
148    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
149        let mut s = serializer.serialize_struct("FieldChange", 5)?;
150        s.serialize_field("path", self.path)?;
151        s.serialize_field("apply_class", &self.apply_class)?;
152        s.serialize_field("old", &self.old)?;
153        s.serialize_field("new", &self.new)?;
154        s.serialize_field("redacted", &self.redacted)?;
155        s.end()
156    }
157}
158
159/// The result of [`preview`]: what an edit would do, computed without side
160/// effects.
161///
162/// Serialises as `{"text", "diff", "changes", "strictest_apply_class",
163/// "errors", "valid"}`.
164///
165/// # Serialisation and redaction
166///
167/// The serialised `text` and `diff` show secret-reference values exactly as
168/// they appear in the TOML: the diff must be faithful (contract E1.3), and a
169/// diff that hid lines would not be one. The serialised `changes` are
170/// [`FieldChange`]s, redacted when built, and `errors` never contain a
171/// secret-reference value. `Debug` shows only the change list, the strictest
172/// class and the errors, never the text or diff, so `{:?}` is safe to log.
173/// Send the serialised form only to a caller entitled to read the whole
174/// configuration file, such as the administrator previewing an edit.
175#[derive(Clone, PartialEq, Eq)]
176pub struct Preview {
177    text: String,
178    diff: String,
179    changes: Vec<FieldChange>,
180    errors: Vec<ValidationError>,
181    document: Option<ConfigDocument>,
182}
183
184impl Preview {
185    /// Returns the edited TOML text. Outside the edited values it is
186    /// byte-identical to the base, comments and blank lines included, for a
187    /// base that uses one line ending throughout. A base with mixed line
188    /// endings is written with the ending of its first line break; see
189    /// [`preview`].
190    pub fn text(&self) -> &str {
191        &self.text
192    }
193
194    /// Returns a unified diff from the base text to [`Preview::text`], empty
195    /// when nothing changed. Unlike the change list, the diff shows
196    /// secret-reference values as they appear in the TOML.
197    pub fn diff(&self) -> &str {
198        &self.diff
199    }
200
201    /// Returns the changed fields in schema order. Requested changes that
202    /// leave a field's effective value as it was are omitted.
203    pub fn changes(&self) -> &[FieldChange] {
204        &self.changes
205    }
206
207    /// Returns the most disruptive apply class among the changes, or `None`
208    /// when there are none.
209    pub fn strictest_apply_class(&self) -> Option<ApplyClass> {
210        self.changes.iter().map(FieldChange::apply_class).max()
211    }
212
213    /// Returns every validation error in the edited document; empty when it
214    /// is valid.
215    pub fn errors(&self) -> &[ValidationError] {
216        &self.errors
217    }
218
219    /// Returns `true` if the edited document passed validation.
220    pub fn is_valid(&self) -> bool {
221        self.document.is_some()
222    }
223
224    /// Returns the edited document when it is valid.
225    pub fn document(&self) -> Option<&ConfigDocument> {
226        self.document.as_ref()
227    }
228
229    /// Consumes the preview and returns the edited document when it is valid.
230    pub fn into_document(self) -> Option<ConfigDocument> {
231        self.document
232    }
233}
234
235/// Shows the change list and errors; the text and diff are elided because
236/// they may contain secret references.
237impl fmt::Debug for Preview {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        f.debug_struct("Preview")
240            .field("changes", &self.changes)
241            .field("strictest_apply_class", &self.strictest_apply_class())
242            .field("errors", &self.errors)
243            .finish_non_exhaustive()
244    }
245}
246
247impl Serialize for Preview {
248    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
249        let mut s = serializer.serialize_struct("Preview", 6)?;
250        s.serialize_field("text", &self.text)?;
251        s.serialize_field("diff", &self.diff)?;
252        s.serialize_field("changes", &self.changes)?;
253        s.serialize_field("strictest_apply_class", &self.strictest_apply_class())?;
254        s.serialize_field("errors", &self.errors)?;
255        s.serialize_field("valid", &self.is_valid())?;
256        s.end()
257    }
258}
259
260/// Computes what applying `changes` to `base_text` would produce.
261///
262/// The function is pure: it reads only its arguments and returns the same
263/// bytes for the same input. Changes are applied in schema order, whatever
264/// order they are given in. Each edit replaces only the value: comments,
265/// blank lines, key order and the decoration around the value (including a
266/// trailing comment on the same line) are kept. A field absent from the
267/// base is appended to its table, and a missing table is appended to the
268/// document. A change that leaves the field's effective value unchanged
269/// (counting defaults) is dropped and does not touch the text.
270///
271/// # Line endings
272///
273/// The edited text uses the base's line ending: CRLF when the first line
274/// break of `base_text` is CRLF, LF otherwise (including a base with no line
275/// break). Every line of the edited text, inserted or kept, ends that way, so
276/// a CRLF document stays entirely CRLF and its diff shows only the lines an
277/// edit changed. A base that mixes endings is the one case where unedited
278/// lines can change: they are rewritten with the ending of its first line
279/// break. When no change takes effect the base is returned verbatim, mixed
280/// endings included.
281///
282/// The base need not be valid, only parseable, so a preview can repair an
283/// invalid document. A change value of the wrong type for its field is
284/// written as given and then reported in [`Preview::errors`].
285///
286/// # Editing a list
287///
288/// A list is edited element by element, so the comments inside it stay with
289/// what they describe:
290///
291/// - **Ownership.** An element owns the comment lines directly above it
292///   (everything between the previous element's line and itself) and the
293///   comment ending its own line; when several elements share a line, that
294///   comment belongs to the last of them. The list itself owns a comment on
295///   the `[` line, the comment lines before the closing `]`, and everything
296///   outside the brackets. In an empty list every comment is the list's.
297/// - **Matching.** Old and new elements are matched by value, each new
298///   element taking the first old element with the same text that is not yet
299///   taken. Reordering therefore moves an element together with its
300///   comments, and of two equal elements the earlier keeps its comments.
301/// - **Survivors** keep their comments exactly once. A **removed** element's
302///   comments are removed with it; replacing an element is removing one and
303///   adding another. **New** elements own no comment and take the
304///   surrounding style: in a multiline list a line of their own at the
305///   existing indentation, in a single-line list the spacing of their
306///   position.
307/// - **The list's own comments** are always kept exactly once, including
308///   when the list is cleared or filled from empty. A comment line is never
309///   joined to another element's line: one that began a line still does.
310/// - An **unchanged** list is left byte-identical.
311/// - The trailing comma is kept; filling an empty multiline list adds one,
312///   and clearing a list removes it and writes `[]` when only whitespace
313///   would remain between the brackets.
314///
315/// # Errors
316///
317/// Returns [`PreviewError::TooLarge`] if `base_text`, or the text the
318/// changes produce, is longer than [`MAX_DOCUMENT_BYTES`] (checked before
319/// parsing the base and before diffing the result),
320/// [`PreviewError::Syntax`] if `base_text` is not valid TOML,
321/// [`PreviewError::UnknownPath`] if a change names a path not in the schema,
322/// [`PreviewError::DuplicatePath`] if two changes name the same path, and
323/// [`PreviewError::NotEditable`] if the base holds a non-table where the
324/// field's table belongs, or a table where the field's value belongs.
325///
326/// # Examples
327///
328/// ```
329/// use stratum_node_config::{preview, ApplyClass, Change, Value};
330///
331/// let base = "schema_version = 1\n\n[limits]\n# Per-request cap.\nmax_body_bytes = 262144\n";
332/// let p = preview(base, &[
333///     Change::new("limits.max_body_bytes", 65_536),
334///     Change::new("node.name", "alpha"),
335/// ])?;
336/// assert!(p.is_valid());
337/// assert!(p.text().contains("# Per-request cap.\nmax_body_bytes = 65536\n"));
338/// assert_eq!(p.changes()[0].path(), "node.name"); // schema order
339/// assert_eq!(p.changes()[1].old(), Some(&Value::Integer(262_144)));
340/// assert_eq!(p.strictest_apply_class(), Some(ApplyClass::Restart));
341/// assert!(p.diff().contains("-max_body_bytes = 262144\n+max_body_bytes = 65536\n"));
342/// # Ok::<(), Box<dyn std::error::Error>>(())
343/// ```
344pub fn preview(base_text: &str, changes: &[Change]) -> Result<Preview, PreviewError> {
345    let mut resolved: Vec<(usize, &'static FieldDescriptor, &Value)> =
346        Vec::with_capacity(changes.len());
347    for change in changes {
348        let Some(index) = schema().index_of(&change.path) else {
349            return Err(PreviewError::UnknownPath {
350                path: change.path.clone(),
351            });
352        };
353        if resolved.iter().any(|(i, _, _)| *i == index) {
354            return Err(PreviewError::DuplicatePath {
355                path: change.path.clone(),
356            });
357        }
358        resolved.push((index, &schema().table()[index], &change.value));
359    }
360    resolved.sort_by_key(|(i, _, _)| *i);
361
362    let too_large = PreviewError::TooLarge {
363        limit: MAX_DOCUMENT_BYTES,
364    };
365    if base_text.len() > MAX_DOCUMENT_BYTES {
366        return Err(too_large);
367    }
368    let mut doc = parse_toml(base_text).map_err(PreviewError::Syntax)?;
369    let base = analyse(&doc);
370
371    let mut list = Vec::new();
372    for (index, field, value) in resolved {
373        let old = base.values.get(index).cloned().flatten();
374        if old.as_ref() == Some(value) {
375            continue;
376        }
377        set_value(&mut doc, field, value)?;
378        list.push(FieldChange::new(field, old, value.clone()));
379    }
380
381    let text = if list.is_empty() {
382        base_text.to_owned()
383    } else {
384        LineEnding::of(base_text).apply(doc.to_string())
385    };
386    if text.len() > MAX_DOCUMENT_BYTES {
387        return Err(too_large);
388    }
389    let diff = unified_diff(base_text, &text);
390    let (errors, document) = match parse_toml(&text) {
391        Err(e) => (vec![e], None),
392        Ok(edited) => match ConfigDocument::from_toml(text.clone(), &edited) {
393            Ok(document) => (Vec::new(), Some(document)),
394            Err(errors) => (errors.into_vec(), None),
395        },
396    };
397    Ok(Preview {
398        text,
399        diff,
400        changes: list,
401        errors,
402        document,
403    })
404}
405
406/// The line break an edited document is written with.
407#[derive(Debug, Clone, Copy, PartialEq, Eq)]
408enum LineEnding {
409    Lf,
410    CrLf,
411}
412
413impl LineEnding {
414    /// The ending of the first line break in `text`, or LF when it has none.
415    fn of(text: &str) -> Self {
416        match text.find('\n') {
417            Some(i) if text[..i].ends_with('\r') => Self::CrLf,
418            _ => Self::Lf,
419        }
420    }
421
422    /// Rewrites every line break of `text` with this ending.
423    ///
424    /// `toml_edit` writes LF after every key, table header and decoration it
425    /// emits, whatever the source used, so its output is LF apart from any
426    /// CRLF kept inside the raw text of a multi-line string. Both kinds are
427    /// first folded to LF and then expanded. A carriage return can only
428    /// appear in valid TOML as part of a CRLF line break, so nothing else is
429    /// touched; and no string field of the schema accepts a line break inside
430    /// its value, so the conversion cannot change a valid document's values.
431    fn apply(self, text: String) -> String {
432        let lf = if text.contains('\r') {
433            text.replace("\r\n", "\n")
434        } else {
435            text
436        };
437        match self {
438            Self::Lf => lf,
439            Self::CrLf => lf.replace('\n', "\r\n"),
440        }
441    }
442}
443
444/// Writes `value` into the document, keeping the old value's decoration.
445fn set_value(
446    doc: &mut DocumentMut,
447    field: &'static FieldDescriptor,
448    value: &Value,
449) -> Result<(), PreviewError> {
450    let section = field.section();
451    if doc.get(section).is_none() {
452        doc.insert(section, Item::Table(Table::new()));
453    }
454    let table = doc
455        .get_mut(section)
456        .and_then(Item::as_table_like_mut)
457        .ok_or_else(|| PreviewError::NotEditable {
458            path: section.to_owned(),
459        })?;
460    let mut new = value.to_toml();
461    match table.get_mut(field.key()) {
462        None => {
463            table.insert(field.key(), Item::Value(new));
464        }
465        Some(item) => {
466            let old = item
467                .as_value_mut()
468                .ok_or_else(|| PreviewError::NotEditable {
469                    path: field.path().to_owned(),
470                })?;
471            match (old, value) {
472                (toml_edit::Value::Array(array), Value::StringList(list)) => {
473                    edit_array(array, list);
474                }
475                (old, _) => {
476                    *new.decor_mut() = old.decor().clone();
477                    *old = new;
478                }
479            }
480        }
481    }
482    Ok(())
483}
484
485/// Rewrites `array` in place to hold `list`, keeping its comments.
486///
487/// The ownership model, which [`preview`] documents for callers:
488///
489/// - **Elements.** An element owns its *head*, every line between the end of
490///   the previous element's line (or the `[` line) and itself, which holds
491///   the comment lines written above it and its indentation; the text between
492///   its value and its comma; and its *tail*, the rest of its own line after
493///   the comma, which holds a comment on that line. When elements share a
494///   line, the comment ending it belongs to the last of them.
495/// - **The array.** The array owns the rest of the `[` line (a comment on
496///   it), everything after the last element's line up to `]` (comments
497///   before the closing bracket), and its decoration outside the brackets.
498///   In an empty array, the first line inside the brackets is the `[` line
499///   and the rest is the closing part.
500/// - **Matching.** Old and new elements are matched by value: each new
501///   element takes the first unmatched old element with the same string, so
502///   a reordered element moves with everything it owns. Unmatched old
503///   elements are removed with everything they own; unmatched new elements
504///   own nothing.
505/// - **Layout.** A head or closing part that began a line still begins one:
506///   a newline is inserted before it when the text before it no longer ends
507///   a line, so a comment is never joined to another element's line. In a
508///   multiline array a new element starts a line at the existing
509///   indentation and the line ends after it; in a single-line array it
510///   takes the spacing of its position. Whitespace that separates elements
511///   on one line belongs to the position, not the element, so an unchanged
512///   list is rebuilt byte for byte.
513/// - **Commas.** The trailing comma is kept as it was. Filling an empty
514///   multiline array adds one; clearing an array removes it, and clearing
515///   collapses the brackets to `[]` when nothing but whitespace is left.
516fn edit_array(array: &mut toml_edit::Array, list: &[String]) {
517    let layout = ArrayLayout::parse(array);
518    let rendered = layout.render(list);
519    let decor = array.decor().clone();
520    *array = rendered;
521    *array.decor_mut() = decor;
522}
523
524/// A run of text that precedes an element's value or the closing `]`.
525#[derive(Debug, Clone, PartialEq, Eq)]
526struct Lead {
527    text: String,
528    /// The text began a line in the old array.
529    starts_line: bool,
530}
531
532/// An old element and the text it owns.
533#[derive(Debug, Clone)]
534struct Element {
535    value: toml_edit::Value,
536    head: Lead,
537    before_comma: String,
538    tail: String,
539}
540
541/// An array split into the text each element and the array itself own.
542#[derive(Debug, Clone)]
543struct ArrayLayout {
544    opening: String,
545    elements: Vec<Element>,
546    closing: Lead,
547    trailing_comma: bool,
548    multiline: bool,
549}
550
551impl ArrayLayout {
552    fn parse(array: &toml_edit::Array) -> Self {
553        let values: Vec<&toml_edit::Value> = array.iter().collect();
554        let n = values.len();
555        let trailing_comma = n > 0 && array.trailing_comma();
556        let mut opening = String::new();
557        let mut elements: Vec<Element> = Vec::with_capacity(n);
558        for (i, v) in values.iter().enumerate() {
559            let (line_end, rest) = split_first_line(raw(v.decor().prefix()));
560            match elements.last_mut() {
561                Some(previous) => line_end.clone_into(&mut previous.tail),
562                None => line_end.clone_into(&mut opening),
563            }
564            let before_comma = if i + 1 < n || trailing_comma {
565                raw(v.decor().suffix()).to_owned()
566            } else {
567                String::new()
568            };
569            let mut value = (*v).clone();
570            value.decor_mut().clear();
571            elements.push(Element {
572                value,
573                head: Lead {
574                    text: rest.to_owned(),
575                    starts_line: !line_end.is_empty(),
576                },
577                before_comma,
578                tail: String::new(),
579            });
580        }
581        // The text after the last element's comma, or, without a trailing
582        // comma, after its value (stored as its suffix).
583        let last_gap = match values.last() {
584            Some(last) if !trailing_comma => raw(last.decor().suffix()),
585            _ => raw(Some(array.trailing())),
586        };
587        let (line_end, rest) = split_first_line(last_gap);
588        match elements.last_mut() {
589            Some(last) => line_end.clone_into(&mut last.tail),
590            None => line_end.clone_into(&mut opening),
591        }
592        let closing = Lead {
593            text: rest.to_owned(),
594            starts_line: !line_end.is_empty(),
595        };
596        let multiline = opening.contains('\n')
597            || closing.text.contains('\n')
598            || elements.iter().any(|e| {
599                e.head.text.contains('\n') || e.before_comma.contains('\n') || e.tail.contains('\n')
600            });
601        Self {
602            opening,
603            elements,
604            closing,
605            trailing_comma,
606            multiline,
607        }
608    }
609
610    /// Builds the array for `list` (without the decoration outside the
611    /// brackets, which the caller keeps).
612    fn render(&self, list: &[String]) -> toml_edit::Array {
613        let mut unmatched: HashMap<&str, VecDeque<&Element>> = HashMap::new();
614        for e in &self.elements {
615            if let Some(s) = e.value.as_str() {
616                unmatched.entry(s).or_default().push_back(e);
617            }
618        }
619        let indent = self.indent();
620        let mut out = toml_edit::Array::new();
621        let mut pending = self.opening.clone();
622        let mut last_before_comma = String::new();
623        for (position, s) in list.iter().enumerate() {
624            let survivor = unmatched.get_mut(s.as_str()).and_then(VecDeque::pop_front);
625            let (mut value, head, before_comma, tail) = if let Some(e) = survivor {
626                (
627                    e.value.clone(),
628                    e.head.clone(),
629                    e.before_comma.as_str(),
630                    e.tail.as_str(),
631                )
632            } else {
633                let head = Lead {
634                    text: if self.multiline {
635                        indent.clone()
636                    } else {
637                        String::new()
638                    },
639                    starts_line: self.multiline,
640                };
641                let tail = if self.multiline { "\n" } else { "" };
642                (toml_edit::Value::from(s.as_str()), head, "", tail)
643            };
644            self.place_head(&mut pending, &head, position, &indent);
645            value.decor_mut().set_prefix(std::mem::take(&mut pending));
646            value.decor_mut().set_suffix(before_comma);
647            out.push_formatted(value);
648            before_comma.clone_into(&mut last_before_comma);
649            tail.clone_into(&mut pending);
650        }
651
652        place_after_line_break(&mut pending, &self.closing);
653        if list.is_empty() {
654            if !self.elements.is_empty() && is_blank(&pending) {
655                pending.clear();
656            }
657            out.set_trailing(pending);
658            out.set_trailing_comma(false);
659            return out;
660        }
661        let trailing_comma = if self.elements.is_empty() {
662            self.multiline
663        } else {
664            self.trailing_comma
665        };
666        if trailing_comma {
667            out.set_trailing(pending);
668        } else if let Some(last) = out.iter_mut().last() {
669            last.decor_mut()
670                .set_suffix(format!("{last_before_comma}{pending}"));
671        }
672        out.set_trailing_comma(trailing_comma);
673        out
674    }
675
676    /// Appends an element's head to `pending`, the text since the previous
677    /// comma (or the `[`), applying the layout rules.
678    fn place_head(&self, pending: &mut String, head: &Lead, position: usize, indent: &str) {
679        let spacing_only = !head.text.contains('\n') && is_blank(&head.text);
680        if !spacing_only {
681            place_after_line_break(pending, head);
682        } else if pending.ends_with('\n') {
683            pending.push_str(if head.starts_line { &head.text } else { indent });
684        } else if head.starts_line {
685            pending.push('\n');
686            pending.push_str(&head.text);
687        } else {
688            pending.push_str(self.spacing(position));
689        }
690    }
691
692    /// The whitespace before the value at `position` on a shared line: the
693    /// old array's spacing at that position, else the spacing of its last
694    /// position after the first, else none for the first and one space for
695    /// the rest.
696    fn spacing(&self, position: usize) -> &str {
697        fn same_line(e: &Element) -> Option<&str> {
698            (!e.head.starts_line).then_some(e.head.text.as_str())
699        }
700        if let Some(s) = self.elements.get(position).and_then(same_line) {
701            return s;
702        }
703        if position == 0 {
704            return "";
705        }
706        self.elements
707            .iter()
708            .skip(1)
709            .rev()
710            .find_map(same_line)
711            .unwrap_or(" ")
712    }
713
714    /// The indentation for a new element in a multiline array: that of the
715    /// first old element that begins a line, else that of a comment before
716    /// `]`, else four spaces.
717    fn indent(&self) -> String {
718        let after_newline = |s: &str| s.rfind('\n').map_or(s, |i| &s[i + 1..]).to_owned();
719        if let Some(e) = self.elements.iter().find(|e| e.head.starts_line) {
720            return after_newline(&e.head.text);
721        }
722        let first_line = self.closing.text.split('\n').next().unwrap_or_default();
723        if self.closing.starts_line && !is_blank(first_line) {
724            return first_line
725                .chars()
726                .take_while(|c| *c == ' ' || *c == '\t')
727                .collect();
728        }
729        "    ".to_owned()
730    }
731}
732
733/// Appends `lead` to `pending`, first ending the current line if `lead`
734/// began a line in the old array and `pending` does not end one now.
735fn place_after_line_break(pending: &mut String, lead: &Lead) {
736    if lead.starts_line && !pending.ends_with('\n') {
737        pending.push('\n');
738    }
739    pending.push_str(&lead.text);
740}
741
742/// Splits `s` after its first newline: the end of the current line
743/// (including the newline) and the rest. Without a newline the whole of `s`
744/// is the rest.
745fn split_first_line(s: &str) -> (&str, &str) {
746    match s.find('\n') {
747        Some(i) => s.split_at(i + 1),
748        None => ("", s),
749    }
750}
751
752/// The text of a parsed decoration, or `""` when it is unset.
753fn raw(s: Option<&toml_edit::RawString>) -> &str {
754    s.and_then(toml_edit::RawString::as_str).unwrap_or_default()
755}
756
757fn is_blank(s: &str) -> bool {
758    s.chars().all(char::is_whitespace)
759}
760
761fn unified_diff(old: &str, new: &str) -> String {
762    if old == new {
763        return String::new();
764    }
765    similar::TextDiff::from_lines(old, new)
766        .unified_diff()
767        .context_radius(DIFF_CONTEXT_LINES)
768        .header(DIFF_FILE_NAME, DIFF_FILE_NAME)
769        .to_string()
770}
771
772#[cfg(test)]
773mod tests {
774    use proptest::prelude::*;
775
776    use super::*;
777
778    /// Parses `a = <array>` and returns the document.
779    fn doc_of(array: &str) -> DocumentMut {
780        format!("a = {array}\n").parse().expect("test input parses")
781    }
782
783    fn array_mut(doc: &mut DocumentMut) -> &mut toml_edit::Array {
784        doc["a"]
785            .as_value_mut()
786            .and_then(toml_edit::Value::as_array_mut)
787            .expect("an array")
788    }
789
790    fn strings(doc: &DocumentMut) -> Vec<String> {
791        doc["a"]
792            .as_array()
793            .expect("an array")
794            .iter()
795            .map(|v| v.as_str().expect("a string").to_owned())
796            .collect()
797    }
798
799    /// Edits the array in `a = <array>` to `list` and returns the text.
800    fn edited(array: &str, list: &[String]) -> String {
801        let mut doc = doc_of(array);
802        edit_array(array_mut(&mut doc), list);
803        doc.to_string()
804    }
805
806    #[test]
807    fn unchanged_list_is_rebuilt_byte_for_byte() {
808        for array in [
809            "[ \"A\",\t\"B\" ]",
810            "[]",
811            "[ ]",
812            "[\n]",
813            "[ # opening\n # closing\n]",
814            "[\"A\", \"B\",\n# C head\n\"C\",\n]",
815            "[\n    # head\n    \"A\" , # tail\n\n    \"B\"\n    # closing\n] # outer",
816            "[\"A\" # before the comma\n, \"B\"]",
817        ] {
818            let doc = doc_of(array);
819            let list = strings(&doc);
820            assert_eq!(edited(array, &list), doc.to_string(), "{array:?}");
821        }
822    }
823
824    /// Gaps that can stand between tokens of an array, comments and blank
825    /// lines included.
826    fn gap() -> impl Strategy<Value = String> {
827        prop_oneof![
828            Just(String::new()),
829            Just(" ".to_owned()),
830            Just("\t".to_owned()),
831            Just("\n".to_owned()),
832            Just("\n\n  ".to_owned()),
833            (0u8..100).prop_map(|n| format!(" # c{n}\n")),
834            (0u8..100).prop_map(|n| format!("\n  # c{n}\n  ")),
835        ]
836    }
837
838    /// Arbitrary layouts: a gap before each value, between each value and its
839    /// comma, and before `]`, with an optional trailing comma.
840    fn any_array() -> impl Strategy<Value = String> {
841        (
842            proptest::collection::vec(((0u8..4), gap(), gap()), 0..6),
843            any::<bool>(),
844            gap(),
845        )
846            .prop_map(|(items, trailing_comma, closing)| {
847                let mut out = String::from("[");
848                let n = items.len();
849                for (i, (v, before, after)) in items.iter().enumerate() {
850                    out.push_str(before);
851                    out.push_str(&toml_edit::Value::from(format!("v{v}")).to_string());
852                    out.push_str(after);
853                    if i + 1 < n || trailing_comma {
854                        out.push(',');
855                    }
856                }
857                out.push_str(&closing);
858                out.push(']');
859                out
860            })
861    }
862
863    proptest! {
864        #![proptest_config(ProptestConfig::with_cases(4096))]
865
866        #[test]
867        fn any_layout_rebuilds_unchanged_and_edits_to_valid_toml(
868            array in any_array(),
869            list in proptest::collection::vec((0u8..5).prop_map(|v| format!("v{v}")), 0..7),
870        ) {
871            let doc = doc_of(&array);
872            let same = strings(&doc);
873            prop_assert_eq!(edited(&array, &same), doc.to_string(), "identity");
874
875            let text = edited(&array, &list);
876            let reparsed: DocumentMut = text
877                .parse()
878                .map_err(|e| TestCaseError::fail(format!("{e}: {text:?}")))?;
879            prop_assert_eq!(strings(&reparsed), list, "values of {:?}", text);
880        }
881    }
882}