redup-config 0.3.0

Типизированная конфигурация: чтение из YAML и окружения, строгость, проверка и выгрузка с комментариями.
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
//! Чтение YAML в прочитанное дерево: один документ, без тегов, с ключами-скалярами.

use std::rc::Rc;

use yaml_rust2::parser::{Event, Parser};
use yaml_rust2::scanner::{Marker, TScalarStyle};

use crate::mark::Mark;
use crate::names::same_name;
use crate::path::Path;
use crate::problems::{Kind, Problems};
use crate::raw::{Raw, RawKey};

/// Исход чтения файла.
#[derive(Debug, PartialEq)]
pub(crate) enum Parsed {
    /// Дерево документа.
    Tree(Raw),
    /// В файле нет документа: он пуст или состоит из одних комментариев.
    Empty,
    /// Файл не разобрался; ошибка уже записана в проблемы.
    Failed,
}

/// Читает текст файла в дерево. Ошибка разбора записывается в проблемы с именем файла и номером
/// строки.
pub(crate) fn read(text: &str, name: &Rc<str>, problems: &mut Problems) -> Parsed {
    let mut parser = Parser::new_from_str(text).keep_tags(true);
    let mut events: Vec<(Event, Marker)> = Vec::new();
    loop {
        match parser.next_token() {
            Ok((event, marker)) => {
                let ended = event == Event::StreamEnd;
                events.push((event, marker));
                if ended {
                    break;
                }
            }
            Err(error) => {
                let message = format!("invalid YAML: {}", error.info());
                report(problems, name, error.marker().line(), &message);
                return Parsed::Failed;
            }
        }
    }
    match document(Cursor::new(&events), name) {
        Ok(Some(raw)) => Parsed::Tree(raw),
        Ok(None) => Parsed::Empty,
        Err((line, message)) => {
            report(problems, name, line, &message);
            Parsed::Failed
        }
    }
}

/// Записывает ошибку разбора: у неё нет пути — она относится к файлу целиком.
fn report(problems: &mut Problems, name: &Rc<str>, line: usize, message: &str) {
    problems.error(
        Kind::Source,
        &Mark::File(name.clone(), line),
        Path::new(),
        message.to_owned(),
    );
}

/// Ошибка разбора: строка и сообщение.
type Syntax = (usize, String);

/// События документа по очереди; каждое со строкой, где оно начинается.
struct Cursor<'a> {
    events: &'a [(Event, Marker)],
    position: usize,
}

impl<'a> Cursor<'a> {
    fn new(events: &'a [(Event, Marker)]) -> Self {
        Self {
            events,
            position: 0,
        }
    }

    /// Следующее событие, не съедая его.
    fn peek(&self) -> Option<(&Event, usize)> {
        let next = self.events.get(self.position)?;
        Some((&next.0, next.1.line()))
    }

    fn next(&mut self) -> Option<(&Event, usize)> {
        let next = self.events.get(self.position)?;
        self.position += 1;
        Some((&next.0, next.1.line()))
    }
}

/// Документ потока. Второй документ — ошибка.
fn document(mut cursor: Cursor<'_>, name: &Rc<str>) -> Result<Option<Raw>, Syntax> {
    match cursor.next() {
        Some((Event::StreamStart, _)) => {}
        _ => return Err((1, "the stream does not start".to_owned())),
    }
    match cursor.next() {
        Some((Event::StreamEnd, _)) => return Ok(None),
        Some((Event::DocumentStart, _)) => {}
        _ => return Err((1, "the document does not start".to_owned())),
    }
    let mut anchors: Vec<(usize, Raw)> = Vec::new();
    let closed_at = match cursor.peek() {
        Some((Event::DocumentEnd, line)) => Some(line),
        _ => None,
    };
    let raw = match closed_at {
        Some(line) => Raw::null(Mark::File(name.clone(), line)),
        None => node(&mut cursor, &mut anchors, name)?,
    };
    match cursor.next() {
        Some((Event::DocumentEnd, _)) => {}
        Some((_, line)) => return Err((line, "the document is not closed".to_owned())),
        None => return Err((1, "the document is not closed".to_owned())),
    }
    match cursor.next() {
        Some((Event::StreamEnd, _)) => Ok(Some(raw)),
        Some((_, line)) => Err((line, "expected a single document".to_owned())),
        None => Err((1, "the stream is not closed".to_owned())),
    }
}

/// Строит узел и регистрирует его якорь, если он есть.
fn node(
    cursor: &mut Cursor<'_>,
    anchors: &mut Vec<(usize, Raw)>,
    name: &Rc<str>,
) -> Result<Raw, Syntax> {
    // Событие забирается целиком: коллекции читают следующие события через тот же курсор.
    let Some((event, line)) = cursor.next().map(|(event, line)| (event.clone(), line)) else {
        return Err((1, "the document ends too early".to_owned()));
    };
    let mark = || Mark::File(name.clone(), line);
    let (anchor, tag, raw) = match event {
        Event::Scalar(text, style, anchor, tag) => {
            let raw = if is_null(&text, style) {
                Raw::null(mark())
            } else {
                Raw::scalar(text, mark())
            };
            (anchor, tag, raw)
        }
        Event::SequenceStart(anchor, tag) => (anchor, tag, sequence(cursor, anchors, name, mark)?),
        Event::MappingStart(anchor, tag) => (anchor, tag, mapping(cursor, anchors, name, mark)?),
        Event::Alias(id) => {
            return anchors
                .iter()
                .find(|(known, _)| *known == id)
                .map(|(_, raw)| raw.clone())
                .ok_or_else(|| (line, format!("unknown anchor {id}")));
        }
        other => return Err((line, format!("unexpected {}", describe(&other)))),
    };
    if let Some(tag) = tag {
        return Err((
            line,
            format!("tags are not supported: {}{}", tag.handle, tag.suffix),
        ));
    }
    if anchor != 0 {
        anchors.push((anchor, raw.clone()));
    }
    Ok(raw)
}

/// Что стоит следующим в коллекции.
enum Ahead {
    Closed,
    Scalar(String, usize),
    Other(usize),
    End,
}

fn ahead(cursor: &Cursor<'_>) -> Ahead {
    match cursor.peek() {
        None => Ahead::End,
        Some((Event::SequenceEnd | Event::MappingEnd, _)) => Ahead::Closed,
        Some((Event::Scalar(text, _, _, _), line)) => Ahead::Scalar(text.clone(), line),
        Some((_, line)) => Ahead::Other(line),
    }
}

fn sequence(
    cursor: &mut Cursor<'_>,
    anchors: &mut Vec<(usize, Raw)>,
    name: &Rc<str>,
    mark: impl Fn() -> Mark,
) -> Result<Raw, Syntax> {
    let mut items: Vec<Raw> = Vec::new();
    loop {
        match ahead(cursor) {
            Ahead::Closed => {
                cursor.next();
                break;
            }
            Ahead::Scalar(_, _) | Ahead::Other(_) => items.push(node(cursor, anchors, name)?),
            Ahead::End => return Err((1, "the sequence is not closed".to_owned())),
        }
    }
    Ok(if items.is_empty() {
        Raw::empty_sequence(mark())
    } else {
        Raw::sequence(items, mark())
    })
}

fn mapping(
    cursor: &mut Cursor<'_>,
    anchors: &mut Vec<(usize, Raw)>,
    name: &Rc<str>,
    mark: impl Fn() -> Mark,
) -> Result<Raw, Syntax> {
    let mut entries: Vec<(RawKey, Raw)> = Vec::new();
    loop {
        let (text, line) = match ahead(cursor) {
            Ahead::Closed => {
                cursor.next();
                break;
            }
            Ahead::Scalar(text, line) => (text, line),
            Ahead::Other(line) => {
                return Err((line, "a key of a mapping must be a scalar".to_owned()));
            }
            Ahead::End => return Err((1, "the mapping is not closed".to_owned())),
        };
        if let Some((Event::Scalar(_, _, _, Some(tag)), _)) = cursor.next() {
            return Err((
                line,
                format!("tags are not supported: {}{}", tag.handle, tag.suffix),
            ));
        }
        let key = RawKey::new(text, Mark::File(name.clone(), line));
        let value = node(cursor, anchors, name)?;
        if entries
            .iter()
            .any(|(known, _)| same_name(known.text(), key.text()))
        {
            return Err((line, format!("duplicate name {:?}", key.text())));
        }
        entries.push((key, value));
    }
    Ok(if entries.is_empty() {
        Raw::empty_mapping(mark())
    } else {
        Raw::mapping(entries, mark())
    })
}

/// Обычный скаляр `~`, `null` в любом регистре или пустой — это `null`.
fn is_null(text: &str, style: TScalarStyle) -> bool {
    style == TScalarStyle::Plain
        && (text.is_empty() || text == "~" || text.eq_ignore_ascii_case("null"))
}

fn describe(event: &Event) -> &'static str {
    match event {
        Event::StreamStart | Event::StreamEnd => "end of the stream",
        Event::DocumentStart | Event::DocumentEnd => "end of the document",
        Event::SequenceEnd | Event::MappingEnd => "end of a collection",
        Event::Nothing => "nothing",
        _ => "node",
    }
}

#[cfg(test)]
mod tests {
    use super::{Parsed, read};
    use crate::mark::Mark;
    use crate::problems::{Origin, Problems};
    use crate::raw::Raw;

    /// Дерево файла или `None`, если файл не дал дерева.
    fn file(text: &str) -> (Option<Raw>, Problems) {
        let mut problems = Problems::new();
        let raw = match read(text, &"config.yaml".into(), &mut problems) {
            Parsed::Tree(raw) => Some(raw),
            Parsed::Empty | Parsed::Failed => None,
        };
        (raw, problems)
    }

    /// Ключ, текст и признак `null` для каждого значения корня.
    fn entries(raw: &Raw) -> Vec<(String, String, bool)> {
        raw.entries()
            .unwrap_or_default()
            .iter()
            .map(|(key, value)| {
                (
                    key.text().to_owned(),
                    value.text().unwrap_or("").to_owned(),
                    value.is_null(),
                )
            })
            .collect()
    }

    #[test]
    fn section_sequence_and_scalars_keep_their_shape() {
        let (raw, problems) =
            file("host: localhost\nports:\n  - 4200\n  - 443\nempty: {}\nnone: []\n");
        assert!(problems.is_empty(), "{problems}");
        let raw = raw.expect("the document is read");
        assert_eq!(
            entries(&raw),
            [
                ("host".to_owned(), "localhost".to_owned(), false),
                ("ports".to_owned(), String::new(), false),
                ("empty".to_owned(), String::new(), false),
                ("none".to_owned(), String::new(), false),
            ]
        );
        let items = raw
            .entries()
            .and_then(|entries| entries.get(1))
            .and_then(|(_, value)| value.items());
        assert_eq!(items.map(<[Raw]>::len), Some(2));
        let empty = raw
            .entries()
            .and_then(|entries| entries.get(2))
            .map(|(_, value)| value.is_empty());
        assert_eq!(empty, Some(true));
    }

    #[test]
    fn null_has_several_spellings_and_quotes_keep_the_text() {
        let text =
            "a:\nb: ~\nc: null\nd: Null\ne: '~'\nf: \"null\"\ng: ''\nh: |\n  first\n  second\n";
        let (raw, problems) = file(text);
        assert!(problems.is_empty(), "{problems}");
        let raw = raw.expect("the document is read");
        let (texts, nulls): (Vec<String>, Vec<bool>) = entries(&raw)
            .into_iter()
            .map(|(_, text, null)| (text, null))
            .unzip();
        assert_eq!(nulls, [true, true, true, true, false, false, false, false]);
        assert_eq!(
            texts,
            ["", "", "", "", "~", "null", "", "first\nsecond\n"].map(String::from)
        );
    }

    #[test]
    fn empty_file_gives_no_document() {
        let (raw, problems) = file("");
        assert!(raw.is_none());
        assert!(problems.is_empty());
        let (raw, problems) = file("# only a comment\n\n");
        assert!(raw.is_none());
        assert!(problems.is_empty(), "{problems}");
    }

    #[test]
    fn anchors_repeat_a_node_and_tags_are_rejected() {
        let (raw, problems) = file("base: &base\n  host: a\nsame: *base\n");
        assert!(problems.is_empty(), "{problems}");
        let raw = raw.expect("the document is read");
        let read = raw.entries().unwrap_or_default();
        assert_eq!(read.len(), 2);
        assert_eq!(read[0].1, read[1].1);

        let (raw, problems) = file("value: !!str 12\n");
        assert!(raw.is_none());
        assert_eq!(problems.len(), 1);
        assert!(
            problems
                .iter()
                .next()
                .unwrap()
                .message
                .contains("tags are not supported")
        );
    }

    #[test]
    fn duplicates_and_second_document_are_errors_with_lines() {
        let (raw, problems) = file("host: a\nHost: b\n");
        assert!(raw.is_none());
        let problem = problems.iter().next().unwrap();
        assert_eq!(
            problem.origin,
            Origin::File {
                name: "config.yaml".into(),
                line: 2
            }
        );
        assert_eq!(problem.message, "duplicate name \"Host\"");

        let (raw, problems) = file("a: 1\n---\nb: 2\n");
        assert!(raw.is_none());
        assert!(
            problems
                .iter()
                .next()
                .unwrap()
                .message
                .contains("single document")
        );

        let (raw, problems) = file("a: [1, 2\n");
        assert!(raw.is_none());
        assert!(
            problems
                .iter()
                .next()
                .unwrap()
                .message
                .starts_with("invalid YAML")
        );
    }

    #[test]
    fn keys_remember_their_lines() {
        let (raw, _) = file("# комментарий\n\nhost: a\n\nports:\n  - 1\n");
        let raw = raw.expect("the document is read");
        let lines: Vec<usize> = raw
            .entries()
            .unwrap_or_default()
            .iter()
            .map(|(key, _)| match key.mark() {
                Mark::File(_, line) => *line,
                other => unreachable!("ключ не из файла: {other:?}"),
            })
            .collect();
        assert_eq!(lines, [3, 5]);
        assert_ne!(Mark::File("a".into(), 1), Mark::File("a".into(), 2));
    }
}