yamled 0.0.1

Format-preserving YAML edits: change what you meant, keep every other byte
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
use std::fmt;
use std::ops::Range;

use crate::index::{Index, Location, Style};
use crate::text::{
    LF, NEWLINE, column, dedent, has_blank_line, indent, join, line_end, line_start, starts_line,
    terminated,
};
use crate::{Error, Path};

#[cfg(feature = "serde")]
mod values;

#[cfg(feature = "serde")]
pub use values::Position;

/// Whether a new sequence item is set off from its neighbours by a blank line,
/// for a sequence whose own items do not settle it. A sequence whose
/// neighbours are all separated, or all adjacent, keeps its spacing whatever
/// this says; one with fewer than two items, or with both kinds of gap, gets
/// this spacing. Set it with [`Document::with_spacing`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Spacing {
    /// Items follow each other directly.
    #[default]
    Tight,
    /// One blank line between items.
    Blank,
}

/// A sequence item taken out of a document by [`Document::take`], with the
/// comments it owns, ready for [`Document::put`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Fragment {
    text: String,
}

impl Fragment {
    /// The item as text, its dash at column 0.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.text
    }
}

/// A splice that removes a sequence item, and the item's own text.
struct Cut {
    from: usize,
    to: usize,
    with: String,
    text: String,
}

/// A read-only view of one node.
#[derive(Clone, Copy, Debug)]
pub struct Node<'a> {
    document: &'a Document,
    id: usize,
}

impl Node<'_> {
    /// Where the value is written.
    #[must_use]
    pub fn value(&self) -> Location {
        let node = &self.document.index.nodes[self.id];
        Location::of(&self.document.source, node.value.clone())
    }

    /// Where the key is written, for a mapping value.
    #[must_use]
    pub fn key(&self) -> Option<Location> {
        let node = &self.document.index.nodes[self.id];
        let key = node.key.as_ref()?;
        Some(Location::of(&self.document.source, key.range.clone()))
    }

    /// The lines this node owns: its comments above, its entry, and its value.
    #[must_use]
    pub fn owned(&self) -> Location {
        let source = &self.document.source;
        let index = &self.document.index;
        let start = index.owned_start(source, self.id);
        let end = line_end(source, index.nodes[self.id].value.end);
        Location::of(source, start..end)
    }

    /// How the value is written.
    #[must_use]
    pub fn style(&self) -> Style {
        self.document.index.nodes[self.id].style
    }

    /// How many items or entries a collection holds; 0 for a scalar.
    #[must_use]
    pub fn len(&self) -> usize {
        self.document.index.nodes[self.id].children.len()
    }

    /// Whether a collection is empty, or the node is a scalar.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The value as written in the source.
    #[must_use]
    pub fn text(&self) -> &str {
        let node = &self.document.index.nodes[self.id];
        &self.document.source[node.value.clone()]
    }
}

/// A YAML document that edits its own text in place.
///
/// Each edit splices the source and parses it again. When the result does not
/// parse, the edit returns an error and the document keeps its old text.
#[derive(Clone, Debug)]
pub struct Document {
    source: String,
    index: Index,
    compact: bool,
    spacing: Spacing,
}

impl Document {
    /// Index one YAML document.
    ///
    /// # Errors
    ///
    /// [`Error::Parse`] for text that is not YAML, and [`Error::Unsupported`]
    /// for `\r\n` line breaks or a stream of several documents.
    pub fn parse(source: impl Into<String>) -> Result<Self, Error> {
        let source = source.into();
        if source.contains('\r') {
            return Err(Error::Unsupported {
                path: Path::root(),
                what: "edit text with carriage returns",
            });
        }
        let index = Index::build(&source)?;
        let compact = compact_lists(&source, &index);
        Ok(Self {
            source,
            index,
            compact,
            spacing: Spacing::default(),
        })
    }

    /// Use `spacing` for new items where a sequence does not settle it.
    #[must_use]
    pub fn with_spacing(mut self, spacing: Spacing) -> Self {
        self.spacing = spacing;
        self
    }

    /// The current text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.source
    }

    /// The current text, owned.
    #[must_use]
    pub fn into_string(self) -> String {
        self.source
    }

    /// The node at a path.
    #[must_use]
    pub fn node(&self, path: &Path) -> Option<Node<'_>> {
        self.index.find(path).map(|id| Node { document: self, id })
    }

    /// Where the value at a path is written.
    #[must_use]
    pub fn locate(&self, path: &Path) -> Option<Location> {
        self.node(path).map(|node| node.value())
    }

    /// Where the value at a path is written, or where its nearest existing
    /// ancestor is, for a path that names something missing. A schema error
    /// about a missing key lands on the mapping that lacks it.
    #[must_use]
    pub fn locate_nearest(&self, path: &Path) -> Option<Location> {
        let id = match self.index.walk(path) {
            Ok(id) => id,
            Err((id, _)) if !self.index.nodes.is_empty() => id,
            Err(_) => return None,
        };
        Some(Node { document: self, id }.value())
    }

    /// Remove the node at a path with its key, the comments it owns, and its
    /// line break. Neighbours keep every byte, including their comments.
    ///
    /// # Errors
    ///
    /// [`Error::NoNode`], [`Error::Unsupported`] for a node inside a flow
    /// collection or the only entry of a mapping, and [`Error::Invalid`].
    pub fn remove(&mut self, path: &Path) -> Result<(), Error> {
        let id = self.id(path)?;
        let parent = self.parent(path, id)?;
        match self.index.nodes[parent].style {
            Style::BlockSequence => {
                let cut = self.cut(path, id, parent)?;
                self.commit_splice(cut.from, cut.to, &cut.with)
            }
            Style::BlockMapping => self.remove_entry(path, id, parent),
            _ => Err(Error::Unsupported {
                path: path.clone(),
                what: "remove from a flow collection",
            }),
        }
    }

    /// Take a sequence item out, with the comments it owns.
    ///
    /// # Errors
    ///
    /// [`Error::NoNode`], [`Error::WrongKind`] when the parent is not a block
    /// sequence, [`Error::Unsupported`] for the only item of a sequence with
    /// no key, and [`Error::Invalid`].
    pub fn take(&mut self, path: &Path) -> Result<Fragment, Error> {
        let id = self.id(path)?;
        let parent = self.parent(path, id)?;
        if self.index.nodes[parent].style != Style::BlockSequence {
            return Err(Error::WrongKind {
                path: path.clone(),
                expected: "an item of a block sequence",
            });
        }
        let cut = self.cut(path, id, parent)?;
        self.commit_splice(cut.from, cut.to, &cut.with)?;
        Ok(Fragment { text: cut.text })
    }

    /// Insert a fragment into a sequence at an index, re-indented to it, and
    /// spaced as [`Spacing`] describes.
    ///
    /// # Errors
    ///
    /// [`Error::NoNode`] for a missing sequence or an index past its end,
    /// [`Error::WrongKind`] when the path is not a sequence or an empty value,
    /// and [`Error::Invalid`].
    pub fn put(&mut self, path: &Path, index: usize, fragment: &Fragment) -> Result<(), Error> {
        let id = self.id(path)?;
        let node = &self.index.nodes[id];
        let lines: Vec<String> = fragment.text.lines().map(str::to_owned).collect();
        match node.style {
            Style::BlockSequence => {
                let dash = column(&self.source, node.value.start);
                let block = join(&indent(&lines, dash));
                let gap = match self.item_spacing(id) {
                    Spacing::Tight => "",
                    Spacing::Blank => NEWLINE,
                };
                if let Some(&child) = node.children.get(index) {
                    let at = self.index.owned_start(&self.source, child);
                    let text = format!("{block}{LF}{gap}");
                    self.commit_splice(at, at, &text)
                } else if let Some(&last) = node.children.last()
                    && index == node.children.len()
                {
                    let at = line_end(&self.source, self.index.nodes[last].value.end);
                    let lead = if self.source[..at].ends_with(LF) {
                        ""
                    } else {
                        NEWLINE
                    };
                    let text = format!("{lead}{gap}{block}{LF}");
                    self.commit_splice(at, at, &text)
                } else {
                    Err(Error::NoNode {
                        path: path.clone().index(index),
                    })
                }
            }
            Style::FlowSequence | Style::Plain
                if node.children.is_empty() && self.is_empty_value(id) =>
            {
                if index != 0 {
                    return Err(Error::NoNode {
                        path: path.clone().index(index),
                    });
                }
                self.fill_empty(path, id, &lines)
            }
            _ => Err(Error::WrongKind {
                path: path.clone(),
                expected: "a block sequence or an empty value",
            }),
        }
    }

    /// The spacing a sequence's items already share, or the document's.
    fn item_spacing(&self, sequence: usize) -> Spacing {
        let mut gaps = self.index.nodes[sequence].children.windows(2).map(|pair| {
            let after = line_end(&self.source, self.index.nodes[pair[0]].value.end);
            has_blank_line(
                &self.source,
                after,
                self.index.owned_start(&self.source, pair[1]),
            )
        });
        match gaps.next() {
            Some(first) if gaps.all(|gap| gap == first) => {
                if first {
                    Spacing::Blank
                } else {
                    Spacing::Tight
                }
            }
            _ => self.spacing,
        }
    }

    fn id(&self, path: &Path) -> Result<usize, Error> {
        self.index
            .find(path)
            .ok_or_else(|| Error::NoNode { path: path.clone() })
    }

    fn parent(&self, path: &Path, id: usize) -> Result<usize, Error> {
        self.index.nodes[id]
            .parent
            .ok_or_else(|| Error::Unsupported {
                path: path.clone(),
                what: "remove or take the root",
            })
    }

    /// Whether a node is `[]`, `~`, `null`, or nothing at all.
    fn is_empty_value(&self, id: usize) -> bool {
        let node = &self.index.nodes[id];
        match node.style {
            Style::FlowSequence => node.children.is_empty(),
            Style::Plain => matches!(self.source[node.value.clone()].trim(), "" | "~" | "null"),
            _ => false,
        }
    }

    /// The byte after a mapping value's `:`, and the key's column.
    fn colon(&self, path: &Path, id: usize) -> Result<(usize, usize), Error> {
        let key = self.index.nodes[id]
            .key
            .as_ref()
            .ok_or_else(|| Error::Unsupported {
                path: path.clone(),
                what: "fill an empty value that has no key",
            })?;
        let after = &self.source[key.range.end..];
        let offset = after.find(':').ok_or_else(|| Error::Invalid {
            message: format!("no ':' after the key at {path}"),
        })?;
        Ok((
            key.range.end + offset + 1,
            column(&self.source, key.range.start),
        ))
    }

    /// Write `lines` as the items of an empty value (`[]`, `~`, `null`, or
    /// nothing) under its key. The key line keeps its node properties and
    /// comment; an empty value on a later line is replaced with its line, and
    /// its own properties and comment move up to the key line. A tag other
    /// than `!!seq`, short or verbatim, would contradict the items, so it is
    /// refused.
    fn fill_empty(&mut self, path: &Path, id: usize, lines: &[String]) -> Result<(), Error> {
        let (colon, key_column) = self.colon(path, id)?;
        let value = self.index.nodes[id].value.clone();
        let key_line_end = line_end(&self.source, colon);
        let key_line_content =
            key_line_end - usize::from(self.source[..key_line_end].ends_with(LF));
        let (mut properties, mut comment) = self.key_line_parts(colon, Some(&value));
        let end = if value.is_empty() || value.end <= key_line_content {
            key_line_end
        } else {
            if value.start > key_line_content {
                let value_line = line_start(&self.source, value.start);
                if !self.source[key_line_end..value_line].trim().is_empty() {
                    return Err(Error::Unsupported {
                        path: path.clone(),
                        what: "fill an empty value with lines between it and its key",
                    });
                }
                properties = spaced(&[&properties, self.source[value_line..value.start].trim()]);
            }
            let end = line_end(&self.source, value.end);
            comment = spaced(&[&comment, self.source[value.end..end].trim()]);
            end
        };
        if properties.split_whitespace().any(|property| {
            property.starts_with('!') && !matches!(property, "!!seq" | "!<tag:yaml.org,2002:seq>")
        }) {
            return Err(Error::Unsupported {
                path: path.clone(),
                what: "fill an empty value whose tag is not !!seq",
            });
        }
        let head = spaced(&[&properties, &comment]);
        let step = if self.compact { 0 } else { 2 };
        let placed: Vec<String> = std::iter::once(if head.is_empty() {
            head
        } else {
            format!(" {head}")
        })
        .chain(indent(lines, key_column + step))
        .collect();
        self.commit_splice(colon, end, &terminated(&join(&placed)))
    }

    /// What follows a key's `:` on its line, apart from the part of `value`
    /// written there: node properties such as `&anchor` or `!!tag`, and a
    /// trailing comment.
    fn key_line_parts(&self, colon: usize, value: Option<&Range<usize>>) -> (String, String) {
        let end = line_end(&self.source, colon);
        let mut rest = self.source[colon..end].trim_end_matches(LF).to_owned();
        let line_content = colon + rest.len();
        if let Some(value) = value.filter(|value| (colon..line_content).contains(&value.start)) {
            rest.replace_range(value.start - colon..value.end.min(line_content) - colon, "");
        }
        let comment_at = rest
            .char_indices()
            .find(|&(at, c)| c == '#' && (at == 0 || rest[..at].ends_with([' ', '\t'])))
            .map(|(at, _)| at);
        let (properties, comment) = rest.split_at(comment_at.unwrap_or(rest.len()));
        (properties.trim().to_owned(), comment.trim().to_owned())
    }

    fn remove_entry(&mut self, path: &Path, id: usize, parent: usize) -> Result<(), Error> {
        let siblings = &self.index.nodes[parent].children;
        if siblings.len() == 1 {
            return Err(Error::Unsupported {
                path: path.clone(),
                what: "remove the only entry of a mapping",
            });
        }
        let entry = self.index.entry_start(id);
        if starts_line(&self.source, entry) {
            let from = self.index.owned_start(&self.source, id);
            let to = line_end(&self.source, self.index.nodes[id].value.end);
            return self.commit_splice(from, to, "");
        }
        let Some(&[_, next]) = siblings.windows(2).find(|pair| pair[0] == id) else {
            return Err(Error::Unsupported {
                path: path.clone(),
                what: "remove the last key of a mapping from its dash line",
            });
        };
        let next_entry = self.index.entry_start(next);
        let comments_start = self.index.owned_start(&self.source, next);
        let comments_end = line_start(&self.source, next_entry);
        let line = line_start(&self.source, entry);
        let dash_column = column(&self.source, self.dash_before(entry));
        let comments: Vec<String> = self.source[comments_start..comments_end]
            .lines()
            .map(|comment| comment.trim_start().to_owned())
            .collect();
        let mut with: String = indent(&comments, dash_column)
            .iter()
            .map(|comment| terminated(comment))
            .collect();
        with.push_str(&self.source[line..entry]);
        self.commit_splice(line, next_entry, &with)
    }

    /// The splice that takes a sequence item out, and the item's text
    /// dedented to its dash. Between blank-separated items the blank line
    /// goes with the item below it, except for the last item, which takes the
    /// one above. Taking the only item leaves `key: []`.
    fn cut(&self, path: &Path, id: usize, parent: usize) -> Result<Cut, Error> {
        let source = &self.source;
        let start = self.index.owned_start(source, id);
        let end = line_end(source, self.index.nodes[id].value.end);
        let text = dedent(&source[start..end], column(source, self.dash(id)));
        let siblings = &self.index.nodes[parent].children;
        if siblings.len() == 1 {
            let (colon, _) = self.colon(path, parent).map_err(|_| Error::Unsupported {
                path: path.clone(),
                what: "take the only item of a sequence with no key",
            })?;
            let (properties, comment) = self.key_line_parts(colon, None);
            let with = format!(" {}{LF}", spaced(&[&properties, "[]", &comment]));
            return Ok(Cut {
                from: colon,
                to: end,
                with,
                text,
            });
        }
        let (mut from, mut to) = (start, end);
        if siblings.last() == Some(&id) {
            while from > 0 {
                let previous = line_start(source, from - 1);
                if !source[previous..from].trim().is_empty() {
                    break;
                }
                from = previous;
            }
        } else {
            while to < source.len() && source[to..line_end(source, to)].trim().is_empty() {
                to = line_end(source, to);
            }
        }
        Ok(Cut {
            from,
            to,
            with: String::new(),
            text,
        })
    }

    /// The byte of the `-` that starts a sequence item.
    fn dash(&self, id: usize) -> usize {
        self.dash_before(self.index.nodes[id].value.start)
    }

    /// The byte of the last `-` on the line before `at`, or `at` itself.
    fn dash_before(&self, at: usize) -> usize {
        let line = line_start(&self.source, at);
        self.source[line..at]
            .rfind('-')
            .map_or(at, |offset| line + offset)
    }

    fn commit_splice(&mut self, from: usize, to: usize, with: &str) -> Result<(), Error> {
        let edited = [&self.source[..from], with, &self.source[to..]].concat();
        let index = Index::build(&edited).map_err(|error| Error::Invalid {
            message: error.to_string(),
        })?;
        self.compact = compact_lists(&edited, &index);
        self.source = edited;
        self.index = index;
        Ok(())
    }
}

/// A document prints as its current text.
impl fmt::Display for Document {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.source)
    }
}

/// The non-empty parts, joined by one space.
fn spaced(parts: &[&str]) -> String {
    parts
        .iter()
        .copied()
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Whether the file writes list items at their key's column rather than
/// under it, judged from the first block list that is a mapping value.
fn compact_lists(source: &str, index: &Index) -> bool {
    index
        .nodes
        .iter()
        .find(|node| node.style == Style::BlockSequence && node.key.is_some())
        .and_then(|node| {
            let key = node.key.as_ref()?;
            Some(column(source, node.value.start) == column(source, key.range.start))
        })
        .unwrap_or(false)
}

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

    use super::Document;
    use crate::Error;

    #[test]
    fn an_edit_that_would_not_parse_leaves_the_text_unchanged() {
        let source = indoc! {"
            a: 1
            b: 2
        "};
        let mut document = Document::parse(source).unwrap();
        let broken = document.commit_splice(0, 4, "a: [1");
        assert!(matches!(broken, Err(Error::Invalid { .. })));
        assert_eq!(document.as_str(), source);
    }
}