brink-project-config 0.0.17

Project settings file (brink.toml) for dialect + type policy, shared by every brink compiler mount
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
//! Round-trip-preserving edits to `brink.toml`.
//!
//! The rest of this crate PARSES config into [`ProjectConfig`] with `toml`,
//! which is the right tool for reading: it produces owned Rust values and
//! throws away everything that only matters to a human — comments, blank
//! lines, key order, quote style, indentation.
//!
//! Writing needs the opposite. `brink.toml` is hand-maintained, and several
//! features now edit it programmatically: `drafts` globs, the spellcheck
//! dictionary, project-wide lint suppression, the configurable indent size,
//! and eventually a whole visual editor over the file. A writer that
//! reformats someone's config on every toggle — dropping their comments,
//! reordering their keys — is worse than no writer at all, because the damage
//! is invisible until they open the file.
//!
//! So edits go through `toml_edit`, which keeps the document's formatting and
//! changes only what it is asked to. Everything here is deliberately narrow:
//! a caller names a table, a key, and a value. There is no "serialize a
//! `ProjectConfig` back out", because that would reintroduce exactly the
//! whole-file rewrite this module exists to avoid.

use toml_edit::{Array, DocumentMut, Item, Value};

/// A parsed `brink.toml` that remembers how it was written.
///
/// Construct from the file's text, apply edits, then [`Self::to_string`] the
/// result back to disk. Anything not touched by an edit comes out byte-identical.
#[derive(Debug, Clone)]
pub struct ConfigDocument {
    doc: DocumentMut,
}

/// Why a document could not be parsed for editing.
#[derive(Debug, thiserror::Error)]
pub enum EditError {
    /// The text is not valid TOML.
    #[error("brink.toml is not valid TOML: {0}")]
    Parse(#[from] toml_edit::TomlError),
    /// A path the edit needs is occupied by a value of the wrong shape —
    /// `[project]` present but not a table, say. Reported rather than
    /// overwritten: clobbering a value the author wrote is the one thing a
    /// config writer must never do silently.
    #[error("brink.toml has `{path}` as {found}, expected {expected}")]
    Shape {
        /// Dotted path to the offending item, e.g. `project.drafts`.
        path: String,
        /// What is actually there.
        found: &'static str,
        /// What the edit needed.
        expected: &'static str,
    },
}

impl ConfigDocument {
    /// Parse `text` for editing.
    ///
    /// # Errors
    /// [`EditError::Parse`] when the text is not valid TOML.
    pub fn parse(text: &str) -> Result<Self, EditError> {
        Ok(Self {
            doc: text.parse::<DocumentMut>()?,
        })
    }

    /// An empty document — for creating a `brink.toml` that does not exist yet.
    #[must_use]
    pub fn empty() -> Self {
        Self {
            doc: DocumentMut::new(),
        }
    }

    /// The document's current text, formatting preserved.
    #[must_use]
    pub fn to_toml_string(&self) -> String {
        self.doc.to_string()
    }

    /// Set `table.key` to an integer, creating the table if absent.
    ///
    /// # Errors
    /// [`EditError::Shape`] when `table` exists as something other than a table.
    pub fn set_integer(&mut self, table: &str, key: &str, value: i64) -> Result<(), EditError> {
        let entry = self.table_mut(table)?;
        Self::assign_keeping_decor(entry, key, toml_edit::value(value));
        Ok(())
    }

    /// Set `table.key` to a string, creating the table if absent.
    ///
    /// # Errors
    /// [`EditError::Shape`] when `table` exists as something other than a table.
    pub fn set_string(&mut self, table: &str, key: &str, value: &str) -> Result<(), EditError> {
        let entry = self.table_mut(table)?;
        Self::assign_keeping_decor(entry, key, toml_edit::value(value));
        Ok(())
    }

    /// Read `table.key` as a string array, or an empty vec when absent.
    ///
    /// # Errors
    /// [`EditError::Shape`] when the key exists but is not an array of strings.
    pub fn string_array(&self, table: &str, key: &str) -> Result<Vec<String>, EditError> {
        let Some(item) = self.doc.get(table).and_then(|t| t.get(key)) else {
            return Ok(Vec::new());
        };
        if item.is_none() {
            return Ok(Vec::new());
        }
        let Some(array) = item.as_array() else {
            return Err(EditError::Shape {
                path: format!("{table}.{key}"),
                found: "a non-array",
                expected: "an array of strings",
            });
        };
        array
            .iter()
            .map(|v| {
                v.as_str()
                    .map(str::to_owned)
                    .ok_or_else(|| EditError::Shape {
                        path: format!("{table}.{key}"),
                        found: "an array with a non-string element",
                        expected: "an array of strings",
                    })
            })
            .collect()
    }

    /// Add `value` to the string array at `table.key`, creating both if
    /// absent. A value already present is left alone — and reported, so a
    /// caller can tell "added" from "was already there" without re-reading.
    ///
    /// Returns whether the document changed.
    ///
    /// # Errors
    /// [`EditError::Shape`] when the key exists but is not an array of strings.
    pub fn add_to_string_array(
        &mut self,
        table: &str,
        key: &str,
        value: &str,
    ) -> Result<bool, EditError> {
        if self.string_array(table, key)?.iter().any(|v| v == value) {
            return Ok(false);
        }
        let entry = self.table_mut(table)?;
        if entry.get(key).is_none_or(Item::is_none) {
            entry[key] = Item::Value(Value::Array(Array::new()));
        }
        let item = &mut entry[key];
        let Some(array) = item.as_array_mut() else {
            return Err(EditError::Shape {
                path: format!("{table}.{key}"),
                found: "a non-array",
                expected: "an array of strings",
            });
        };
        array.push(value);
        Ok(true)
    }

    /// Remove `value` from the string array at `table.key`. Returns whether
    /// the document changed.
    ///
    /// # Errors
    /// [`EditError::Shape`] when the key exists but is not an array of strings.
    pub fn remove_from_string_array(
        &mut self,
        table: &str,
        key: &str,
        value: &str,
    ) -> Result<bool, EditError> {
        // A missing key reads back as `Item::None` rather than `None` — the
        // `is_none()` check is what makes "remove from a key that was never
        // there" a no-op instead of a shape error.
        let Some(item) = self.doc.get_mut(table).and_then(|t| t.get_mut(key)) else {
            return Ok(false);
        };
        if item.is_none() {
            return Ok(false);
        }
        let Some(array) = item.as_array_mut() else {
            return Err(EditError::Shape {
                path: format!("{table}.{key}"),
                found: "a non-array",
                expected: "an array of strings",
            });
        };
        let before = array.len();
        array.retain(|v| v.as_str() != Some(value));
        Ok(array.len() != before)
    }

    /// Remove `table.key`, leaving the table (and everything else) alone.
    /// Returns whether the document changed — a key that was never there
    /// is a no-op, not an error, so a form can "unset" without first
    /// reading.
    ///
    /// # Errors
    /// [`EditError::Shape`] when `table` exists as something other than a table.
    pub fn remove_key(&mut self, table: &str, key: &str) -> Result<bool, EditError> {
        let Some(existing) = self.doc.get_mut(table) else {
            return Ok(false);
        };
        let Some(table_like) = existing.as_table_like_mut() else {
            return Err(EditError::Shape {
                path: table.to_owned(),
                found: "a non-table",
                expected: "a table",
            });
        };
        Ok(table_like.remove(key).is_some())
    }

    /// Set `table.key` to a boolean, creating the table if absent.
    ///
    /// # Errors
    /// [`EditError::Shape`] when `table` exists as something other than a table.
    pub fn set_bool(&mut self, table: &str, key: &str, value: bool) -> Result<(), EditError> {
        let entry = self.table_mut(table)?;
        Self::assign_keeping_decor(entry, key, toml_edit::value(value));
        Ok(())
    }

    /// Read `table.key` as a boolean, or `None` when absent or not one.
    #[must_use]
    pub fn bool(&self, table: &str, key: &str) -> Option<bool> {
        self.doc
            .get(table)
            .and_then(|t| t.get(key))
            .and_then(Item::as_bool)
    }

    /// Read `table.key` as an integer, or `None` when absent or not one.
    #[must_use]
    pub fn integer(&self, table: &str, key: &str) -> Option<i64> {
        self.doc
            .get(table)
            .and_then(|t| t.get(key))
            .and_then(Item::as_integer)
    }

    /// The keys of `table`, in the order written; empty when the table is
    /// absent or not a table.
    #[must_use]
    pub fn keys(&self, table: &str) -> Vec<String> {
        self.doc
            .get(table)
            .and_then(Item::as_table_like)
            .map(|t| t.iter().map(|(k, _)| k.to_owned()).collect())
            .unwrap_or_default()
    }

    /// Read `table.key` as a string, or `None` when absent or not a string.
    #[must_use]
    pub fn string(&self, table: &str, key: &str) -> Option<String> {
        self.doc
            .get(table)
            .and_then(|t| t.get(key))
            .and_then(Item::as_str)
            .map(str::to_owned)
    }

    /// Assign `item` to `key`, keeping the existing value's decoration.
    ///
    /// `toml_edit` attaches a trailing comment to the VALUE, so a plain
    /// `entry[key] = ...` silently drops the comment explaining the setting
    /// you just changed — the exact damage this module exists to prevent.
    fn assign_keeping_decor(entry: &mut Item, key: &str, item: Item) {
        let decor = entry
            .get(key)
            .and_then(Item::as_value)
            .map(|v| v.decor().clone());
        entry[key] = item;
        if let (Some(decor), Some(value)) = (decor, entry[key].as_value_mut()) {
            *value.decor_mut() = decor;
        }
    }

    /// The named table, created (as an implicit-free ordinary table) if absent.
    fn table_mut(&mut self, table: &str) -> Result<&mut Item, EditError> {
        if let Some(existing) = self.doc.get(table) {
            if !existing.is_table_like() {
                return Err(EditError::Shape {
                    path: table.to_owned(),
                    found: "a non-table",
                    expected: "a table",
                });
            }
        } else {
            self.doc[table] = Item::Table(toml_edit::Table::new());
        }
        Ok(&mut self.doc[table])
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A hand-written config, with everything a formatter would happily
    /// destroy: comments, a blank line, alignment, single quotes, and a
    /// deliberate key order that is not alphabetical.
    const HAND_WRITTEN: &str = "\
# The story's entry point.
[project]
entry = 'main.ink'   # kept deliberately in single quotes
dialect = \"screenplay\"

# Loud about unreachable content.
[lints]
E063 = \"warn\"
";

    #[test]
    fn an_edit_leaves_every_untouched_byte_alone() {
        // The whole reason this module exists. `toml` would return a
        // reformatted document with the comments gone.
        let mut doc = ConfigDocument::parse(HAND_WRITTEN).expect("valid toml");
        doc.add_to_string_array("project", "drafts", "scratch/*.ink")
            .expect("array edit");
        let out = doc.to_toml_string();

        assert!(
            out.contains("# The story's entry point."),
            "leading comment survives"
        );
        assert!(
            out.contains("# kept deliberately in single quotes"),
            "trailing comment survives"
        );
        assert!(out.contains("entry = 'main.ink'"), "quote style survives");
        assert!(
            out.contains("# Loud about unreachable content."),
            "section comment survives"
        );
        assert!(out.contains("E063 = \"warn\""), "unrelated table survives");
        // And the edit landed.
        assert!(out.contains("scratch/*.ink"));
    }

    #[test]
    fn adding_a_value_already_present_changes_nothing() {
        let mut doc = ConfigDocument::parse("[project]\ndrafts = [\"a.ink\"]\n").expect("valid");
        assert!(
            !doc.add_to_string_array("project", "drafts", "a.ink")
                .expect("edit")
        );
        assert_eq!(doc.to_toml_string(), "[project]\ndrafts = [\"a.ink\"]\n");
    }

    #[test]
    fn arrays_and_tables_are_created_when_absent() {
        let mut doc = ConfigDocument::empty();
        assert!(
            doc.add_to_string_array("project", "drafts", "scratch/*.ink")
                .expect("edit")
        );
        assert_eq!(
            doc.string_array("project", "drafts").expect("read"),
            vec!["scratch/*.ink"]
        );
    }

    #[test]
    fn removing_reports_whether_anything_changed() {
        let mut doc =
            ConfigDocument::parse("[project]\ndrafts = [\"a.ink\", \"b.ink\"]\n").expect("valid");
        assert!(
            doc.remove_from_string_array("project", "drafts", "a.ink")
                .expect("edit")
        );
        assert!(
            !doc.remove_from_string_array("project", "drafts", "a.ink")
                .expect("edit")
        );
        assert_eq!(
            doc.string_array("project", "drafts").expect("read"),
            vec!["b.ink"]
        );
    }

    #[test]
    fn removing_from_an_absent_key_is_a_no_op_not_an_error() {
        let mut doc = ConfigDocument::parse("[project]\n").expect("valid");
        assert!(
            !doc.remove_from_string_array("project", "drafts", "a.ink")
                .expect("edit")
        );
    }

    #[test]
    fn set_integer_and_string_round_trip() {
        let mut doc = ConfigDocument::parse(HAND_WRITTEN).expect("valid");
        doc.set_integer("format", "indent", 2).expect("edit");
        doc.set_string("project", "entry", "other.ink")
            .expect("edit");
        let out = doc.to_toml_string();
        assert!(out.contains("indent = 2"));
        assert!(out.contains("other.ink"));
        // Rewriting one value must not cost the comment attached to it.
        assert!(out.contains("# kept deliberately in single quotes"));
    }

    #[test]
    fn a_wrong_shaped_key_is_reported_not_clobbered() {
        // Overwriting what the author wrote is the one thing this must never
        // do quietly, so a scalar where an array belongs is an error.
        let mut doc = ConfigDocument::parse("[project]\ndrafts = \"oops\"\n").expect("valid");
        let err = doc
            .add_to_string_array("project", "drafts", "a.ink")
            .unwrap_err();
        assert!(matches!(err, EditError::Shape { .. }), "got {err:?}");
        assert_eq!(
            doc.to_toml_string(),
            "[project]\ndrafts = \"oops\"\n",
            "document untouched"
        );
    }

    #[test]
    fn a_non_table_where_a_table_belongs_is_reported() {
        let mut doc = ConfigDocument::parse("project = 3\n").expect("valid");
        let err = doc.set_integer("project", "x", 1).unwrap_err();
        assert!(matches!(err, EditError::Shape { .. }), "got {err:?}");
    }

    #[test]
    fn invalid_toml_fails_to_parse_rather_than_being_repaired() {
        assert!(matches!(
            ConfigDocument::parse("[project"),
            Err(EditError::Parse(_))
        ));
    }

    #[test]
    fn remove_key_takes_one_key_and_nothing_else() {
        let mut doc = ConfigDocument::parse(HAND_WRITTEN).expect("valid toml");
        assert_eq!(
            doc.string("project", "dialect").as_deref(),
            Some("screenplay")
        );
        assert!(doc.remove_key("project", "dialect").expect("a table"));
        let out = doc.to_toml_string();
        assert!(!out.contains("dialect"), "the key is gone: {out}");
        assert!(
            out.contains("entry = 'main.ink'   # kept deliberately in single quotes"),
            "its neighbour is untouched, comment and quotes included: {out}"
        );
        assert!(out.contains("# Loud about unreachable content."));
        assert_eq!(doc.string("project", "dialect"), None);

        assert!(
            !doc.remove_key("project", "dialect").expect("a table"),
            "removing an absent key is a no-op"
        );
        assert!(
            !doc.remove_key("nowhere", "entry")
                .expect("an absent table is fine"),
            "an absent table is a no-op too"
        );
        let mut scalar = ConfigDocument::parse("project = 1\n").expect("valid toml");
        assert!(
            matches!(
                scalar.remove_key("project", "entry"),
                Err(EditError::Shape { .. })
            ),
            "a table that is not a table is reported, never clobbered"
        );
    }

    #[test]
    fn scalar_readers_and_the_key_list_see_what_is_written() {
        let mut doc = ConfigDocument::parse(HAND_WRITTEN).expect("valid toml");
        assert_eq!(
            doc.keys("project"),
            ["entry", "dialect"],
            "in written order"
        );
        assert_eq!(doc.keys("lints"), ["E063"]);
        assert!(doc.keys("nowhere").is_empty());
        assert_eq!(doc.bool("lints", "deny-warnings"), None);
        assert_eq!(doc.integer("project", "indent"), None);
        assert_eq!(doc.bool("project", "entry"), None, "a string is not a bool");

        doc.set_bool("lints", "deny-warnings", true)
            .expect("a table");
        doc.set_integer("project", "indent", 2).expect("a table");
        assert_eq!(doc.bool("lints", "deny-warnings"), Some(true));
        assert_eq!(doc.integer("project", "indent"), Some(2));
        assert_eq!(doc.keys("lints"), ["E063", "deny-warnings"]);
        let out = doc.to_toml_string();
        assert!(out.contains("deny-warnings = true"), "{out}");
        assert!(out.contains("# Loud about unreachable content."));
    }
}