knf-core 0.5.0

Load, merge and emit layered JSON and TOML configuration files
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
//! Validated glob predicates and quoted, dotted key-path selectors.

use std::str::FromStr;

/// An invalid glob pattern, with a byte offset into its source.
pub use fast_glob::Error as GlobError;

/// A case-sensitive byte glob, validated once before matching.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GlobPattern(Vec<u8>);

impl FromStr for GlobPattern {
    type Err = GlobError;

    fn from_str(pattern: &str) -> Result<Self, Self::Err> {
        Self::from_bytes(pattern.as_bytes().to_vec())
    }
}

impl GlobPattern {
    fn from_bytes(pattern: Vec<u8>) -> Result<Self, GlobError> {
        fast_glob::validate(&pattern)?;
        Ok(Self(pattern))
    }

    /// Match the entire candidate. `?` matches one byte, not one Unicode character.
    pub fn matches(&self, candidate: impl AsRef<[u8]>) -> bool {
        fast_glob::glob_match(&self.0, candidate)
    }
}

/// Why a quoted key-path glob was rejected.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum KeyGlobError {
    /// No selector was supplied. A quoted empty key (`''`) is valid.
    #[error("empty key-path glob; use '*' to select top-level keys")]
    Empty,
    /// A literal span has no closing single quote.
    #[error("unclosed quote at byte {index}")]
    UnclosedQuote {
        /// Byte offset of the opening quote in the original expression.
        index: usize,
    },
    /// Invalid glob syntax, with the offset mapped to the original expression.
    #[error("{0}")]
    Glob(GlobError),
}

/// A glob selecting full key paths for wholesale replacement.
///
/// Unquoted dots separate keys; single-quoted spans are literal, including
/// wildcard characters. Thus `foo.*` selects children of `foo`, whereas
/// `'foo.bar'` selects a single key containing a dot. Backslash escapes the
/// next byte literally inside quotes; outside quotes it follows fast-glob.
/// Arrays are never traversed and brackets are character classes, not indices.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyGlobPattern(GlobPattern);

// These bytes cannot occur in UTF-8 keys. Encoding literal separators keeps
// the matching grammar independent of std::path::is_separator on Windows.
const LITERAL_SLASH: u8 = 0xff;
const LITERAL_BACKSLASH: u8 = 0xfe;

fn encode(byte: u8) -> u8 {
    match byte {
        b'/' => LITERAL_SLASH,
        b'\\' => LITERAL_BACKSLASH,
        byte => byte,
    }
}

impl KeyGlobPattern {
    /// Match actual key segments, never a dotted diagnostic rendering.
    /// The empty slice denotes the document root and is never selected.
    pub fn matches_keys(&self, keys: &[String]) -> bool {
        if keys.is_empty() {
            return false;
        }
        let mut candidate = Vec::new();
        for (index, key) in keys.iter().enumerate() {
            if index != 0 {
                candidate.push(b'/');
            }
            candidate.extend(key.bytes().map(encode));
        }
        self.0.matches(candidate)
    }
}

struct Normalizer<'a> {
    source: &'a [u8],
    bytes: Vec<u8>,
    offsets: Vec<usize>,
}

impl Normalizer<'_> {
    fn push(&mut self, byte: u8, offset: usize) {
        self.bytes.push(byte);
        self.offsets.push(offset);
    }

    fn literal(&mut self, byte: u8, offset: usize) {
        let byte = encode(byte);
        if matches!(byte, b'*' | b'?' | b'[' | b']' | b'{' | b'}' | b',' | b'!') {
            self.push(b'\\', offset);
        }
        self.push(byte, offset);
    }

    fn glob_error(&self, kind: fast_glob::ErrorKind, index: usize) -> KeyGlobError {
        KeyGlobError::Glob(GlobError { kind, index })
    }

    // Decode exactly fast-glob's escapes outside quoted literal spans.
    fn escaped(&self, index: &mut usize) -> Result<u8, KeyGlobError> {
        let offset = *index;
        let mut byte = self.source[*index];
        if byte == b'\\' {
            *index += 1;
            byte = *self
                .source
                .get(*index)
                .ok_or_else(|| self.glob_error(fast_glob::ErrorKind::TrailingBackslash, offset))?;
            byte = match byte {
                b'b' => 8,
                b'n' => b'\n',
                b'r' => b'\r',
                b't' => b'\t',
                byte => byte,
            };
        }
        *index += 1;
        Ok(byte)
    }

    fn class(&mut self, index: &mut usize) -> Result<(), KeyGlobError> {
        let start = *index;
        *index += 1;
        let negated = matches!(self.source.get(*index), Some(b'!' | b'^'));
        if negated {
            *index += 1;
        }
        let mut members = [false; 256];
        let mut first = true;
        loop {
            let Some(&byte) = self.source.get(*index) else {
                return Err(self.glob_error(fast_glob::ErrorKind::UnclosedBracket, start));
            };
            if byte == b']' && !first {
                *index += 1;
                break;
            }
            let low = self.escaped(index)?;
            let high = if self.source.get(*index) == Some(&b'-')
                && self.source.get(*index + 1).is_some_and(|b| *b != b']')
            {
                *index += 1;
                self.escaped(index)?
            } else {
                low
            };
            if low <= high {
                members[usize::from(low)..=usize::from(high)].fill(true);
            }
            first = false;
        }

        self.push(b'[', start);
        let mut emitted = false;
        // 0xfe and 0xff cannot occur in an original UTF-8 key. Every other
        // original byte maps injectively, including slash and backslash.
        for original in 0..=0xfd_u8 {
            if members[usize::from(original)] != negated {
                let byte = encode(original);
                if matches!(byte, b']' | b'-' | b'^' | b'!' | b'[') {
                    self.push(b'\\', start);
                }
                self.push(byte, start);
                emitted = true;
            }
        }
        if !emitted {
            // A class containing only the internal separator never matches.
            self.push(b'/', start);
        }
        self.push(b']', start);
        Ok(())
    }
}

impl FromStr for KeyGlobPattern {
    type Err = KeyGlobError;

    fn from_str(pattern: &str) -> Result<Self, Self::Err> {
        if pattern.is_empty() {
            return Err(KeyGlobError::Empty);
        }
        let mut norm = Normalizer {
            source: pattern.as_bytes(),
            bytes: Vec::new(),
            offsets: Vec::new(),
        };
        let mut index = 0;
        while index < norm.source.len() {
            let offset = index;
            match norm.source[index] {
                b'\'' => {
                    index += 1;
                    loop {
                        let Some(&byte) = norm.source.get(index) else {
                            return Err(KeyGlobError::UnclosedQuote { index: offset });
                        };
                        if byte == b'\'' {
                            index += 1;
                            break;
                        }
                        let literal_offset = index;
                        if byte == b'\\' {
                            index += 1;
                            if index == norm.source.len() {
                                return Err(norm.glob_error(
                                    fast_glob::ErrorKind::TrailingBackslash,
                                    literal_offset,
                                ));
                            }
                        }
                        norm.literal(norm.source[index], literal_offset);
                        index += 1;
                    }
                }
                b'[' => norm.class(&mut index)?,
                b'\\' => {
                    let byte = norm.escaped(&mut index)?;
                    norm.literal(byte, offset);
                }
                b'.' => {
                    norm.push(b'/', offset);
                    index += 1;
                }
                byte => {
                    norm.push(encode(byte), offset);
                    index += 1;
                }
            }
        }
        GlobPattern::from_bytes(norm.bytes)
            .map(Self)
            .map_err(|mut err| {
                err.index = norm
                    .offsets
                    .get(err.index)
                    .copied()
                    .unwrap_or(pattern.len());
                KeyGlobError::Glob(err)
            })
    }
}

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

    fn matches(pattern: &str, keys: &[&str]) -> bool {
        pattern
            .parse::<KeyGlobPattern>()
            .unwrap()
            .matches_keys(&keys.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>())
    }

    #[test]
    fn selectors_match_full_paths_and_respect_depth() {
        for (pattern, keys, expected) in [
            ("*", vec!["foo"], true),
            ("*", vec!["foo.bar/baz\\qux"], true),
            ("*", vec!["foo", "bar"], false),
            ("foo", vec!["foo"], true),
            ("foo", vec!["parent", "foo"], false),
            ("foo.*", vec!["foo", "bar"], true),
            ("foo.*", vec!["foo", "bar", "baz"], false),
            ("foo.*", vec!["foo"], false),
            ("foo.**", vec!["foo", "bar", "baz"], true),
            ("**.cache", vec!["cache"], true),
            ("**.cache", vec!["foo", "bar", "cache"], true),
            ("**.cache", vec!["foo", "cache", "bar"], false),
            ("{foo,bar}.*", vec!["bar", "baz"], true),
            ("{foo.bar,baz}.*", vec!["foo", "bar", "qux"], true),
            ("{foo,bar}.*", vec!["baz", "qux"], false),
            ("!foo", vec!["foo"], false),
            ("!foo", vec!["bar"], true),
            ("!!foo", vec!["foo"], true),
            ("!foo.*", vec!["foo"], true),
            ("*", vec![], false),
            ("''", vec![""], true),
            ("''", vec![], false),
            ("foo.''", vec!["foo", ""], true),
        ] {
            assert_eq!(matches(pattern, &keys), expected, "{pattern:?}: {keys:?}");
        }
    }

    #[test]
    fn literals_do_not_collide_with_nested_paths_or_glob_syntax() {
        for (pattern, keys, expected) in [
            ("'foo.bar'", vec!["foo.bar"], true),
            ("'foo.bar'", vec!["foo", "bar"], false),
            ("foo.bar", vec!["foo.bar"], false),
            ("'foo.bar'.*", vec!["foo.bar", "pool"], true),
            (r"foo\.bar", vec!["foo.bar"], true),
            ("foo/bar", vec!["foo/bar"], true),
            ("foo/bar", vec!["foo", "bar"], false),
            ("'foo/bar'", vec!["foo/bar"], true),
            (r"'foo\\bar'", vec![r"foo\bar"], true),
            (r"foo\\bar", vec![r"foo\bar"], true),
            (r"'it\'s'", vec!["it's"], true),
            ("'*'", vec!["*"], true),
            ("'*'", vec!["anything"], false),
            ("'!foo'", vec!["!foo"], true),
            ("'!foo'", vec!["foo"], false),
            ("'{a,b}[0]?'", vec!["{a,b}[0]?"], true),
            ("{'foo.bar',baz}.*", vec!["foo.bar", "x"], true),
            ("foo'bar'.*", vec!["foobar", "x"], true),
            ("'ยต'", vec!["ยต"], true),
            ("?", vec!["ยต"], false),
            ("??", vec!["ยต"], true),
            ("?", vec!["/"], true),
            ("?", vec!["\\"], true),
            ("?", vec!["", ""], false),
            (r"\n", vec!["\n"], true),
            (r"'\n'", vec!["n"], true),
        ] {
            assert_eq!(matches(pattern, &keys), expected, "{pattern:?}: {keys:?}");
        }
    }

    #[test]
    fn classes_preserve_original_byte_membership() {
        for pattern in [
            "[a-z]", "[!a-z]", "[^a-z]", "[.]", "[/]", r"[\\]", "[.-0]", r"[Z-\^]", "[]]", "[[]",
            "[-]", "[z-a]", "[!z-a]", "['.]", r"[\n]",
        ] {
            let selector: KeyGlobPattern = pattern.parse().unwrap();
            // A class always selects one byte within a key. Unlike filesystem
            // matching, slash and backslash are ordinary key bytes here.
            for byte in 0..=127_u8 {
                let reference = pattern.as_bytes().to_vec();
                // Compare the original class against a non-separator byte;
                // separators are checked explicitly below instead.
                if matches!(byte, b'/' | b'\\') {
                    continue;
                }
                assert_eq!(
                    selector.matches_keys(&[String::from_utf8(vec![byte]).unwrap()]),
                    fast_glob::glob_match(&reference, [byte]),
                    "{pattern:?} byte {byte}"
                );
            }
        }
        for (pattern, key, expected) in [
            ("[/]", "/", true),
            (r"[\\]", "\\", true),
            ("[.-0]", "/", true),
            ("[!.-0]", "/", false),
            (r"[Z-\^]", "\\", true),
            ("[!a-z]", "/", true),
            ("[.]", ".", true),
            ("[.]", "/", false),
            ("[z-a]", "z", false),
        ] {
            assert_eq!(matches(pattern, &[key]), expected, "{pattern:?}: {key:?}");
        }
        assert!(!matches("[!a-z]", &["", ""]));
    }

    #[test]
    fn errors_name_original_source_offsets() {
        assert_eq!("".parse::<KeyGlobPattern>(), Err(KeyGlobError::Empty));
        assert_eq!(
            "ยต.'unclosed".parse::<KeyGlobPattern>(),
            Err(KeyGlobError::UnclosedQuote { index: 3 })
        );
        for (pattern, kind, index) in [
            (
                "'long literal'.{foo",
                fast_glob::ErrorKind::UnclosedBrace,
                15,
            ),
            ("[!a-z].{foo", fast_glob::ErrorKind::UnclosedBrace, 7),
            ("foo.[bar", fast_glob::ErrorKind::UnclosedBracket, 4),
            ("foo.\\", fast_glob::ErrorKind::TrailingBackslash, 4),
            ("'foo\\", fast_glob::ErrorKind::TrailingBackslash, 4),
        ] {
            let err = pattern.parse::<KeyGlobPattern>().unwrap_err();
            assert_eq!(err, KeyGlobError::Glob(GlobError { kind, index }));
            assert!(!err.to_string().ends_with('\n'));
            assert!(!err.to_string().contains("--shallow"));
        }
    }

    proptest::proptest! {
        #[test]
        fn quoted_keys_round_trip_without_separator_collisions(key in ".*") {
            let quoted = format!("'{}'", key.replace('\\', "\\\\").replace('\'', "\\'"));
            let selector: KeyGlobPattern = quoted.parse().unwrap();
            proptest::prop_assert!(selector.matches_keys(std::slice::from_ref(&key)));
            if key.contains('/') {
                let nested = key.split('/').map(String::from).collect::<Vec<_>>();
                proptest::prop_assert!(!selector.matches_keys(&nested));
            }
        }
    }
}