atypical-config 0.5.0

(Non)standard enforcing DX
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
//! Discovery and loading of `atypical.toml`. Each tool owns its section
//! schema; a top-level `extends` layers other files beneath, see
//! [`resolve`].
//!
//! Schema-free but not key-free: within a named array, `name`, `drop`
//! and `before` are directives consumed before any schema sees them.

use std::path::{Path, PathBuf};

pub use oxc_resolver::ResolveError;
use oxc_resolver::{ResolveOptions, Resolver};
use serde::de::DeserializeOwned;

pub const FILE_NAME: &str = "atypical.toml";

#[derive(Debug)]
pub enum Error {
    Io(std::io::Error),
    Toml(toml::de::Error),
    /// A document names itself, directly or indirectly, in `extends`.
    Cycle(PathBuf),
    /// `extends` is not a string or an array of strings.
    Extends(PathBuf),
    /// An `npm:` specifier that does not resolve to a file.
    Resolve(String, ResolveError),
    /// An `extends` `scheme:` naming an ecosystem with no resolver yet.
    Scheme(String),
    /// A `before` names no entry to sit ahead of, or names its own.
    Before(PathBuf, String),
    /// One array gives the same `name` to two of its entries.
    Duplicate(PathBuf, String),
}

/// An [`Error`] from within a document, before the document is known.
enum Conflict {
    Before(String),
    Duplicate(String),
}

impl Conflict {
    fn at(self, path: &Path) -> Error {
        let path = path.to_path_buf();

        match self {
            Conflict::Before(name) => Error::Before(path, name),
            Conflict::Duplicate(name) => Error::Duplicate(path, name),
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Io(error) => error.fmt(f),
            Error::Toml(error) => error.fmt(f),
            Error::Cycle(path) => {
                write!(f, "cyclic `extends` involving {}", path.display())
            }
            Error::Extends(path) => write!(
                f,
                "`extends` in {} must be a string or an array of strings",
                path.display()
            ),
            Error::Resolve(base, error) => {
                write!(f, "cannot resolve `extends = \"{base}\"`: {error}")
            }
            Error::Scheme(scheme) => {
                write!(f, "`extends` scheme `{scheme}:` is not supported yet")
            }
            Error::Before(path, name) => write!(
                f,
                "`before = \"{name}\"` in {} names no other entry",
                path.display()
            ),
            Error::Duplicate(path, name) => write!(
                f,
                "two entries named \"{name}\" in one array in {}",
                path.display()
            ),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Io(error) => Some(error),
            Error::Toml(error) => Some(error),
            Error::Resolve(_, error) => Some(error),
            Error::Cycle(_)
            | Error::Extends(_)
            | Error::Scheme(_)
            | Error::Before(..)
            | Error::Duplicate(..) => None,
        }
    }
}

/// The nearest [`FILE_NAME`] in `start` or any of its ancestors.
pub fn find(start: impl AsRef<Path>) -> Option<PathBuf> {
    start
        .as_ref()
        .ancestors()
        .map(|dir| dir.join(FILE_NAME))
        .find(|path| path.is_file())
}

/// Deserialize the `[key]` section of a TOML document as written: no
/// `extends`, no directives. A document without the section is
/// `Ok(None)`.
pub fn section<T: DeserializeOwned>(
    document: &str,
    key: &str,
) -> Result<Option<T>, toml::de::Error> {
    let table: toml::Table = document.parse()?;

    let Some(value) = table.get(key) else {
        return Ok(None);
    };

    value.clone().try_into().map(Some)
}

/// Parse the file at `path` into a table, resolving its top-level
/// `extends` key (a string or an array of strings). Extended documents
/// are applied one by one in declaration order, the extending document
/// last: tables merge key-by-key, arrays whose every entry carries a
/// `name` merge by that name, any other value replaces the one beneath
/// it.
///
/// Targets take two forms:
///
/// - A `scheme:spec` prefix names the ecosystem to resolve `spec` in.
///   Only `npm` is wired up, through the shared `node_modules` layout
///   npm, pnpm, yarn and bun populate; every other scheme is the seam a
///   per-ecosystem resolver (`cargo`, `pip`, ...) drops into.
/// - Anything else is a file relative to the extending file, written
///   `./x`, `../x`, an absolute path, or a bare name.
///
/// A named entry matching one beneath it merges into it field by field.
/// An unmatched one keeps its place within its own document: right after
/// the entry it follows there, or at the front when it follows none of
/// them. It appends only when its document keeps nothing beneath it, so
/// peer documents compose. `drop = true` removes
/// the entry it names; `before = "other"` places the entry ahead of the
/// one named, moving it if it was already there. A directive of the
/// wrong type is left in place for the section schema to reject.
///
/// A `before` that names no other entry is an error rather than a
/// silent append or no-op: the position asked for is part of the
/// grammar, so anywhere else is a different grammar. Two entries of
/// one array sharing a `name` is an error for the same reason: the
/// second would merge into the first instead of being an entry of its
/// own.
pub fn resolve(path: impl AsRef<Path>) -> Result<toml::Table, Error> {
    resolve_into(path.as_ref(), &mut Vec::new())
}

fn resolve_into(
    path: &Path,
    stack: &mut Vec<PathBuf>,
) -> Result<toml::Table, Error> {
    let path = path.canonicalize().map_err(Error::Io)?;

    if stack.contains(&path) {
        return Err(Error::Cycle(path));
    }

    let document = std::fs::read_to_string(&path).map_err(Error::Io)?;
    let mut table: toml::Table = document.parse().map_err(Error::Toml)?;

    let bases = match table.remove("extends") {
        None => Vec::new(),
        Some(toml::Value::String(base)) => vec![base],
        Some(toml::Value::Array(bases)) => bases
            .into_iter()
            .map(|base| match base {
                toml::Value::String(base) => Ok(base),
                _ => Err(Error::Extends(path.clone())),
            })
            .collect::<Result<_, _>>()?,
        Some(_) => return Err(Error::Extends(path)),
    };

    let dir = path.parent().unwrap_or(Path::new("")).to_path_buf();

    stack.push(path.clone());

    let mut merged = toml::Table::new();

    for base in bases {
        let base = resolve_into(&locate(&dir, &base)?, stack)?;

        merge(&mut merged, base).map_err(|it| it.at(&path))?;
    }

    stack.pop();
    merge(&mut merged, table).map_err(|it| it.at(&path))?;

    Ok(merged)
}

/// Turn an `extends` target into a file path, in the forms listed on
/// [`resolve`].
fn locate(dir: &Path, base: &str) -> Result<PathBuf, Error> {
    match base.split_once(':') {
        Some((scheme, spec))
            if scheme.len() > 1
                && scheme.chars().all(|c| c.is_ascii_lowercase()) =>
        {
            match scheme {
                "npm" => resolve_package(dir, base, spec),
                _ => Err(Error::Scheme(scheme.to_owned())),
            }
        }
        _ => Ok(dir.join(base)),
    }
}

/// Resolve an npm-style specifier through `node_modules`, naming the
/// whole `label` (scheme included) if it fails.
fn resolve_package(
    dir: &Path,
    label: &str,
    spec: &str,
) -> Result<PathBuf, Error> {
    Resolver::new(ResolveOptions::default())
        .resolve(dir, spec)
        .map(|resolution| resolution.path().to_path_buf())
        .map_err(|error| Error::Resolve(label.to_owned(), error))
}

fn merge(base: &mut toml::Table, layer: toml::Table) -> Result<(), Conflict> {
    for (key, value) in layer {
        match (base.get_mut(&key), value) {
            (Some(base), value) => merge_value(base, value)?,
            (None, value) => {
                base.insert(key, normalised(value)?);
            }
        }
    }

    Ok(())
}

fn merge_value(
    base: &mut toml::Value,
    layer: toml::Value,
) -> Result<(), Conflict> {
    match (base, layer) {
        (toml::Value::Table(base), toml::Value::Table(layer)) => {
            merge(base, layer)
        }
        (toml::Value::Array(base), toml::Value::Array(layer))
            if named(base) && named(&layer) =>
        {
            merge_named(base, layer)
        }
        (base, layer) => {
            *base = normalised(layer)?;

            Ok(())
        }
    }
}

/// What a value looks like with nothing beneath it to merge into: as it
/// was, except that the directives its entries carry are consumed here
/// rather than left to reach a section schema.
fn normalised(layer: toml::Value) -> Result<toml::Value, Conflict> {
    match layer {
        toml::Value::Table(layer) => {
            let mut onto = toml::Table::new();

            merge(&mut onto, layer)?;
            Ok(toml::Value::Table(onto))
        }
        toml::Value::Array(layer) if named(&layer) => {
            let mut onto = Vec::new();

            merge_named(&mut onto, layer)?;
            Ok(toml::Value::Array(onto))
        }
        layer => Ok(layer),
    }
}

fn name_of(entry: &toml::Value) -> Option<&str> {
    match entry {
        toml::Value::Table(fields) => {
            fields.get("name").and_then(toml::Value::as_str)
        }
        _ => None,
    }
}

/// Whether every entry carries a `name` to be matched on, which is what
/// makes an array mergeable entry by entry rather than wholesale.
fn named(array: &[toml::Value]) -> bool {
    !array.is_empty() && array.iter().all(|entry| name_of(entry).is_some())
}

fn position(base: &[toml::Value], name: &str) -> Option<usize> {
    base.iter().position(|entry| name_of(entry) == Some(name))
}

/// Whether this entry says to remove the one it names, consuming the
/// directive so it never reaches a section schema. A `drop` that is not
/// a boolean is left where it is, so the schema reports it rather than
/// it quietly meaning `false`.
fn dropped(entry: &mut toml::Value) -> bool {
    let flag = entry
        .as_table()
        .and_then(|fields| fields.get("drop"))
        .and_then(toml::Value::as_bool);

    if let (Some(flag), Some(fields)) = (flag, entry.as_table_mut()) {
        fields.remove("drop");

        return flag;
    }

    false
}

/// Which entry this one says to sit ahead of, consuming the directive
/// so it never reaches a section schema. Like `drop`, a `before` that
/// is not a string is left where it is for the schema to report.
fn before(entry: &mut toml::Value) -> Option<String> {
    let name = entry
        .as_table()
        .and_then(|fields| fields.get("before"))
        .and_then(toml::Value::as_str)
        .map(str::to_owned)?;

    entry.as_table_mut()?.remove("before");

    Some(name)
}

/// The first name this array gives to two of its entries.
fn duplicate(array: &[toml::Value]) -> Option<&str> {
    array.iter().enumerate().find_map(|(at, entry)| {
        let name = name_of(entry)?;

        array[..at]
            .iter()
            .any(|earlier| name_of(earlier) == Some(name))
            .then_some(name)
    })
}

fn merge_named(
    base: &mut Vec<toml::Value>,
    layer: Vec<toml::Value>,
) -> Result<(), Conflict> {
    if let Some(name) = duplicate(&layer) {
        return Err(Conflict::Duplicate(name.to_owned()));
    }

    // A layer that keeps any entry beneath it is read as a layout around
    // those entries, so what it adds lands where it sits between them.
    let anchored = layer.iter().any(|entry| {
        let kept =
            entry.get("drop").and_then(toml::Value::as_bool) != Some(true);

        kept && name_of(entry)
            .is_some_and(|name| position(base, name).is_some())
    });
    let mut last: Option<String> = None;

    for mut entry in layer {
        let dropped = dropped(&mut entry);
        let before = before(&mut entry);
        let name = name_of(&entry).unwrap_or_default().to_owned();

        let to = match before {
            None => None,
            Some(before) if before == name => {
                return Err(Conflict::Before(before));
            }
            Some(before) => {
                Some(position(base, &before).ok_or(Conflict::Before(before))?)
            }
        };

        match (position(base, &name), dropped) {
            (Some(at), true) => {
                base.remove(at);
            }
            (Some(at), false) => {
                merge_value(&mut base[at], entry)?;

                if let Some(to) = to {
                    let entry = base.remove(at);

                    base.insert(to - usize::from(to > at), entry);
                }

                last = Some(name);
            }
            (None, true) => {}
            (None, false) => {
                let entry = normalised(entry)?;
                let after_last = last
                    .as_deref()
                    .and_then(|last| position(base, last))
                    .map(|at| at + 1);
                let to = match (to, after_last) {
                    (Some(to), _) | (None, Some(to)) => to,
                    (None, None) if anchored => 0,
                    (None, None) => base.len(),
                };

                base.insert(to, entry);
                last = Some(name);
            }
        }
    }

    Ok(())
}

/// Read the file at `path`, [`resolve`] its `extends` chain, and
/// deserialize the `[key]` section of the merged document.
pub fn load<T: DeserializeOwned>(
    path: impl AsRef<Path>,
    key: &str,
) -> Result<Option<T>, Error> {
    let mut table = resolve(path)?;

    let Some(value) = table.remove(key) else {
        return Ok(None);
    };

    value.try_into().map(Some).map_err(Error::Toml)
}

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

    #[derive(Debug, PartialEq, serde::Deserialize)]
    struct Section {
        name: String,
    }

    #[test]
    fn test_section() {
        let document = indoc::indoc! {r#"
            [commit]
            name = "value"
        "#};

        assert_eq!(
            section::<Section>(document, "commit").unwrap(),
            Some(Section {
                name: "value".into()
            })
        );
        assert_eq!(section::<Section>(document, "branch").unwrap(), None);
        assert_eq!(section::<Section>("", "commit").unwrap(), None);

        assert!(section::<Section>("not toml", "commit").is_err());
        assert!(
            section::<Section>(
                indoc::indoc! {r#"
                [commit]
                name = 1
            "#},
                "commit"
            )
            .is_err()
        );
    }
}