From 1ae4c7906765e53294e0acddd3454df953a34e04 Mon Sep 17 00:00:00 2001 From: Craig Thacker Date: Fri, 4 Dec 2026 22:57:48 +0000 Subject: [PATCH] Get values out of YAML, read as YAML 1.2 reads it Get-LdoYamlValue, the twin of ldo yaml get, on a port of the ldo CLI's YAML reader: no yq or powershell-yaml needed. Values are typed by YAML 1.2's core schema, so yes, 12:30 and 2026-09-24 stay strings; anchors and << merges are filled in; and a custom tag, a tab in the indentation, a YAML bomb and nesting past 100 are refused with the line and column. The two readers agree through tests/shared/yaml-read.json, and yaml.json is renamed yaml-write.json, as in ldo-cli. --- CHANGELOG.md | 6 + .../LibreDevOpsHelpers.Yaml.psm1 | 1683 +++++++++++++++++ LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 | 1 + README.md | 10 + tests/README.md | 2 +- tests/Yaml.Tests.ps1 | 162 +- tests/shared/yaml-read.json | 1367 +++++++++++++ tests/shared/{yaml.json => yaml-write.json} | 0 8 files changed, 3225 insertions(+), 6 deletions(-) create mode 100644 tests/shared/yaml-read.json rename tests/shared/{yaml.json => yaml-write.json} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b8299c..904e065 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,12 @@ All notable changes to LibreDevOpsHelpers are recorded here. as an RFC 7396 merge patch. The two agree through one set of test cases, `tests/shared`, that both suites run. - `ConvertTo-LdoYaml -Indent`, for the spaces per level. +- `Get-LdoYamlValue`, the twin of the ldo CLI's `ldo yaml get`: values out of YAML by the paths + `Get-LdoJsonValue` reads, with nothing installed. YAML is read as YAML 1.2 reads it, as yq and + Terraform read it, so `yes`, `on`, `12:30` and `2026-09-24` stay strings and `010` is ten; + anchors, aliases and `<<` merges are filled in; and a custom tag (`!Ref`, `!reference`), a tab + in the indentation, a YAML bomb and nesting past 100 are refused, naming the line and column. A + key given twice is a warning. Its reader and the ldo CLI's agree through `tests/shared`. ### Fixed - `ConvertTo-LdoYaml` wrote a multi-line string as `|` whatever its ending, so a string with no diff --git a/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 b/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 index 39b3f98..c5c06a5 100644 --- a/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 +++ b/LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1 @@ -345,3 +345,1686 @@ function ConvertTo-LdoYaml { return [LdoYamlWriter]::new($Indent, $Depth).Render($InputObject) } } + +# Reading YAML ------------------------------------------------------------------------------- +# +# The twin of the ldo CLI's core.yaml_reader (libre-devops/ldo-cli), by the shared cases in +# tests/shared/yaml-read.json: YAML read with nothing installed, as YAML 1.2 reads it. Values are +# typed by YAML 1.2's core schema, as yq and Terraform type them: true, false, null and ~ in +# lower, title or upper case, whole numbers (12, 0o14, 0xC) as [long] or BigInteger, and floats +# (1.5, 1e3, .inf, .nan) as [double]. Everything else is a string, so yes, on, 12:30 and +# 2026-09-24 stay strings, where YAML 1.1 (PyYAML, Ansible) makes a boolean, a number and a date +# of them, and 010 is ten. Maps are ordered, case-sensitive dictionaries whose keys are their text +# as written; lists are arrays. Anchors, aliases and << merges are filled in. +# +# Refused, with the line and column: a tag other than the core schema's (!Ref, !reference, +# !!timestamp), a key that is not text, a tab in indentation, control characters, aliases that +# stand for more than a million values (a YAML bomb), and nesting past 100. +# +# Text is compared ordinally throughout (String.Equals, char -ceq, ordinal collections): -ceq on +# strings compares by culture, where a zero-width character is nothing, and switch and -in do too. + +class LdoYamlNote { + # Something found in YAML that is read all the same: where (line and column, from 1, the + # column in characters), how much it matters, which rule, and what it means. + [int]$Line + [int]$Column + [string]$Severity + [string]$Rule + [string]$Message + + LdoYamlNote([int]$line, [int]$column, [string]$severity, [string]$rule, [string]$message) { + $this.Line = $line + $this.Column = $column + $this.Severity = $severity + $this.Rule = $rule + $this.Message = $message + } +} + +class LdoYamlError : System.FormatException { + # YAML that cannot be read: where (line and column, from 1), by which rule, and what to do + # about it, if anything. Rule is not-yaml for text that is not YAML, or names what was + # refused: tab-indent, unclosed-quote, control-character, directive, tag, tag-value, + # complex-key, unknown-alias, recursive-alias, alias-limit, too-deep, merge or number; and + # empty for text holding no document. + [int]$Line + [int]$Column + [string]$Rule + [string]$Hint + + LdoYamlError([string]$message, [int]$line, [int]$column, [string]$rule, [string]$hint) : base($message) { + $this.Line = $line + $this.Column = $column + $this.Rule = $rule + $this.Hint = $hint + } +} + +class LdoYamlParsed { + # A stream's documents, and the notes on them. + [object[]]$Documents + [LdoYamlNote[]]$Notes +} + +class LdoYamlScalar { + # A scalar as written, before it is typed: plain text is typed by the core schema, and + # quoted text and blocks are strings. + [string]$Text + [bool]$Plain + [int]$At + + LdoYamlScalar([string]$text, [bool]$plain, [int]$at) { + $this.Text = $text + $this.Plain = $plain + $this.At = $at + } +} + +class LdoYamlProps { + # A node's anchor and tag (either may be empty), and where they were written. + [string]$Anchor + [string]$Tag + [int]$At + + LdoYamlProps([string]$anchor, [string]$tag, [int]$at) { + $this.Anchor = $anchor + $this.Tag = $tag + $this.At = $at + } +} + +class LdoYamlFlow { + # A node read inside [ ] or { }, and what it gives as a key: its text (HasKey) when it is + # plain or quoted text with no anchor or tag, and Why it cannot be one otherwise. JsonLike + # (quoted, or a collection) lets a ':' follow it with no space; Explicit is a ? key. + [object]$Value + [string]$Key + [bool]$HasKey + [bool]$Plain + [bool]$JsonLike + [string]$Why + [bool]$Explicit + + LdoYamlFlow([object]$value, [string]$why) { + $this.Value = $value + $this.Why = $why + } +} + +class LdoYamlEntries { + # A map as it is read: its entries in order, and the << merges among them. + [object]$Reader + [System.Collections.Generic.List[string]]$Keys = [System.Collections.Generic.List[string]]::new() + [System.Collections.Generic.List[bool]]$Merges = [System.Collections.Generic.List[bool]]::new() + [System.Collections.Generic.List[object]]$Values = [System.Collections.Generic.List[object]]::new() + [System.Collections.Generic.Dictionary[string, int]]$First = [System.Collections.Generic.Dictionary[string, int]]::new([System.StringComparer]::Ordinal) + + LdoYamlEntries([object]$reader) { + $this.Reader = $reader + } + + # Add a key (written at $at), warning when it was given before. Only a plain << merges. + [void] Add([string]$key, [bool]$plain, [object]$value, [int]$at) { + if ($this.First.ContainsKey($key)) { + $this.Reader.Duplicate($key, $this.First[$key], $at) + } + else { + $this.First[$key] = $at + } + $merge = $plain -and [string]::Equals($key, '<<') + $this.Keys.Add($key) + $this.Merges.Add($merge) + if ($merge) { $this.Values.Add($this.Reader.Merged($value, $at)) } else { $this.Values.Add($value) } + } + + # The map. A << merge puts the keys of the maps it names where it stands, but not a key the + # map sets itself, wherever that is, nor one an earlier merge gave: the first map named wins. + [System.Collections.Specialized.OrderedDictionary] Build() { + $own = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + for ($i = 0; $i -lt $this.Keys.Count; $i++) { + if (-not $this.Merges[$i]) { [void]$own.Add($this.Keys[$i]) } + } + $mapping = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + for ($i = 0; $i -lt $this.Keys.Count; $i++) { + if (-not $this.Merges[$i]) { + $mapping[[string]$this.Keys[$i]] = $this.Values[$i] + continue + } + foreach ($source in [object[]]$this.Values[$i]) { + foreach ($key in [string[]]@($source.Keys)) { + if (-not $own.Contains($key) -and -not $mapping.Contains($key)) { $mapping[$key] = $source[$key] } + } + } + } + return $mapping + } +} + +class LdoYamlReader { + # One pass over a YAML stream, by recursive descent: Pos is how far it has read, as an + # offset in the text. Parent throughout is the indent of the map or list a node is in (-1 at + # the top): its lines below its first must be indented more than that. + # + # An error is not left to unwind the whole descent: PowerShell catches and throws again at + # every method on the way out, each time on top of the stack, so an error 70 maps deep runs + # out of stack and ends the process. Instead each map and list catches what is thrown inside + # it, keeps the first as Failure, and returns; each loop stops when Failure is set; and the + # document throws it from the top. So the error is the first one met, as the ldo CLI's is. + + # How many values aliases may stand for in one stream, each counted whole. Past this a file + # is a YAML bomb (a billion laughs), or far bigger than it looks. + static [int]$AliasLimit = 1000000 + # How deep maps and lists may nest, an alias's own nesting included. + static [int]$DepthLimit = 100 + # The most digits a decimal number may have: Python's limit, which the ldo CLI meets. + static [int]$MaxDigits = 4300 + + static [System.Collections.Generic.HashSet[string]]$Tags = [System.Collections.Generic.HashSet[string]]::new( + [string[]]@('!', '!!str', '!!int', '!!float', '!!bool', '!!null', '!!map', '!!seq'), [System.StringComparer]::Ordinal) + static [string]$CorePrefix = 'tag:yaml.org,2002:' + static [string]$TagHint = "a custom tag, such as CloudFormation's !Ref or GitLab's !reference, means something only to the tool it was written for, so it is not read" + static [string]$KeyWhy = "a key here is plain or quoted text on one line, as JSON's keys are text" + static [string]$NoKey = 'an explicit key (?) with no key' + static [System.Collections.Generic.HashSet[string]]$Nulls = [System.Collections.Generic.HashSet[string]]::new( + [string[]]@('null', 'Null', 'NULL', '~', ''), [System.StringComparer]::Ordinal) + static [System.Collections.Generic.HashSet[string]]$Trues = [System.Collections.Generic.HashSet[string]]::new( + [string[]]@('true', 'True', 'TRUE'), [System.StringComparer]::Ordinal) + static [System.Collections.Generic.HashSet[string]]$Falses = [System.Collections.Generic.HashSet[string]]::new( + [string[]]@('false', 'False', 'FALSE'), [System.StringComparer]::Ordinal) + + static [regex]$DecimalPattern = [regex]::new('\A[-+]?[0-9]+\z') + static [regex]$OctalPattern = [regex]::new('\A0o[0-7]+\z') + static [regex]$HexPattern = [regex]::new('\A0x[0-9a-fA-F]+\z') + static [regex]$FloatPattern = [regex]::new('\A[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?\z') + static [regex]$InfinityPattern = [regex]::new('\A[-+]?\.(?:inf|Inf|INF)\z') + static [regex]$NanPattern = [regex]::new('\A\.(?:nan|NaN|NAN)\z') + + # What YAML allows nowhere in a file: control characters but tab and line breaks (NEL, + # U+0085, is allowed), DEL, lone surrogates (a pair is one character), and U+FFFE and U+FFFF. + static [regex]$Unprintable = [regex]::new('[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x84\x86-\x9f\ufffe\uffff]|[\ud800-\udbff](?![\udc00-\udfff])|(?''"%@`]|[-?:](?=[^ \t\n]))') + static [regex]$PlainStartFlow = [regex]::new('\G(?:[^ \t\n\-?:,\[\]{}#&*!|>''"%@`]|[-?:](?=[^ \t\n,\[\]{}]))') + static [regex]$DoubleRun = [regex]::new('\G[^"\\\n]*') + static [regex]$SingleRun = [regex]::new("\G[^'\n]*") + static [regex]$HexDigits = [regex]::new('\A[0-9a-fA-F]+\z') + + static [System.Collections.Generic.Dictionary[string, string]]$Escapes = [LdoYamlReader]::Table(@( + '0', [string][char]0, 'a', [string][char]7, 'b', [string][char]8, 't', "`t", "`t", "`t", + 'n', "`n", 'v', [string][char]11, 'f', [string][char]12, 'r', "`r", 'e', [string][char]27, + ' ', ' ', '"', '"', '/', '/', '\', '\', 'N', [string][char]0x85, '_', [string][char]0xA0, + 'L', [string][char]0x2028, 'P', [string][char]0x2029)) + static [System.Collections.Generic.Dictionary[string, string]]$HexEscapes = [LdoYamlReader]::Table(@('x', '2', 'u', '4', 'U', '8')) + # What cannot start a value, and why: each is what|why. + static [System.Collections.Generic.Dictionary[string, string]]$CannotStartWhy = [LdoYamlReader]::Table(@( + ']', 'a ] with no [ before it|', '}', 'a } with no { before it|', ',', 'a , with no value before it|', + '|', 'a | block inside [ ] or { }|', '>', 'a > block inside [ ] or { }|', '-', 'a - with nothing after it|', + ':', 'a : with no key before it|', '@', 'a value starting with @|YAML keeps @ for later, so quote it', + '`', 'a value starting with `|YAML keeps ` for later, so quote it', '%', 'a value starting with %|quote it')) + # Where a key should be, what was there instead. + static [System.Collections.Generic.Dictionary[string, string]]$NotKeys = [LdoYamlReader]::Table(@( + '?', 'an explicit key (?) that is not text', '[', 'a list or map as a key', '{', 'a list or map as a key', + '*', 'an alias as a key', '&', 'an anchor or tag on a key', '!', 'an anchor or tag on a key')) + # What a tag on a scalar asks for: the kinds of text that can be one|what it is. + static [System.Collections.Generic.Dictionary[string, string]]$TagKinds = [LdoYamlReader]::Table(@( + '!!int', 'int|a whole number', '!!float', 'int float|a number', '!!bool', 'bool|true or false', '!!null', 'null|null')) + + [string]$Text + [int]$Pos + [System.Collections.Generic.List[LdoYamlNote]]$Notes = [System.Collections.Generic.List[LdoYamlNote]]::new() + [int[]]$Starts + # The text with four NULs after it, so a character a few ahead can be looked at without a + # method call (a call costs some twenty times a comparison here) and without checking the + # length first: past the end it is NUL, which the text cannot hold (it is refused). + [string]$Padded + [bool]$Astral + [System.Collections.Generic.Dictionary[string, object]]$Anchors + [System.Collections.Generic.HashSet[string]]$Open = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal) + [System.Collections.Generic.Dictionary[object, int[]]]$Measured = [System.Collections.Generic.Dictionary[object, int[]]]::new([System.Collections.Generic.ReferenceEqualityComparer]::Instance) + [int]$Expanded + [int]$Depth + [LdoYamlError]$Failure + + # Text written first|second, split at its last |, as the tables above hold two things each. + static [string[]] Pair([string]$text) { + $bar = $text.LastIndexOf([char]'|') + return [string[]]@($text.Substring(0, $bar), $text.Substring($bar + 1)) + } + + static [System.Collections.Generic.Dictionary[string, string]] Table([string[]]$pairs) { + $table = [System.Collections.Generic.Dictionary[string, string]]::new([System.StringComparer]::Ordinal) + for ($i = 0; $i -lt $pairs.Count; $i += 2) { $table[$pairs[$i]] = $pairs[$i + 1] } + return $table + } + + # Every document in the text, read as YAML 1.2, and warnings on them: a key given twice, and + # a %YAML directive for a version other than 1.2. A byte order mark is dropped, and a line + # may end CR LF or CR. Throws LdoYamlError saying where the text cannot be read. + static [LdoYamlParsed] Parse([string]$source) { + $given = $source + if ($given.Length -gt 0 -and $given[0] -ceq [char]0xFEFF) { $given = $given.Substring(1) } + $given = $given.Replace("`r`n", "`n").Replace("`r", "`n") + if ($given.Trim([char[]]@(' ', "`t", "`n")).Length -eq 0) { + throw [LdoYamlError]::new('the input is empty', 0, 0, 'empty', '') + } + $reader = [LdoYamlReader]::new($given) + $documents = $reader.Read() + if ($documents.Count -eq 0) { + throw [LdoYamlError]::new('the input holds no document, only comments', 0, 0, 'empty', '') + } + $parsed = [LdoYamlParsed]::new() + $parsed.Documents = $documents + $parsed.Notes = $reader.Notes.ToArray() + return $parsed + } + + # The LdoYamlError behind an exception, which PowerShell may have wrapped on the way out. + static [System.Exception] Cause([System.Exception]$exception) { + while ($exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $exception.InnerException) { + $exception = $exception.InnerException + } + return $exception + } + + LdoYamlReader([string]$text) { + $this.Text = $text + $found = [System.Collections.Generic.List[int]]::new() + $found.Add(0) + $at = $text.IndexOf([char]10) + while ($at -ge 0) { + $found.Add($at + 1) + $at = $text.IndexOf([char]10, $at + 1) + } + $this.Starts = $found.ToArray() + $this.Padded = $text + [string]::new([char]0, 4) + $this.Astral = $text -cmatch '[\ud800-\udfff]' + $control = [LdoYamlReader]::Unprintable.Match($text) + if ($control.Success) { + $code = ([int][char]$control.Value[0]).ToString('X4') + throw $this.Fail('control-character', "not YAML: a control character (U+$code)", $control.Index, + 'YAML allows none in a file', 'write it inside double quotes as an escape, such as \u0007') + } + } + + # Typing ---------------------------------------------------------------------------------- + + # The kind (null, bool, int, float, str, or too-long for a decimal of more than MaxDigits + # digits) and value the core schema gives text written plain. + static [object[]] Core([string]$text) { + if ([LdoYamlReader]::Nulls.Contains($text)) { return @('null', $null) } + if ([LdoYamlReader]::Trues.Contains($text)) { return @('bool', $true) } + if ([LdoYamlReader]::Falses.Contains($text)) { return @('bool', $false) } + $invariant = [System.Globalization.CultureInfo]::InvariantCulture + if ([LdoYamlReader]::DecimalPattern.IsMatch($text)) { + if ($text.TrimStart([char[]]@('+', '-')).Length -gt [LdoYamlReader]::MaxDigits) { return @('too-long', $null) } + return @('int', [LdoYamlReader]::Whole([System.Numerics.BigInteger]::Parse($text, $invariant))) + } + if ([LdoYamlReader]::OctalPattern.IsMatch($text)) { + $value = [System.Numerics.BigInteger]::Zero + foreach ($digit in $text.Substring(2).ToCharArray()) { $value = $value * 8 + ([int]$digit - 48) } + return @('int', [LdoYamlReader]::Whole($value)) + } + if ([LdoYamlReader]::HexPattern.IsMatch($text)) { + $value = [System.Numerics.BigInteger]::Parse('0' + $text.Substring(2), [System.Globalization.NumberStyles]::AllowHexSpecifier, $invariant) + return @('int', [LdoYamlReader]::Whole($value)) + } + if ([LdoYamlReader]::FloatPattern.IsMatch($text)) { + return @('float', [double]::Parse($text, [System.Globalization.NumberStyles]::Float, $invariant)) + } + if ([LdoYamlReader]::InfinityPattern.IsMatch($text)) { + $infinity = if ($text[0] -ceq [char]'-') { [double]::NegativeInfinity } else { [double]::PositiveInfinity } + return @('float', $infinity) + } + if ([LdoYamlReader]::NanPattern.IsMatch($text)) { return @('float', [double]::NaN) } + return @('str', $text) + } + + # A whole number as a [long] when it fits in one, else a BigInteger. + static [object] Whole([System.Numerics.BigInteger]$value) { + if ($value -ge [long]::MinValue -and $value -le [long]::MaxValue) { return [long]$value } + return $value + } + + # Blocks ---------------------------------------------------------------------------------- + + # A > block's lines as one text: a line break between two lines of text becomes a space, + # unless empty lines come between them (each is a line break), or either line is more + # indented (starts with a space or tab), whose breaks are all kept. + static [string] Folded([System.Collections.Generic.List[string]]$lines) { + $leading = 0 + while ($lines[$leading].Length -eq 0) { $leading++ } + $previous = $lines[$leading] + $pieces = [System.Text.StringBuilder]::new() + [void]$pieces.Append([char]10, $leading).Append($previous) + $empty = 0 + for ($i = $leading + 1; $i -lt $lines.Count; $i++) { + $line = $lines[$i] + if ($line.Length -eq 0) { + $empty++ + continue + } + if (-not [LdoYamlReader]::Indented($previous) -and -not [LdoYamlReader]::Indented($line)) { + if ($empty -eq 0) { [void]$pieces.Append(' ') } else { [void]$pieces.Append([char]10, $empty) } + } + else { + [void]$pieces.Append([char]10, $empty + 1) + } + [void]$pieces.Append($line) + $previous = $line + $empty = 0 + } + return $pieces.ToString() + } + + static [bool] Indented([string]$line) { + return $line[0] -ceq [char]' ' -or $line[0] -ceq [char]"`t" + } + + # A block's text with its ending as chomp says: strip keeps no final line break, clip one, + # and keep every one, the empty lines after it included. + static [string] Chomped([string]$body, [bool]$text, [bool]$ended, [int]$trailing, [string]$chomp) { + if ([string]::Equals($chomp, 'strip')) { return $body } + if (-not $text) { + if ([string]::Equals($chomp, 'keep')) { return [string]::new([char]10, $trailing) } + return '' + } + $end = if ($ended) { "`n" } else { '' } + if ([string]::Equals($chomp, 'clip')) { return $body + $end } + return $body + $end + [string]::new([char]10, $trailing) + } + + static [int] LeadingSpaces([string]$line) { + return $line.Length - $line.TrimStart([char]' ').Length + } + + # Text as Python's repr writes it, for a message: quoted, with what cannot be seen escaped. + static [string] Repr([string]$text) { + $quote = if ($text.Contains("'") -and -not $text.Contains('"')) { '"' } else { "'" } + $out = [System.Text.StringBuilder]::new($quote) + foreach ($char in $text.ToCharArray()) { + $code = [int]$char + if ($char -ceq [char]'\') { [void]$out.Append('\\') } + elseif ([string]::Equals([string]$char, $quote)) { [void]$out.Append('\').Append($char) } + elseif ($code -eq 10) { [void]$out.Append('\n') } + elseif ($code -eq 9) { [void]$out.Append('\t') } + elseif ($code -eq 13) { [void]$out.Append('\r') } + elseif ($code -lt 32 -or ($code -ge 0x7F -and $code -le 0xA0) -or $code -eq 0xAD) { [void]$out.Append('\x' + $code.ToString('x2')) } + elseif ($code -eq 0x2028 -or $code -eq 0x2029) { [void]$out.Append('\u' + $code.ToString('x4')) } + else { [void]$out.Append($char) } + } + return $out.Append($quote).ToString() + } + + # The stream ------------------------------------------------------------------------------ + + # Every document in the stream, in order. + [object[]] Read() { + $documents = [System.Collections.Generic.List[object]]::new() + while ($this.NextContent($false)) { + if ([string]::Equals($this.Marker(), '...')) { + $this.DocumentEnd() + continue + } + try { + $documents.Add($this.Document()) + } + catch { + # What went wrong after a map or list kept an error is not the error. + if ($null -ne $this.Failure) { throw $this.Failure } + throw + } + } + return $documents.ToArray() + } + + [object] Document() { + $this.Anchors = [System.Collections.Generic.Dictionary[string, object]]::new([System.StringComparer]::Ordinal) + $value = $null + if ($this.Directives() -or [string]::Equals($this.Marker(), '---')) { + if (-not [string]::Equals($this.Marker(), '---')) { + throw $this.Fail('not-yaml', 'not YAML: directives with no --- after them') + } + $this.Pos += 3 + $value = $this.Value(-1, $true, $false) + } + else { + $value = $this.ReadNode(-1, $true, $false, $null) + } + if ($null -ne $this.Failure) { throw $this.Failure } + if ($this.NextContent($false) -and -not [string]::Equals($this.Marker(), '---')) { + if (-not [string]::Equals($this.Marker(), '...')) { + throw $this.Fail('not-yaml', 'not YAML: more after the document has ended', $this.Pos, + 'a stream starts each document after the first with ---', '') + } + $this.DocumentEnd() + } + return $value + } + + [void] DocumentEnd() { + $this.Pos += 3 + if (-not $this.LineEnds()) { throw $this.Fail('not-yaml', 'not YAML: more on the line after ...') } + } + + # Read the % lines that may start a document; whether there were any. + [bool] Directives() { + $found = $false + while (($this.Padded[$this.Pos] -ceq [char]'%') -and $this.LineStart($this.Pos)) { + $this.Directive() + $found = $true + if (-not $this.NextContent($false)) { + throw $this.Fail('not-yaml', 'not YAML: directives with no document after them') + } + } + return $found + } + + [void] Directive() { + $start = $this.Pos + $end = $this.LineEnd($start) + $version = [LdoYamlReader]::DirectivePattern.Match($this.Text.Substring($start, $end - $start)) + if (-not $version.Success) { + $name = $this.Text.Substring($start, $this.EndOf([LdoYamlReader]::DirectiveName, $start) - $start) + throw $this.Fail('directive', "the directive $name", $start, 'only %YAML is read', '') + } + $number = $version.Groups[1].Value + if (-not [string]::Equals($number, '1.2')) { + $this.Note($start, 'warning', 'yaml-version', + "a %YAML $number directive, but this reads YAML 1.2, where yes and on are strings and 010 is ten") + } + $this.Pos = $end + } + + # Block nodes ----------------------------------------------------------------------------- + + # The node after a key's colon, an item's dash or ---: on the same line, or on the lines + # below if they are indented more than parent; null if neither. + [object] Value([int]$parent, [bool]$compact, [bool]$inMap) { + if ($this.LineEnds()) { return $this.Below($parent, $inMap, $null) } + return $this.ReadNode($parent, $compact, $inMap, $null) + } + + # The node on the lines below, if indented more than parent. A key's value may also be a + # list at the key's own indent (inMap), as YAML allows. Held is an anchor or tag written + # alone on the line before, for this node. + [object] Below([int]$parent, [bool]$inMap, [object]$held) { + if (-not $this.NextContent($false) -or $this.Marker()) { + return $this.Finish($held, [LdoYamlScalar]::new('', $true, $this.Pos)) + } + $column = $this.Column($this.Pos) + if ($column -gt $parent) { return $this.ReadNode($parent, $true, $false, $held) } + if ($column -eq $parent -and $inMap -and $this.AtDash()) { + return $this.Finish($held, $this.BlockSequence($column, $true)) + } + return $this.Finish($held, [LdoYamlScalar]::new('', $true, $this.Pos)) + } + + # The node whose first character is here. Compact lets a map or list start on this line, as + # at the start of a line or after a dash. + [object] ReadNode([int]$parent, [bool]$compact, [bool]$inMap, [object]$held) { + $column = $this.Column($this.Pos) + if ($compact -and $this.AtDash()) { + return $this.Finish($held, $this.BlockSequence($column, $false)) + } + if ($compact -and ($this.KeyAhead() -or $this.ExplicitKeyHere())) { + return $this.Finish($held, $this.BlockMapping($column)) + } + $props = $this.Properties($held) + if (-not [object]::ReferenceEquals($props, $held) -and $this.LineEnds()) { + return $this.Below($parent, $inMap, $props) + } + return $this.Inline($parent, $compact, $props) + } + + # A node that starts on this line and is not a map or list in block style: a scalar, a + # block, a flow collection or an alias. + [object] Inline([int]$parent, [bool]$compact, [object]$props) { + $start = $this.Pos + $this.RefuseCollection($compact) + if (($this.Padded[$this.Pos] -ceq [char]'*')) { + $value = $this.AliasWith($props) + $this.LineDone('an alias', $start) + return $value + } + if (($this.Padded[$this.Pos] -ceq [char]'|') -or ($this.Padded[$this.Pos] -ceq [char]'>')) { + return $this.Finish($props, $this.BlockScalar($parent)) + } + return $this.Finish($props, $this.BlockFlowOrScalar($parent, $start)) + } + + # Refuse a map or list in block style where one cannot start. + [void] RefuseCollection([bool]$compact) { + if ($this.KeyAhead()) { + if ($compact) { throw $this.Fail('complex-key', 'an anchor or tag on a key', $this.Pos, [LdoYamlReader]::KeyWhy, '') } + throw $this.Fail('not-yaml', 'not YAML: a map starting on the line of its key', $this.Pos, 'start it on the next line, indented', '') + } + if ($this.AtDash()) { + throw $this.Fail('not-yaml', 'not YAML: a list starting on the line of its key', $this.Pos, 'start it on the next line', '') + } + } + + [object] BlockFlowOrScalar([int]$parent, [int]$start) { + if (($this.Padded[$this.Pos] -ceq [char]'[') -or ($this.Padded[$this.Pos] -ceq [char]'{')) { + $collection = $this.FlowCollection() + $this.LineDone('a list or map', $start) + return $collection + } + if (($this.Padded[$this.Pos] -ceq [char]'"') -or ($this.Padded[$this.Pos] -ceq [char]"'")) { + $scalar = [LdoYamlScalar]::new($this.Quoted(), $false, $start) + $this.LineDone('a quoted string', $start) + return $scalar + } + $this.RefuseExplicitKey() + return [LdoYamlScalar]::new($this.Plain($parent, $false), $true, $start) + } + + # After a node in block style: nothing but a comment may follow on its line. + [void] LineDone([string]$what, [int]$start) { + if ($this.LineEnds()) { return } + if (($this.Padded[$this.Pos] -ceq [char]':')) { throw $this.Fail('complex-key', "$what as a key", $start, [LdoYamlReader]::KeyWhy, '') } + throw $this.Fail('not-yaml', 'not YAML: more on the line after a complete value') + } + + [System.Collections.Specialized.OrderedDictionary] BlockMapping([int]$indent) { + try { + $entries = [LdoYamlEntries]::new($this) + $this.Enter() + while ($true) { + $at = $this.Pos + if ($this.ExplicitKeyHere()) { + $entry = $this.ExplicitEntry($indent) + if ($null -ne $this.Failure) { return $null } + $entries.Add($entry[0], $entry[1], $entry[2], $at) + } + else { + $this.RefuseNonKey() + $key = $this.BlockKey() + $value = $this.Value($indent, $false, $true) + if ($null -ne $this.Failure) { return $null } + $entries.Add($key[0], $key[1], $value, $at) + } + if (-not $this.NextAt($indent)) { break } + } + $this.Depth-- + return $entries.Build() + } + catch { + $this.Keep($_.Exception) + return $null + } + } + + # Keep an error thrown inside a map or list as Failure, the first one only; anything that is + # not an LdoYamlError is a fault in this reader, and goes on up. + [void] Keep([System.Exception]$exception) { + $cause = [LdoYamlReader]::Cause($exception) + if ($cause -isnot [LdoYamlError]) { throw $exception } + if ($null -eq $this.Failure) { $this.Failure = $cause } + } + + # A key and its colon, already known to be here: the key's text, and whether it was plain + # (only a plain << merges). + [object[]] BlockKey() { + $key = $null + $plain = $false + if (($this.Padded[$this.Pos] -ceq [char]'"') -or ($this.Padded[$this.Pos] -ceq [char]"'")) { + $key = $this.Quoted() + } + else { + $end = $this.EndOf([LdoYamlReader]::PlainBlock, $this.Pos) + $key = $this.Text.Substring($this.Pos, $end - $this.Pos).TrimEnd([char[]]@(' ', "`t")) + $plain = $true + $this.Pos = $end + } + $this.SkipSpaces() + $this.Pos += 1 # the colon + return @($key, $plain) + } + + [bool] ExplicitKeyHere() { + return ($this.Padded[$this.Pos] -ceq [char]'?') -and $this.Blank(1) + } + + # ? key and, on a line of its own at the same indent, : value: how YAML writes a key over + # several lines. The key must still be text. Gives the key, whether it was plain, and value. + [object[]] ExplicitEntry([int]$indent) { + $question = $this.Pos + $this.Pos += 1 + $key = $this.ExplicitKey($indent, $question) + if (-not $this.NextContent($false) -or $this.Marker() -or $this.Column($this.Pos) -ne $indent) { + return @($key[0], $key[1], $null) + } + if (-not $this.ColonAt($this.Pos)) { return @($key[0], $key[1], $null) } + $this.Pos += 1 + return @($key[0], $key[1], $this.Value($indent, $true, $true)) + } + + # The text of an explicit key: plain, quoted or a block, on its line or below. Question is + # where its ? is. + [object[]] ExplicitKey([int]$indent, [int]$question) { + if ($this.LineEnds() -and (-not $this.NextContent($false) -or $this.Marker() -or $this.Column($this.Pos) -le $indent)) { + throw $this.Fail('complex-key', [LdoYamlReader]::NoKey, $question, [LdoYamlReader]::KeyWhy, '') + } + $start = $this.Pos + if ([LdoYamlReader]::NotKeys.ContainsKey($this.Peek(0)) -or $this.AtDash() -or $this.KeyAhead()) { + throw $this.Fail('complex-key', 'an explicit key (?) that is not text', $this.Pos, [LdoYamlReader]::KeyWhy, '') + } + $key = $null + $plain = $false + if (($this.Padded[$this.Pos] -ceq [char]'"') -or ($this.Padded[$this.Pos] -ceq [char]"'")) { + $key = $this.Quoted() + } + elseif (($this.Padded[$this.Pos] -ceq [char]'|') -or ($this.Padded[$this.Pos] -ceq [char]'>')) { + $key = $this.BlockScalar($indent).Text + } + else { + $key = $this.Plain($indent, $false) + $plain = $true + } + $this.LineDone('an explicit key', $start) + return @($key, $plain) + } + + [void] RefuseNonKey() { + if ($this.KeyAhead()) { return } + if ($this.AtDash()) { throw $this.Fail('not-yaml', 'not YAML: a list item among the keys of a map') } + $refused = $null + if ([LdoYamlReader]::NotKeys.TryGetValue($this.Peek(0), [ref]$refused)) { + throw $this.Fail('complex-key', $refused, $this.Pos, [LdoYamlReader]::KeyWhy, '') + } + throw $this.Fail('not-yaml', 'not YAML: a line in a map with no key: on it') + } + + # A list in block style at indent. InMap: it is a key's value at the key's own indent, so a + # line there with no dash is the map's next key. + [object[]] BlockSequence([int]$indent, [bool]$inMap) { + try { + $items = [System.Collections.Generic.List[object]]::new() + $this.Enter() + while ($true) { + $this.Pos += 1 # the dash + $items.Add($this.Value($indent, $true, $false)) + if ($null -ne $this.Failure) { return $null } + if (-not $this.NextAt($indent)) { break } + if (-not $this.AtDash()) { + if ($inMap) { break } + throw $this.Fail('not-yaml', 'not YAML: a line among a list''s items with no -') + } + } + $this.Depth-- + return $items.ToArray() + } + catch { + $this.Keep($_.Exception) + return $null + } + } + + # After an entry or item: whether the next is at indent. Less indented means the map or list + # has ended; more lines up with nothing. + [bool] NextAt([int]$indent) { + if (-not $this.NextContent($false) -or $this.Marker()) { return $false } + $column = $this.Column($this.Pos) + if ($column -gt $indent) { + throw $this.Fail('not-yaml', "not YAML: indented $column spaces", $this.Pos, 'that lines up with nothing above it', '') + } + return $column -eq $indent + } + + [void] Enter() { + $this.Depth++ + if ($this.Depth -gt [LdoYamlReader]::DepthLimit) { + throw $this.Fail('too-deep', "maps and lists nested more than $([LdoYamlReader]::DepthLimit) deep") + } + } + + # Properties, aliases and types ----------------------------------------------------------- + + # The anchor and tag written here, in either order; else held, those written alone on the + # line before for this node. + [object] Properties([object]$held) { + $start = $this.Pos + $anchor = '' + $tag = '' + while (($this.Padded[$this.Pos] -ceq [char]'&') -or ($this.Padded[$this.Pos] -ceq [char]'!')) { + if (($this.Padded[$this.Pos] -ceq [char]'&') -and $anchor.Length -eq 0) { + $anchor = $this.Anchor() + } + elseif (($this.Padded[$this.Pos] -ceq [char]'!') -and $tag.Length -eq 0) { + $tag = $this.Tag() + } + else { + throw $this.Fail('not-yaml', 'not YAML: a second anchor or tag for one value') + } + $this.SkipSpaces() + } + if ($anchor.Length -eq 0 -and $tag.Length -eq 0) { return $held } + if ($null -ne $held) { + throw $this.Fail('not-yaml', 'not YAML: a second anchor or tag for one value', $start, '', '') + } + if ($anchor.Length -gt 0) { [void]$this.Open.Add($anchor) } + return [LdoYamlProps]::new($anchor, $tag, $start) + } + + [string] Anchor() { + $at = $this.Pos + $this.Pos += 1 + $name = $this.AnchorName() + if ($name.Length -eq 0) { throw $this.Fail('not-yaml', 'not YAML: an & with no name after it', $at, '', '') } + return $name + } + + [string] Tag() { + $at = $this.Pos + $tag = $null + if (($this.Padded[$this.Pos + 1] -ceq [char]'<')) { + $tag = $this.VerbatimTag() + } + else { + $this.Pos = $this.EndOf([LdoYamlReader]::TagPattern, $at) + $tag = $this.Text.Substring($at, $this.Pos - $at) + } + if (-not [LdoYamlReader]::Tags.Contains($tag)) { + if ($tag.StartsWith('!!', [System.StringComparison]::Ordinal)) { + throw $this.Fail('tag', "the tag $tag", $at, "YAML 1.1 had that type, but 1.2's core schema has not", '') + } + throw $this.Fail('tag', "the tag $tag", $at, "YAML 1.2's core schema has no such type", [LdoYamlReader]::TagHint) + } + return $tag + } + + # A tag written !<...>, as its short form when it is the core schema's. + [string] VerbatimTag() { + $at = $this.Pos + $close = $this.Text.IndexOf([char]'>', $at) + $lineEnd = $this.Text.IndexOf([char]10, $at) + if ($close -lt 0 -or (0 -le $lineEnd -and $lineEnd -lt $close)) { + throw $this.Fail('not-yaml', 'not YAML: a !< tag with no > to close it') + } + $name = $this.Text.Substring($at + 2, $close - $at - 2) + $this.Pos = $close + 1 + if ($name.StartsWith([LdoYamlReader]::CorePrefix, [System.StringComparison]::Ordinal)) { + return '!!' + $name.Substring([LdoYamlReader]::CorePrefix.Length) + } + return "!<$name>" + } + + [object] AliasWith([object]$props) { + if ($null -ne $props) { throw $this.Fail('not-yaml', 'not YAML: an alias with an anchor or tag of its own') } + return $this.Alias() + } + + [object] Alias() { + $at = $this.Pos + $this.Pos += 1 + $name = $this.AnchorName() + if ($name.Length -eq 0) { throw $this.Fail('not-yaml', 'not YAML: a * with no name after it', $at, '', '') } + if ($this.Open.Contains($name)) { + throw $this.Fail('recursive-alias', "the alias *$name", $at, 'it is inside what it names', '') + } + if (-not $this.Anchors.ContainsKey($name)) { + throw $this.Fail('unknown-alias', "the alias *$name", $at, "no &$name comes before it", '') + } + $value = $this.Anchors[$name] + $this.Tally($value, $at) + return $value + } + + # Count what an alias stands for against the limits. + [void] Tally([object]$value, [int]$at) { + $size = $this.Measure($value) + $this.Expanded += $size[0] + if ($this.Expanded -gt [LdoYamlReader]::AliasLimit) { + $limit = [LdoYamlReader]::AliasLimit.ToString('N0', [System.Globalization.CultureInfo]::InvariantCulture) + throw $this.Fail('alias-limit', 'an alias', $at, "aliases here stand for more than $limit values", + 'this is a YAML bomb (a billion laughs), or a file far bigger than it looks') + } + if ($this.Depth + $size[1] -gt [LdoYamlReader]::DepthLimit) { + throw $this.Fail('too-deep', "maps and lists nested more than $([LdoYamlReader]::DepthLimit) deep", $at, '', '') + } + } + + # How many values a value holds, itself included, and how deep it nests. + [int[]] Measure([object]$value) { + $isMap = $value -is [System.Collections.IDictionary] + if (-not $isMap -and $value -isnot [object[]]) { return [int[]]@(1, 0) } + $known = $null + if ($this.Measured.TryGetValue($value, [ref]$known)) { return $known } + $size = 1 + $deepest = 0 + # Not an if used as a value, which would unroll a list of one list. + [object[]]$children = $value + if ($isMap) { $children = [object[]]@($value.Values) } + foreach ($child in $children) { + $inner = $this.Measure($child) + $size += $inner[0] + $deepest = [Math]::Max($deepest, $inner[1]) + } + $result = [int[]]@($size, ($deepest + 1)) # parenthesised: a comma binds before + + $this.Measured[$value] = $result + return $result + } + + # A node as a value: a scalar typed (by its tag, or by the core schema when plain), a + # collection checked against its tag, and its anchor set. + [object] Finish([object]$props, [object]$node) { + $value = $null + if ($node -is [LdoYamlScalar]) { + $value = $this.ScalarValue($node, $props) + } + else { + $value = $this.CollectionValue($node, $props) + } + if ($null -ne $props -and $props.Anchor.Length -gt 0) { + $this.Anchors[$props.Anchor] = $value + [void]$this.Open.Remove($props.Anchor) + } + return $value + } + + [object] CollectionValue([object]$node, [object]$props) { + $tag = if ($null -ne $props) { $props.Tag } else { '' } + $isMap = $node -is [System.Collections.IDictionary] + if ($tag.Length -eq 0 -or [string]::Equals($tag, '!') -or ($isMap -and [string]::Equals($tag, '!!map')) -or + (-not $isMap -and [string]::Equals($tag, '!!seq'))) { + return $node + } + $kind = if ($isMap) { 'map' } else { 'list' } + $at = if ($null -ne $props) { $props.At } else { $this.Pos } + throw $this.Fail('tag-value', "the tag $tag on a $kind", $at, '', '') + } + + [object] ScalarValue([LdoYamlScalar]$scalar, [object]$props) { + $tag = if ($null -ne $props) { $props.Tag } else { '' } + if ([string]::Equals($tag, '!') -or [string]::Equals($tag, '!!str') -or ($tag.Length -eq 0 -and -not $scalar.Plain)) { + return $scalar.Text + } + $typed = [LdoYamlReader]::Core($scalar.Text) + $kind = [string]$typed[0] + if ([string]::Equals($kind, 'too-long')) { + throw $this.Fail('number', "a number of more than $([LdoYamlReader]::MaxDigits) digits", $scalar.At, '', '') + } + if ($tag.Length -eq 0) { return $typed[1] } + # An empty value has no place of its own, so an error about one points at its tag. + $given = 'nothing' + $at = $props.At + if ($scalar.Text.Length -gt 0) { + $given = [LdoYamlReader]::Repr($scalar.Text) + $at = $scalar.At + } + $wanted = $null + if (-not [LdoYamlReader]::TagKinds.TryGetValue($tag, [ref]$wanted)) { + throw $this.Fail('tag-value', "the tag $tag on $given", $at, '', '') + } + $parts = [LdoYamlReader]::Pair($wanted) + if ([Array]::IndexOf($parts[0].Split(' '), $kind) -lt 0) { + throw $this.Fail('tag-value', "the tag $tag on $given", $at, "that is not $($parts[1])", '') + } + # A whole number too big for a float is infinity, as 1e400 is. + if ([string]::Equals($tag, '!!float')) { return [double]$typed[1] } + return $typed[1] + } + + # The maps a << merges in: one, or a list of them. + [object[]] Merged([object]$value, [int]$at) { + [object[]]$sources = @(, $value) + if ($value -is [object[]]) { $sources = $value } + foreach ($source in $sources) { + if ($source -isnot [System.Collections.IDictionary]) { + throw $this.Fail('merge', 'a <<', $at, 'it merges in a map or a list of maps, nothing else', '') + } + } + return $sources + } + + # Warn of a key given again at $at, first given at $first. + [void] Duplicate([string]$key, [int]$first, [int]$at) { + $place = $this.Place($first) + $this.Note($at, 'warning', 'duplicate-key', + "the key `"$key`" again (first at line $($place[0]), column $($place[1])): YAML forbids it, and readers keep the last, as this does, or refuse the file") + } + + # Scalars --------------------------------------------------------------------------------- + + [LdoYamlScalar] BlockScalar([int]$parent) { + $at = $this.Pos + $folded = ($this.Padded[$this.Pos] -ceq [char]'>') + $this.Pos += 1 + $header = $this.BlockHeader() + $lines = [System.Collections.Generic.List[string]]::new() + $tail = $this.BlockLines($parent, [int]$header[1], $lines) + $body = '' + if ($lines.Count -gt 0) { + $body = if ($folded) { [LdoYamlReader]::Folded($lines) } else { [string]::Join("`n", $lines) } + } + $content = [LdoYamlReader]::Chomped($body, $lines.Count -gt 0, [bool]$tail[1], [int]$tail[0], [string]$header[0]) + return [LdoYamlScalar]::new($content, $false, $at) + } + + # A block's chomping indicator and indentation indicator, in either order. + [object[]] BlockHeader() { + $chomp = 'clip' + $explicit = 0 + for ($i = 0; $i -lt 2; $i++) { + $char = $this.Peek(0) + if ((($this.Padded[$this.Pos] -ceq [char]'+') -or ($this.Padded[$this.Pos] -ceq [char]'-')) -and [string]::Equals($chomp, 'clip')) { + $chomp = if (($this.Padded[$this.Pos] -ceq [char]'+')) { 'keep' } else { 'strip' } + } + elseif ($char.Length -eq 1 -and [int]$char[0] -ge 49 -and [int]$char[0] -le 57 -and $explicit -eq 0) { + $explicit = [int]$char[0] - 48 # 1 to 9 + } + elseif (($this.Padded[$this.Pos] -ceq [char]'0')) { + throw $this.Fail('not-yaml', 'not YAML: an indentation indicator of 0') + } + else { + break + } + $this.Pos += 1 + } + if (-not $this.LineEnds()) { + throw $this.Fail('not-yaml', 'not YAML: more on the line after a block''s | or >', $this.Pos, 'the block starts on the next line', '') + } + return @($chomp, $explicit) + } + + # A block's lines after its header, without the block's indent (empty ones empty), up to its + # last line of text, into $lines; gives how many empty lines follow that, and whether that + # last line ended with a line break. + [int[]] BlockLines([int]$parent, [int]$explicit, [System.Collections.Generic.List[string]]$lines) { + if ($this.Pos -ge $this.Text.Length) { return [int[]]@(0, 0) } + $start = $this.Pos + 1 + $indent = if ($explicit -gt 0) { [Math]::Max($parent, 0) + $explicit } else { $this.BlockIndent($start, $parent) } + $empty = 0 + $ended = 0 + $at = $start + while ($at -lt $this.Text.Length) { + $end = $this.LineEnd($at) + $line = $this.Text.Substring($at, $end - $at) + if ($line.Trim([char]' ').Length -eq 0 -and $line.Length -le $indent) { + if ($end -lt $this.Text.Length) { $empty++ } + } + elseif ([LdoYamlReader]::LeadingSpaces($line) -ge $indent) { + for ($i = 0; $i -lt $empty; $i++) { $lines.Add('') } + $lines.Add($line.Substring($indent)) + $empty = 0 + $ended = if ($end -lt $this.Text.Length) { 1 } else { 0 } + } + else { + break + } + $this.Pos = $end + $at = $end + 1 + } + return [int[]]@($empty, $ended) + } + + # A block's indent, from its first line of text. Empty lines before that may not be + # indented more. + [int] BlockIndent([int]$start, [int]$parent) { + $least = [Math]::Max($parent + 1, 1) + $widest = 0 + $at = $start + while ($at -lt $this.Text.Length) { + $end = $this.LineEnd($at) + $line = $this.Text.Substring($at, $end - $at) + if ($line.Trim([char]' ').Length -gt 0) { + $leading = [LdoYamlReader]::LeadingSpaces($line) + if ($leading -lt $least) { break } + if ($widest -gt $leading) { + throw $this.Fail('not-yaml', 'not YAML: a block''s first line of text', $at + $leading, 'an empty line before it is indented more', '') + } + return $leading + } + $widest = [Math]::Max($widest, $line.Length) + $at = $end + 1 + } + return [Math]::Max($least, $widest) + } + + [string] Quoted() { + if (($this.Padded[$this.Pos] -ceq [char]'"')) { return $this.DoubleQuoted() } + return $this.SingleQuoted() + } + + [string] DoubleQuoted() { + $start = $this.Pos + $this.Pos += 1 + $parts = [System.Text.StringBuilder]::new() + while ($true) { + $end = $this.EndOf([LdoYamlReader]::DoubleRun, $this.Pos) + $chunk = $this.Text.Substring($this.Pos, $end - $this.Pos) + $this.Pos = $end + if (($this.Padded[$this.Pos] -ceq [char]10)) { $chunk = $chunk.TrimEnd([char[]]@(' ', "`t")) } + [void]$parts.Append($chunk) + if (($this.Padded[$this.Pos] -ceq [char]'"')) { + $this.Pos += 1 + return $parts.ToString() + } + if (($this.Padded[$this.Pos] -ceq [char]'\')) { + [void]$parts.Append($this.Escape($start)) + } + elseif (($this.Padded[$this.Pos] -ceq [char]10)) { + [void]$parts.Append($this.QuotedBreak($start, $false)) + } + else { + throw $this.Unclosed($start) + } + } + return '' # never reached: the loop returns or throws + } + + [string] Escape([int]$start) { + $at = $this.Pos + $code = $this.Peek(1) + if (($this.Padded[$this.Pos + 1] -ceq [char]10)) { + $this.Pos += 1 + return $this.QuotedBreak($start, $true) + } + if ($code.Length -eq 0) { throw $this.Unclosed($start) } + $this.Pos += 2 + $escaped = $null + if ([LdoYamlReader]::Escapes.TryGetValue($code, [ref]$escaped)) { return $escaped } + if ([LdoYamlReader]::HexEscapes.ContainsKey($code)) { return $this.HexEscape($at, $code) } + throw $this.Fail('not-yaml', "not YAML: \$code is not an escape YAML has", $at, '', '') + } + + [string] HexEscape([int]$at, [string]$code) { + $digits = [int][LdoYamlReader]::HexEscapes[$code] + $written = $this.Slice($this.Pos, $this.Pos + $digits) + if ($written.Length -ne $digits -or -not [LdoYamlReader]::HexDigits.IsMatch($written)) { + throw $this.Fail('not-yaml', "not YAML: \$code needs $digits hex digits after it", $at, '', '') + } + $this.Pos += $digits + $value = [System.Convert]::ToInt64($written, 16) + if ($value -gt 0x10FFFF) { throw $this.Fail('not-yaml', "not YAML: \$code$written is past Unicode", $at, '', '') } + # A surrogate written alone (\ud83d) is kept alone, and two side by side make a pair. + if ($value -le 0xFFFF) { return [string][char][int]$value } + return [char]::ConvertFromUtf32([int]$value) + } + + # The line breaks inside a quoted string, from here: one becomes a space, and each empty line + # after it a line break. After a backslash, the first is dropped. + [string] QuotedBreak([int]$start, [bool]$escaped) { + $breaks = 0 + while (($this.Padded[$this.Pos] -ceq [char]10)) { + $this.Pos += 1 + $breaks++ + if ($this.Marker()) { throw $this.Unclosed($start) } + $this.SkipSpaces() + } + if ($this.Pos -ge $this.Text.Length) { throw $this.Unclosed($start) } + if ($escaped -or $breaks -gt 1) { return [string]::new([char]10, $breaks - 1) } + return ' ' + } + + [string] SingleQuoted() { + $start = $this.Pos + $this.Pos += 1 + $parts = [System.Text.StringBuilder]::new() + while ($true) { + $end = $this.EndOf([LdoYamlReader]::SingleRun, $this.Pos) + $chunk = $this.Text.Substring($this.Pos, $end - $this.Pos) + $this.Pos = $end + if (($this.Padded[$this.Pos] -ceq [char]10)) { + [void]$parts.Append($chunk.TrimEnd([char[]]@(' ', "`t"))) + [void]$parts.Append($this.QuotedBreak($start, $false)) + } + elseif (($this.Padded[$this.Pos] -ceq [char]"'") -and ($this.Padded[$this.Pos + 1] -ceq [char]"'")) { + [void]$parts.Append($chunk).Append("'") + $this.Pos += 2 + } + elseif (($this.Padded[$this.Pos] -ceq [char]"'")) { + $this.Pos += 1 + return $parts.Append($chunk).ToString() + } + else { + throw $this.Unclosed($start) + } + } + return '' # never reached: the loop returns or throws + } + + [LdoYamlError] Unclosed([int]$start) { + return $this.Fail('unclosed-quote', 'not YAML: the quoted string', $start, 'it never closes', '') + } + + # Plain text, over as many lines as continue it: a line break between lines becomes a + # space, and each empty line between them a line break. + [string] Plain([int]$parent, [bool]$flow) { + $startPattern = if ($flow) { [LdoYamlReader]::PlainStartFlow } else { [LdoYamlReader]::PlainStartBlock } + if (-not $startPattern.Match($this.Text, $this.Pos).Success) { throw $this.CannotStart() } + $found = $this.PlainLine($flow) + while ($true) { + $back = $this.Pos + $breaks = $this.PlainContinues($parent, $flow) + if ($breaks -eq 0) { + $this.Pos = $back + return $found + } + if ($breaks -eq 1) { $found += ' ' } else { $found += [string]::new([char]10, $breaks - 1) } + $found += $this.PlainLine($flow) + } + return '' # never reached: the loop returns + } + + [string] PlainLine([bool]$flow) { + $pattern = if ($flow) { [LdoYamlReader]::PlainFlow } else { [LdoYamlReader]::PlainBlock } + $end = $this.EndOf($pattern, $this.Pos) + $line = $this.Text.Substring($this.Pos, $end - $this.Pos).TrimEnd([char[]]@(' ', "`t")) + $this.Pos += $line.Length + return $line + } + + # How many line breaks there are before the line that continues plain text, moving to that + # line's text; 0 when the text does not continue. + [int] PlainContinues([int]$parent, [bool]$flow) { + $this.SkipSpaces() + $breaks = 0 + $indent = 0 + while (($this.Padded[$this.Pos] -ceq [char]10)) { + $this.Pos += 1 + $breaks++ + if ($this.Marker()) { return 0 } + $lineStart = $this.Pos + $this.SkipSpaces() + $indent = [LdoYamlReader]::LeadingSpaces($this.Text.Substring($lineStart, $this.Pos - $lineStart)) + } + if ($this.Pos -ge $this.Text.Length -or ($this.Padded[$this.Pos] -ceq [char]'#')) { return 0 } + $ends = $false + if ($flow) { + $ends = $this.OneOf(0, ',[]{}') -or $this.ColonAt($this.Pos) + } + else { + $ends = $indent -le $parent -or $this.KeyAhead() + } + if ($ends) { return 0 } + return $breaks + } + + [LdoYamlError] CannotStart() { + $found = $null + if (-not [LdoYamlReader]::CannotStartWhy.TryGetValue($this.Peek(0), [ref]$found)) { $found = 'no value here|' } + $parts = [LdoYamlReader]::Pair($found) + return $this.Fail('not-yaml', "not YAML: $($parts[0])", $this.Pos, $parts[1], '') + } + + [void] RefuseExplicitKey() { + if (($this.Padded[$this.Pos] -ceq [char]'?') -and $this.Blank(1)) { + throw $this.Fail('complex-key', 'an explicit key (?)', $this.Pos, [LdoYamlReader]::KeyWhy, '') + } + } + + # Flow collections ------------------------------------------------------------------------ + + [object] FlowCollection() { + try { + $start = $this.Pos + $this.Enter() + $this.Pos += 1 + $collection = $null + if ($this.Text[$start] -ceq [char]'[') { $collection = $this.FlowSequence($start) } else { $collection = $this.FlowMapping($start) } + $this.Depth-- + return $collection + } + catch { + $this.Keep($_.Exception) + return $null + } + } + + [object[]] FlowSequence([int]$start) { + $items = [System.Collections.Generic.List[object]]::new() + while ($this.FlowMore($start, ']')) { + $at = $this.Pos + $node = $this.FlowNode($start, ']') + if ($null -ne $this.Failure) { return $null } + if ($this.FlowColon($node, $start, ']')) { + $key = $this.FlowKey($node, $at) + $this.Pos += 1 + $pair = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + $pair[$key] = $this.FlowValue($start, ']') + if ($null -ne $this.Failure) { return $null } + $items.Add($pair) + } + elseif ($node.Explicit) { + $pair = [System.Collections.Specialized.OrderedDictionary]::new([System.StringComparer]::Ordinal) + $pair[$this.FlowKey($node, $at)] = $null + $items.Add($pair) + } + else { + $items.Add($node.Value) + } + $this.FlowSeparator($start, ']') + } + return $items.ToArray() + } + + [System.Collections.Specialized.OrderedDictionary] FlowMapping([int]$start) { + $entries = [LdoYamlEntries]::new($this) + while ($this.FlowMore($start, '}')) { + $at = $this.Pos + $node = $this.FlowNode($start, '}') + if ($null -ne $this.Failure) { return $null } + $key = $this.FlowKey($node, $at) + $value = $null + if ($this.FlowColon($node, $start, '}')) { + $this.Pos += 1 + $value = $this.FlowValue($start, '}') + if ($null -ne $this.Failure) { return $null } + } + $entries.Add($key, $node.Plain, $value, $at) + $this.FlowSeparator($start, '}') + } + return $entries.Build() + } + + # Whether another entry follows, past spaces and comments; false once close is read. + [bool] FlowMore([int]$start, [string]$close) { + $this.FlowSpace($start, $close) + if (($this.Padded[$this.Pos] -ceq $close[0])) { + $this.Pos += 1 + return $false + } + return $true + } + + [void] FlowSeparator([int]$start, [string]$close) { + $this.FlowSpace($start, $close) + if (($this.Padded[$this.Pos] -ceq [char]',')) { + $this.Pos += 1 + } + elseif (-not ($this.Padded[$this.Pos] -ceq $close[0])) { + throw $this.Fail('not-yaml', "not YAML: no , or $close after a value") + } + } + + [void] FlowSpace([int]$start, [string]$close) { + if (-not $this.NextContent($true) -or $this.Marker()) { + throw $this.Fail('not-yaml', "not YAML: the $($this.Text[$start]) never closed by $close", $start, '', '') + } + } + + # Whether a ':' follows the node, making it a key: with a space after it, or right after a + # quoted string or collection, as JSON writes one. + [bool] FlowColon([LdoYamlFlow]$node, [int]$start, [string]$close) { + $this.FlowSpace($start, $close) + if (-not ($this.Padded[$this.Pos] -ceq [char]':')) { return $false } + return $node.JsonLike -or $this.Blank(1) -or $this.OneOf(1, ',[]{}') + } + + [string] FlowKey([LdoYamlFlow]$node, [int]$at) { + if (-not $node.HasKey) { throw $this.Fail('complex-key', $node.Why, $at, [LdoYamlReader]::KeyWhy, '') } + return $node.Key + } + + [object] FlowValue([int]$start, [string]$close) { + $this.FlowSpace($start, $close) + if (($this.Padded[$this.Pos] -ceq [char]',') -or ($this.Padded[$this.Pos] -ceq $close[0])) { return $null } + return $this.FlowNode($start, $close).Value + } + + [LdoYamlFlow] FlowNode([int]$start, [string]$close) { + $at = $this.Pos + $props = $this.Properties($null) + if ($null -ne $props) { + $this.FlowSpace($start, $close) + if (($this.Padded[$this.Pos] -ceq [char]',') -or ($this.Padded[$this.Pos] -ceq $close[0]) -or $this.ColonAt($this.Pos)) { + return [LdoYamlFlow]::new($this.Finish($props, [LdoYamlScalar]::new('', $true, $at)), 'an anchor or tag on a key') + } + } + if (($this.Padded[$this.Pos] -ceq [char]'?') -and $null -eq $props -and ($this.Blank(1) -or ($this.Padded[$this.Pos + 1] -ceq [char]',') -or ($this.Padded[$this.Pos + 1] -ceq $close[0]))) { + $question = $this.Pos + $this.Pos += 1 + $this.FlowSpace($start, $close) + if (($this.Padded[$this.Pos] -ceq [char]',') -or ($this.Padded[$this.Pos] -ceq $close[0])) { + throw $this.Fail('complex-key', [LdoYamlReader]::NoKey, $question, [LdoYamlReader]::KeyWhy, '') + } + $node = $this.FlowNode($start, $close) + $node.Explicit = $true + return $node + } + if (($this.Padded[$this.Pos] -ceq [char]'*')) { + return [LdoYamlFlow]::new($this.AliasWith($props), 'an alias as a key') + } + if (($this.Padded[$this.Pos] -ceq [char]'[') -or ($this.Padded[$this.Pos] -ceq [char]'{')) { + $node = [LdoYamlFlow]::new($this.Finish($props, $this.FlowCollection()), 'a list or map as a key') + $node.JsonLike = $true + return $node + } + return $this.FlowScalar($props, $at) + } + + [LdoYamlFlow] FlowScalar([object]$props, [int]$at) { + $quoted = ($this.Padded[$this.Pos] -ceq [char]'"') -or ($this.Padded[$this.Pos] -ceq [char]"'") + $scalar = $null + if ($quoted) { + $scalar = [LdoYamlScalar]::new($this.Quoted(), $false, $at) + } + else { + $this.RefuseExplicitKey() + $scalar = [LdoYamlScalar]::new($this.Plain(-1, $true), $true, $at) + } + $node = [LdoYamlFlow]::new($this.Finish($props, $scalar), 'an anchor or tag on a key') + $node.HasKey = $null -eq $props + $node.Key = $scalar.Text + $node.Plain = $scalar.Plain + $node.JsonLike = $quoted + return $node + } + + # Where reading is ------------------------------------------------------------------------ + + # The character ahead of where reading has reached, as text; empty past the end. + [string] Peek([int]$ahead) { + $at = $this.Pos + $ahead + if ($at -ge $this.Text.Length) { return '' } + return [string]$this.Text[$at] + } + + # Whether the character ahead is one of $chars. + [bool] OneOf([int]$ahead, [string]$chars) { + return $chars.IndexOf($this.Padded[$this.Pos + $ahead]) -ge 0 + } + + # Whether what is ahead may follow an indicator (- : --- ...): a space, a tab, a line break + # or the end. + [bool] Blank([int]$ahead) { + return "`0 `t`n".IndexOf($this.Padded[$this.Pos + $ahead]) -ge 0 + } + + # The text from start to end, as much of it as there is. + [string] Slice([int]$start, [int]$end) { + $end = [Math]::Min($end, $this.Text.Length) + if ($start -ge $end) { return '' } + return $this.Text.Substring($start, $end - $start) + } + + [int] EndOf([regex]$pattern, [int]$at) { + $found = $pattern.Match($this.Text, $at) + if ($found.Success) { return $found.Index + $found.Length } + return $at + } + + [int] LineEnd([int]$at) { + $end = $this.Text.IndexOf([char]10, $at) + if ($end -lt 0) { return $this.Text.Length } + return $end + } + + # How far into its line an offset is, from 0, in UTF-16 code units: only spaces and + # indicators come before where it counts (an indent), so a pair of surrogates never does. + [int] Column([int]$at) { + $index = [Array]::BinarySearch($this.Starts, $at) + if ($index -lt 0) { $index = (-bnot $index) - 1 } + return $at - $this.Starts[$index] + } + + # Whether an offset starts a line: Column's 0, without the search. + [bool] LineStart([int]$at) { + return $at -eq 0 -or $this.Text[$at - 1] -ceq [char]10 + } + + [int] LineIndex([int]$at) { + $index = [Array]::BinarySearch($this.Starts, $at) + if ($index -ge 0) { return $index } + return (-bnot $index) - 1 + } + + # An offset as a line and column, from 1, the column in characters (a pair of surrogates is + # one), as Python counts them. + [int[]] Place([int]$at) { + $line = $this.LineIndex($at) + $start = $this.Starts[$line] + $column = $at - $start + 1 + if ($this.Astral) { + for ($i = $start + 1; $i -lt $at; $i++) { + if ([char]::IsLowSurrogate($this.Text[$i]) -and [char]::IsHighSurrogate($this.Text[$i - 1])) { $column-- } + } + } + return [int[]]@(($line + 1), $column) # parenthesised: a comma binds before + + } + + # Spaces is anchored with \G and matches nothing at worst, so its length is how far to move. + [void] SkipSpaces() { + $this.Pos += [LdoYamlReader]::Spaces.Match($this.Text, $this.Pos).Length + } + + # Whether nothing but spaces and a comment is left on this line, moving past them. + [bool] LineEnds() { + $this.Pos += [LdoYamlReader]::Spaces.Match($this.Text, $this.Pos).Length # SkipSpaces, inline + if (($this.Padded[$this.Pos] -ceq [char]'#') -and ($this.Pos -eq 0 -or " `t`n".IndexOf($this.Text[$this.Pos - 1]) -ge 0)) { + $this.Pos = $this.LineEnd($this.Pos) + } + return $this.Pos -ge $this.Text.Length -or ($this.Padded[$this.Pos] -ceq [char]10) + } + + # Move past spaces, comments and line breaks to the next content; false at the end. In block + # style a tab before content at the start of a line is refused. + [bool] NextContent([bool]$flow) { + while ($true) { + $start = $this.Pos + if (-not $this.LineEnds()) { + if (-not $flow -and ($start -eq 0 -or $this.Text[$start - 1] -ceq [char]10)) { + $tab = $this.Text.IndexOf([char]9, $start, $this.Pos - $start) + if ($tab -ge 0) { + throw $this.Fail('tab-indent', 'not YAML: a tab in the indentation', $tab, '', 'YAML indents with spaces only') + } + } + return $true + } + if ($this.Pos -ge $this.Text.Length) { return $false } + $this.Pos += 1 + } + return $false # never reached: the loop returns + } + + # --- or ... when one starts here, at the start of a line; else empty. + [string] Marker() { + $first = $this.Padded[$this.Pos] + if (($first -cne [char]'-' -and $first -cne [char]'.') -or -not $this.LineStart($this.Pos)) { return '' } + $mark = $this.Slice($this.Pos, $this.Pos + 3) + if (-not [string]::Equals($mark, '---') -and -not [string]::Equals($mark, '...')) { return '' } + if ($this.Blank(3)) { return $mark } + return '' + } + + [bool] AtDash() { + return ($this.Padded[$this.Pos] -ceq [char]'-') -and $this.Blank(1) + } + + [bool] ColonAt([int]$at) { + return $at -lt $this.Text.Length -and $this.Text[$at] -ceq [char]':' -and + ($at + 1 -ge $this.Text.Length -or " `t`n".IndexOf($this.Text[$at + 1]) -ge 0) + } + + # Whether a key and its colon start here, on this line: plain or quoted text. + [bool] KeyAhead() { + if (($this.Padded[$this.Pos] -ceq [char]'"') -or ($this.Padded[$this.Pos] -ceq [char]"'")) { + $end = $this.QuoteEnd($this.Pos) + return $end -ge 0 -and $this.ColonAt($this.EndOf([LdoYamlReader]::Spaces, $end)) + } + if (-not [LdoYamlReader]::PlainStartBlock.Match($this.Text, $this.Pos).Success) { return $false } + $end = $this.EndOf([LdoYamlReader]::PlainBlock, $this.Pos) + return $end -lt $this.Text.Length -and $this.Text[$end] -ceq [char]':' + } + + # Just past the closing quote of the string opening at $at, if it closes on its own line; + # else -1. + [int] QuoteEnd([int]$at) { + $quote = $this.Text[$at] + $at++ + while ($at -lt $this.Text.Length) { + $char = $this.Text[$at] + if ($char -ceq [char]10) { return -1 } + if ($char -ceq [char]'\' -and $quote -ceq [char]'"') { + if ($at + 1 -lt $this.Text.Length -and $this.Text[$at + 1] -ceq [char]10) { $at += 1 } else { $at += 2 } + continue + } + if ($char -ceq $quote -and $quote -ceq [char]"'" -and $at + 1 -lt $this.Text.Length -and $this.Text[$at + 1] -ceq [char]"'") { + $at += 2 + continue + } + if ($char -ceq $quote) { return $at + 1 } + $at++ + } + return -1 + } + + [string] AnchorName() { + $end = $this.EndOf([LdoYamlReader]::NamePattern, $this.Pos) + $name = $this.Text.Substring($this.Pos, $end - $this.Pos) + $this.Pos = $end + return $name + } + + [void] Note([int]$at, [string]$severity, [string]$rule, [string]$message) { + $place = $this.Place($at) + $this.Notes.Add([LdoYamlNote]::new($place[0], $place[1], $severity, $rule, $message)) + } + + # The error for what was found where reading has reached. + [LdoYamlError] Fail([string]$rule, [string]$what) { + return $this.Fail($rule, $what, $this.Pos, '', '') + } + + # The error for what was found at $at, why it cannot be, and what to do about it. + [LdoYamlError] Fail([string]$rule, [string]$what, [int]$at, [string]$why, [string]$hint) { + $place = $this.Place($at) + $message = "$what at line $($place[0]), column $($place[1])" + if ($why.Length -gt 0) { $message += ": $why" } + return [LdoYamlError]::new($message, $place[0], $place[1], $rule, $hint) + } +} + +function Read-LdoYamlFile { + # Internal: a file's text, decoded as UTF-8 strictly. + [OutputType([string])] + param([Parameter(Mandatory)][string]$Path) + + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "no such file: $Path" } + try { + $bytes = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $Path).ProviderPath) + return [System.Text.UTF8Encoding]::new($false, $true).GetString($bytes) + } + catch { + throw "cannot read ${Path}: $($_.Exception.Message)" + } +} + +function Read-LdoYamlDocument { + # Internal: the documents in some YAML text, each warning logged as "label:line:column: + # message". An error names the label, the line and column, and what to do, if anything. + [OutputType([object[]])] + param( + [Parameter(Mandatory)][AllowEmptyString()][string]$Text, + [Parameter(Mandatory)][string]$Label + ) + + try { + $parsed = [LdoYamlReader]::Parse($Text) + } + catch { + $cause = [LdoYamlReader]::Cause($_.Exception) + if ($cause -isnot [LdoYamlError]) { throw } + $message = "${Label}: $($cause.Message)" + if ($cause.Hint) { $message += " ($($cause.Hint))" } + throw [LdoYamlError]::new($message, $cause.Line, $cause.Column, $cause.Rule, $cause.Hint) + } + foreach ($note in $parsed.Notes) { + Write-LdoLog -Level WARN -Message "${Label}:$($note.Line):$($note.Column): $($note.Message)" + } + return , [object[]]$parsed.Documents +} + +function Read-LdoYamlSource { + # Internal: each document in a YAML file, or in text, written whole: a document that is a + # list is not unrolled into its items. + [OutputType([object])] + param( + [AllowEmptyString()][string]$Path, + [AllowEmptyString()][string]$Content, + [Parameter(Mandatory)][string]$Label + ) + + $text = if ($Path) { Read-LdoYamlFile -Path $Path } else { $Content } + foreach ($document in (Read-LdoYamlDocument -Text $text -Label $Label)) { , $document } +} + +function Get-LdoYamlValue { + <# + .SYNOPSIS + Gets values out of YAML by path, with nothing installed, read as YAML 1.2 reads it. + + .DESCRIPTION + Reads YAML and returns what a path names in each document: jobs.build.steps, steps[0], + steps[-1] (the last), steps[].name (each step's), ["key.with.dots"] for a key a plain + name cannot spell, or . for all of it. A string comes back as it is, a map as an + ordered, case-sensitive dictionary and a list as an array, so a value pipes on as + ConvertFrom-LdoJson's would. + + The YAML is read by this module, with no yq or powershell-yaml, as YAML 1.2 reads it: + yes, on, 12:30 and 2026-09-24 stay strings and 010 is ten, as yq and Terraform read + them, where YAML 1.1 (PyYAML, Ansible) makes booleans, numbers and dates of them. + Anchors, aliases and << merges are filled in. A custom tag (!Ref, !reference), a tab + in the indentation, a key that is not text, a YAML bomb and nesting past 100 are + refused, naming the line and column. A key given twice is a warning, and the last is + kept. + + The twin of the ldo CLI's ldo yaml get: both read YAML, and paths, the same way, by + the same shared cases. + + .PARAMETER Path + A YAML file, of one document or several. + + .PARAMETER Content + YAML text. + + .PARAMETER Field + The path to get, such as spec.template.spec.containers[].image. + + .PARAMETER Detailed + Return each value with the path that names it alone (jobs[1].name), and its file, + instead of the values alone. + + .EXAMPLE + Get-LdoYamlValue -Path ./deploy.yaml -Field 'spec.template.spec.containers[].image' + + .EXAMPLE + Get-LdoYamlValue -Path ./.gitlab-ci.yml -Field 'build.script' -Detailed + + .OUTPUTS + System.Object + #> + [CmdletBinding(DefaultParameterSetName = 'Path')] + [OutputType([object])] + param( + [Parameter(Mandatory, ParameterSetName = 'Path', Position = 0)][ValidateNotNullOrEmpty()][string]$Path, + [Parameter(Mandatory, ParameterSetName = 'Content')][AllowEmptyString()][string]$Content, + [Parameter(Mandatory, Position = 1)][ValidateNotNull()][string]$Field, + [switch]$Detailed + ) + + $label = if ($PSCmdlet.ParameterSetName -eq 'Path') { $Path } else { 'content' } + # Paths are Get-LdoJsonValue's. Every command's begin runs before the first in a pipeline + # writes anything, so it refuses a path it cannot read before the YAML is read, as ldo yaml + # get does; and each value comes back whole. + Read-LdoYamlSource -Path $Path -Content $Content -Label $label | Get-LdoJsonValue -Field $Field -Detailed:$Detailed | ForEach-Object { + if ($Detailed) { + $_.File = $label + $_ + } + else { + $PSCmdlet.WriteObject($_, $false) + } + } +} diff --git a/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 b/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 index 6357a3e..49bcdc2 100644 --- a/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 +++ b/LibreDevOpsHelpers/LibreDevOpsHelpers.psd1 @@ -207,6 +207,7 @@ 'Get-LdoTerraformStackFolders', 'Get-LdoTraceContext', 'Get-LdoUvPython', + 'Get-LdoYamlValue', 'Initialize-LdoVenv', 'Install-LdoAzureCli', 'Install-LdoCheckov', diff --git a/README.md b/README.md index 848f4f2..e2aa136 100644 --- a/README.md +++ b/README.md @@ -117,8 +117,18 @@ Merge-LdoJson -Path ./base.json, ./prod.json -Changes | Format-Table Path, Chang - `ConvertTo-LdoYaml` writes block-style YAML, quoting only what a YAML 1.1 or 1.2 reader could read as something else (`yes`, `12:30`, `2026-09-24`, `0x1F`), and keeping a multi-line string's ending exactly (`|-`, `|` or `|+`). It writes what `ldo json show --yaml` writes. +- `Get-LdoYamlValue` gets values out of YAML by the same paths as `Get-LdoJsonValue`, with + nothing installed. It reads YAML as YAML 1.2 does, as yq and Terraform do (`yes`, `12:30` and + `2026-09-24` stay strings, `010` is ten), fills in anchors and `<<` merges, and refuses a custom + tag such as `!reference`, naming the line and column. It reads what `ldo yaml get` reads. - `ConvertFrom-LdoYaml` reads YAML through yq, or the powershell-yaml module +```powershell +# Every image a deployment runs, and each job's script after its anchors are filled in. +Get-LdoYamlValue -Path ./deploy.yaml -Field 'spec.template.spec.containers[].image' +Get-LdoYamlValue -Path ./.gitlab-ci.yml -Field 'build.script' -Detailed +``` + ### Graph Resilient Microsoft Graph and Azure REST helpers. - `Invoke-LdoWithRetry`, `Invoke-LdoGraphRequest`, `Get-LdoGraphToken`, `Clear-LdoGraphTokenCache`, diff --git a/tests/README.md b/tests/README.md index abb8218..2d544dc 100644 --- a/tests/README.md +++ b/tests/README.md @@ -29,7 +29,7 @@ Invoke-Pester ./tests/Logger.Tests.ps1 `tests/shared` holds cases the ldo CLI's tests run too, so the two agree exactly rather than roughly: reading and repairing JSON (`json.json`), field paths (`paths.json`), merging -(`merge.json`) and writing YAML (`yaml.json`). They are copied from ldo-cli's +(`merge.json`), writing YAML (`yaml-write.json`) and reading it (`yaml-read.json`). They are copied from ldo-cli's `tests/fakes/shared`, which is where they change; copy them here again after a change, and never edit them only here. diff --git a/tests/Yaml.Tests.ps1 b/tests/Yaml.Tests.ps1 index 4f7b5b4..0c70221 100644 --- a/tests/Yaml.Tests.ps1 +++ b/tests/Yaml.Tests.ps1 @@ -1,9 +1,13 @@ BeforeDiscovery { Import-Module (Join-Path $PSScriptRoot '..' 'LibreDevOpsHelpers' 'LibreDevOpsHelpers.psd1') -Force - # The shared cases (tests/shared, copied from ldo-cli): the ldo CLI writes the same YAML. - $script:yamlCases = foreach ($case in (ConvertFrom-LdoJson -Path (Join-Path $PSScriptRoot 'shared' 'yaml.json')).cases) { - @{ Name = $case.name; Case = $case } + # The shared cases (tests/shared, copied from ldo-cli): the ldo CLI writes the same YAML, + # and reads YAML the same way. + function Get-SharedCase([string]$Name) { + $file = Join-Path $PSScriptRoot 'shared' "$Name.json" + foreach ($case in (ConvertFrom-LdoJson -Path $file).cases) { @{ Name = $case.name; Case = $case } } } + $script:writeCases = @(Get-SharedCase yaml-write) + $script:readCases = @(Get-SharedCase yaml-read) $script:yamlReady = [bool](Get-Command yq -ErrorAction SilentlyContinue) -or [bool](Get-Module -ListAvailable powershell-yaml) } @@ -11,10 +15,51 @@ BeforeDiscovery { BeforeAll { $manifest = Join-Path $PSScriptRoot '..' 'LibreDevOpsHelpers' 'LibreDevOpsHelpers.psd1' Import-Module $manifest -Force + + # A value as the reading cases compare it: key order kept, numbers by value, true never 1, + # and a whole number never a float, since YAML types 10 and 10.0 apart. + function ConvertTo-TypedShape($Value) { + if ($null -eq $Value) { return 'null' } + if ($Value -is [bool]) { return "b:$Value" } + if ($Value -is [string]) { return 's:' + ($Value | ConvertTo-Json -Compress) } + if ($Value -is [System.Collections.IDictionary]) { + $parts = foreach ($key in $Value.Keys) { ($key | ConvertTo-Json -Compress) + '=' + (ConvertTo-TypedShape $Value[$key]) } + return '{' + ($parts -join ',') + '}' + } + if ($Value -is [System.Collections.IList]) { + $parts = foreach ($item in $Value) { ConvertTo-TypedShape $item } + return '[' + ($parts -join ',') + ']' + } + if ($Value -is [double]) { + if ($Value -eq 0) { return 'f:0' } # -0.0 is 0.0, as Python compares them + return 'f:' + $Value.ToString('R', [cultureinfo]::InvariantCulture) + } + return 'i:' + $Value.ToString() + } + + # What reading the text gives, in the cases' terms: the documents and the notes (each + # line:column:severity:rule), or the error as "rule line:column", or empty. + function Get-ReadOutcome([string]$Text) { + $yaml = (Get-Module LibreDevOpsHelpers).NestedModules | Where-Object Name -EQ 'LibreDevOpsHelpers.Yaml' + & $yaml { + param($Text) + try { + $parsed = [LdoYamlReader]::Parse($Text) + $notes = @(foreach ($note in $parsed.Notes) { "$($note.Line):$($note.Column):$($note.Severity):$($note.Rule)" }) + [pscustomobject]@{ Documents = $parsed.Documents; Notes = $notes; Failure = $null } + } + catch { + $cause = [LdoYamlReader]::Cause($_.Exception) + if ($cause -isnot [LdoYamlError]) { throw } + $failure = if ([string]::Equals($cause.Rule, 'empty')) { 'empty' } else { "$($cause.Rule) $($cause.Line):$($cause.Column)" } + [pscustomobject]@{ Documents = $null; Notes = @(); Failure = $failure } + } + } $Text + } } Describe 'Yaml module surface' { - It 'exports the expected commands' -ForEach @('ConvertTo-LdoYaml', 'ConvertFrom-LdoYaml') { + It 'exports the expected commands' -ForEach @('ConvertTo-LdoYaml', 'ConvertFrom-LdoYaml', 'Get-LdoYamlValue') { Get-Command $_ -ErrorAction SilentlyContinue | Should -Not -BeNullOrEmpty } } @@ -104,7 +149,7 @@ Describe 'ConvertTo-LdoYaml' { } Describe 'Shared cases: writing YAML' { - It '' -ForEach $yamlCases { + It '' -ForEach $writeCases { $written = ConvertFrom-LdoJson -Content $Case.json | ConvertTo-LdoYaml # Ordinal: Should -BeExactly, like -ceq, takes control characters for nothing. [string]::Equals($written, $Case.yaml) | Should -BeTrue -Because "it wrote:`n$written`nand the case wants:`n$($Case.yaml)" @@ -134,3 +179,110 @@ Describe 'ConvertTo-LdoYaml quoting' { } } +Describe 'Shared cases: reading YAML' { + It '' -ForEach $readCases { + $found = Get-ReadOutcome $Case.text + if ($Case.Contains('error')) { + $wanted = if ([string]::Equals($Case.error.rule, 'empty')) { 'empty' } else { "$($Case.error.rule) $($Case.error.line):$($Case.error.column)" } + $found.Failure | Should -BeExactly $wanted + return + } + $found.Failure | Should -BeNullOrEmpty + $notes = @(foreach ($note in $Case.notes) { "$($note[0]):$($note[1]):$($note[2]):$($note[3])" }) + ($found.Notes -join ' ') | Should -BeExactly ($notes -join ' ') + # Ordinal throughout: Should -BeExactly, like -ceq, takes control characters for nothing. + if ($Case.Contains('written')) { + # What JSON cannot hold (.inf, .nan) is compared as the YAML written for it. + $written = ($found.Documents | ForEach-Object { ConvertTo-LdoYaml -InputObject $_ }) -join "---`n" + [string]::Equals($written, $Case.written) | Should -BeTrue -Because "it wrote:`n$written`nand the case wants:`n$($Case.written)" + } + else { + $read = ConvertTo-TypedShape $found.Documents + $wanted = ConvertTo-TypedShape $Case.documents + [string]::Equals($read, $wanted) | Should -BeTrue -Because "it read:`n$read`nand the case wants:`n$wanted" + } + } +} + +Describe 'Reading YAML' { + # An error thrown deep inside used to unwind through every map and list it was in, and + # PowerShell runs out of stack doing that some 70 deep: the process ended. + It 'gives an error from 99 deep as itself: ' -ForEach @( + @{ Name = 'flow'; Text = ('[' * 99) + '!Ref x' + (']' * 99); Wanted = 'tag 1:100' } + @{ Name = 'block'; Text = (-join (0..98 | ForEach-Object { (' ' * $_) + "k:`n" })) + (' ' * 99) + "v: !Ref x`n"; Wanted = 'tag 100:103' } + ) { + (Get-ReadOutcome $Text).Failure | Should -BeExactly $Wanted + } + + It 'gives the first error, not one met while leaving' { + (Get-ReadOutcome "a:`n - [!Ref x`n").Failure | Should -BeExactly 'tag 2:6' + } +} + +Describe 'Get-LdoYamlValue' { + BeforeAll { + $pipeline = Join-Path $TestDrive 'pipeline.yml' + $text = "# Shared by every job.`ndefaults: &defaults`n image: alpine:3`n retry: 2`njobs:`n" + + " - name: build`n <<: *defaults`n on: yes`n - name: test`n <<: *defaults`n retry: 0`n at: 12:30`n" + Set-Content -LiteralPath $pipeline -Value $text -NoNewline + } + + It 'gives text as it is, and values typed as YAML 1.2 types them' { + Get-LdoYamlValue -Path $pipeline -Field 'jobs[].name' | Should -Be @('build', 'test') + Get-LdoYamlValue -Path $pipeline -Field 'jobs[0].on' | Should -BeExactly 'yes' + Get-LdoYamlValue -Path $pipeline -Field 'jobs[1].at' | Should -BeExactly '12:30' + Get-LdoYamlValue -Path $pipeline -Field 'jobs[1].retry' | Should -BeOfType [long] + } + + It 'fills in merges, the map''s own keys winning' { + $job = Get-LdoYamlValue -Path $pipeline -Field 'jobs[-1]' + @($job.Keys) | Should -Be @('name', 'image', 'retry', 'at') + $job['retry'] | Should -Be 0 + } + + It 'gives a list whole, and looks in each document' { + $list = @(Get-LdoYamlValue -Content "a: [1, 2]`n" -Field a) + $list.Count | Should -Be 1 + $list[0].Count | Should -Be 2 + Get-LdoYamlValue -Content "kind: Service`n---`n- a`n---`nkind: Pod`n" -Field kind | Should -Be @('Service', 'Pod') + } + + It 'gives with -Detailed the path that names each value, and its file' { + $last = Get-LdoYamlValue -Path $pipeline -Field 'jobs[-1].name' -Detailed + $last.Path | Should -BeExactly 'jobs[1].name' + $last.File | Should -BeExactly $pipeline + $last.Value | Should -BeExactly 'test' + (Get-LdoYamlValue -Content "a: 1`n" -Field a -Detailed).File | Should -BeExactly 'content' + } + + It 'says what is there when nothing is' { + { Get-LdoYamlValue -Path $pipeline -Field 'defaults.stage' } | Should -Throw -ExpectedMessage 'nothing at defaults.stage: *' + } + + It 'refuses a custom tag, naming the file, the line and column, and why' { + $ci = Join-Path $TestDrive 'gitlab-ci.yml' + Set-Content -LiteralPath $ci -Value "build:`n script:`n - !reference [.a, b]`n" -NoNewline + { Get-LdoYamlValue -Path $ci -Field build } | + Should -Throw -ExpectedMessage "${ci}: the tag !reference at line 3, column 7: YAML 1.2's core schema has no such type (a custom tag, such as CloudFormation's !Ref or GitLab's !reference, *" + } + + It 'warns of a key given twice, with both places, and keeps the last' { + InModuleScope LibreDevOpsHelpers.Yaml { + Mock Write-LdoLog {} + Get-LdoYamlValue -Content "a: 1`nb: 2`na: 3`n" -Field a | Should -Be 3 + Should -Invoke Write-LdoLog -ParameterFilter { $Level -eq 'WARN' -and $Message -ceq 'content:3:1: the key "a" again (first at line 1, column 1): YAML forbids it, and readers keep the last, as this does, or refuse the file' } + } + } + + It 'refuses a path it cannot read, before reading anything' { + { Get-LdoYamlValue -Content "a: !Ref x`n" -Field 'a..b' } | Should -Throw -ExpectedMessage "cannot read the field path 'a..b' at character 2*" + } + + It 'refuses a file missing, not UTF-8, or holding no document' { + { Get-LdoYamlValue -Path (Join-Path $TestDrive 'none.yaml') -Field a } | Should -Throw -ExpectedMessage 'no such file:*' + $latin = Join-Path $TestDrive 'latin.yaml' + [System.IO.File]::WriteAllBytes($latin, [byte[]]@(0x61, 0x3A, 0x20, 0xE9, 0x0A)) + { Get-LdoYamlValue -Path $latin -Field a } | Should -Throw -ExpectedMessage "cannot read ${latin}:*" + { Get-LdoYamlValue -Content "# only this`n" -Field a } | Should -Throw -ExpectedMessage 'content: the input holds no document, only comments' + } +} diff --git a/tests/shared/yaml-read.json b/tests/shared/yaml-read.json new file mode 100644 index 0000000..d494518 --- /dev/null +++ b/tests/shared/yaml-read.json @@ -0,0 +1,1367 @@ +{ + "about": "Reading YAML: the Python package's core.yaml_reader and the PowerShell module's YAML reader. Each case gives YAML text and what reading it gives: the documents (as JSON, where a float is written with a point or an exponent, so it stays a float), or, when they hold .inf or .nan, which JSON cannot, the YAML core.yaml_text writes for them; and the notes, each [line, column, severity, rule]. A case that is refused gives the error's rule, line and column instead, or rule empty for a text with no document.", + "version": 1, + "cases": [ + { + "name": "core-nulls", + "text": "[null, Null, NULL, ~, '', nULL]\n", + "documents": [ + [ + null, + null, + null, + null, + "", + "nULL" + ] + ], + "notes": [] + }, + { + "name": "core-booleans", + "text": "[true, True, TRUE, false, False, FALSE, tRUE]\n", + "documents": [ + [ + true, + true, + true, + false, + false, + false, + "tRUE" + ] + ], + "notes": [] + }, + { + "name": "yaml-1.1-words-stay-strings", + "text": "[yes, no, on, off, y, n, Yes, NO, On]\n", + "documents": [ + [ + "yes", + "no", + "on", + "off", + "y", + "n", + "Yes", + "NO", + "On" + ] + ], + "notes": [] + }, + { + "name": "whole-numbers", + "text": "[0, -0, +1, 10, 010, -42, 0o17, 0x1f, 0xFF, 123456789012345678901234567890]\n", + "documents": [ + [ + 0, + 0, + 1, + 10, + 10, + -42, + 15, + 31, + 255, + 123456789012345678901234567890 + ] + ], + "notes": [] + }, + { + "name": "floats", + "text": "[1.5, .5, 1., -1.5e+3, 1e3, 2E-2, +0.0, -0.0, 0.1]\n", + "documents": [ + [ + 1.5, + 0.5, + 1.0, + -1500.0, + 1000.0, + 0.02, + 0.0, + -0.0, + 0.1 + ] + ], + "notes": [] + }, + { + "name": "non-finite", + "text": "[.inf, -.inf, +.inf, .Inf, .INF, .nan, .NaN, .NAN]\n", + "written": "- .inf\n- -.inf\n- .inf\n- .inf\n- .inf\n- .nan\n- .nan\n- .nan\n", + "notes": [] + }, + { + "name": "number-like-strings", + "text": "[1_000, 0b11, 0x, 0o8, 1:20, 12:30:00, inf, nan, .Nan, 1e, -.5.5, '1', \"2\"]\n", + "documents": [ + [ + "1_000", + "0b11", + "0x", + "0o8", + "1:20", + "12:30:00", + "inf", + "nan", + ".Nan", + "1e", + "-.5.5", + "1", + "2" + ] + ], + "notes": [] + }, + { + "name": "dates-stay-strings", + "text": "a: 2026-09-24\nb: 2026-09-24T10:00:00Z\nc: 10:30\n", + "documents": [ + { + "a": "2026-09-24", + "b": "2026-09-24T10:00:00Z", + "c": "10:30" + } + ], + "notes": [] + }, + { + "name": "tags", + "text": "a: !!str 123\nb: !!int \"42\"\nc: !!float 1\nd: !!bool 'true'\ne: !!null ''\nf: !!map {x: 1}\ng: !!seq [1]\nh: ! 5\n", + "documents": [ + { + "a": "123", + "b": 42, + "c": 1.0, + "d": true, + "e": null, + "f": { + "x": 1 + }, + "g": [ + 1 + ], + "h": "5" + } + ], + "notes": [] + }, + { + "name": "non-specific-tag", + "text": "[! 12, ! true, ! null]\n", + "documents": [ + [ + "12", + "true", + "null" + ] + ], + "notes": [] + }, + { + "name": "float-tag-past-the-largest-float", + "text": "- !!float 1e400\n- !!float 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\n- !!float -9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\n- !!float 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\n- !!float 10\n", + "written": "- .inf\n- .inf\n- -.inf\n- .inf\n- 10.0\n", + "notes": [] + }, + { + "name": "keys-as-written", + "text": "1: a\ntrue: b\n0x10: c\n~: d\n1.0: e\n", + "documents": [ + { + "1": "a", + "true": "b", + "0x10": "c", + "~": "d", + "1.0": "e" + } + ], + "notes": [] + }, + { + "name": "keys-quoted-and-plain", + "text": "a b: 1\na:b: 2\n\"q:\": 3\n'x y': 4\n-n: 5\n?x: 6\n:c: 7\n", + "documents": [ + { + "a b": 1, + "a:b": 2, + "q:": 3, + "x y": 4, + "-n": 5, + "?x": 6, + ":c": 7 + } + ], + "notes": [] + }, + { + "name": "duplicate-key", + "text": "a: 1\nb: 2\na: 3\n", + "documents": [ + { + "a": 3, + "b": 2 + } + ], + "notes": [ + [ + 3, + 1, + "warning", + "duplicate-key" + ] + ] + }, + { + "name": "duplicate-key-in-flow", + "text": "{a: 1, a: 2}\n", + "documents": [ + { + "a": 2 + } + ], + "notes": [ + [ + 1, + 8, + "warning", + "duplicate-key" + ] + ] + }, + { + "name": "explicit-keys", + "text": "? a\n: 1\n? |\n block key\n: 2\n? \"q\"\n:\n - x\n? plain\n key\n: 3\n? alone\n", + "documents": [ + { + "a": 1, + "block key\n": 2, + "q": [ + "x" + ], + "plain key": 3, + "alone": null + } + ], + "notes": [] + }, + { + "name": "explicit-key-in-flow", + "text": "{? a : 1, ? b}\n", + "documents": [ + { + "a": 1, + "b": null + } + ], + "notes": [] + }, + { + "name": "explicit-key-in-a-flow-list", + "text": "[? a : 1, ? b, c]\n", + "documents": [ + [ + { + "a": 1 + }, + { + "b": null + }, + "c" + ] + ], + "notes": [] + }, + { + "name": "nested-maps", + "text": "a:\n b:\n c: 1\n d: 2\ne: 3\n", + "documents": [ + { + "a": { + "b": { + "c": 1 + }, + "d": 2 + }, + "e": 3 + } + ], + "notes": [] + }, + { + "name": "lists", + "text": "- a\n- b: 1\n c: 2\n- - x\n - y\n- []\n", + "documents": [ + [ + "a", + { + "b": 1, + "c": 2 + }, + [ + "x", + "y" + ], + [] + ] + ], + "notes": [] + }, + { + "name": "compact-nesting", + "text": "- - - a\n - b\n - c\n- a: 1\n b:\n - x\n c: 2\n", + "documents": [ + [ + [ + [ + "a", + "b" + ], + "c" + ], + { + "a": 1, + "b": [ + "x" + ], + "c": 2 + } + ] + ], + "notes": [] + }, + { + "name": "list-at-key-indent", + "text": "a:\n- 1\n- 2\nb:\n - 3\nc: 4\n", + "documents": [ + { + "a": [ + 1, + 2 + ], + "b": [ + 3 + ], + "c": 4 + } + ], + "notes": [] + }, + { + "name": "indented-root", + "text": " a: 1\n b:\n c: 2\n", + "documents": [ + { + "a": 1, + "b": { + "c": 2 + } + } + ], + "notes": [] + }, + { + "name": "empty-values", + "text": "a:\nb: ~\nc: # nothing\nd: ''\ne:\n -\n - \n", + "documents": [ + { + "a": null, + "b": null, + "c": null, + "d": "", + "e": [ + null, + null + ] + } + ], + "notes": [] + }, + { + "name": "top-level-scalar", + "text": "just\n some\ntext\n", + "documents": [ + "just some text" + ], + "notes": [] + }, + { + "name": "top-level-list-of-maps", + "text": "- name: web\n port: 80\n- name: db\n port: 5432\n", + "documents": [ + [ + { + "name": "web", + "port": 80 + }, + { + "name": "db", + "port": 5432 + } + ] + ], + "notes": [] + }, + { + "name": "comments", + "text": "# top\na: 1 # after\n# between\nb: # empty value\n - x # item\n # inside\n - y\nc: 'q # not' # yes\nd: b#c\n", + "documents": [ + { + "a": 1, + "b": [ + "x", + "y" + ], + "c": "q # not", + "d": "b#c" + } + ], + "notes": [] + }, + { + "name": "flow-collections", + "text": "a: [1, # one\n 2,\n {b: c, d: [e, f]}, ]\nb: {x: 1,\n y: 2}\ne: []\nf: {}\n", + "documents": [ + { + "a": [ + 1, + 2, + { + "b": "c", + "d": [ + "e", + "f" + ] + } + ], + "b": { + "x": 1, + "y": 2 + }, + "e": [], + "f": {} + } + ], + "notes": [] + }, + { + "name": "flow-pairs-in-a-list", + "text": "[a: 1, b, 'c': 2]\n", + "documents": [ + [ + { + "a": 1 + }, + "b", + { + "c": 2 + } + ] + ], + "notes": [] + }, + { + "name": "flow-plain-text", + "text": "[a b, c:d, http://x.y/z, -1, ?x]\n", + "documents": [ + [ + "a b", + "c:d", + "http://x.y/z", + -1, + "?x" + ] + ], + "notes": [] + }, + { + "name": "flow-json-like-keys", + "text": "{\"j\":1, 'k':2, \"l\":[3]}\n", + "documents": [ + { + "j": 1, + "k": 2, + "l": [ + 3 + ] + } + ], + "notes": [] + }, + { + "name": "flow-key-with-no-value", + "text": "{a, b: 1, c}\n", + "documents": [ + { + "a": null, + "b": 1, + "c": null + } + ], + "notes": [] + }, + { + "name": "json-as-yaml", + "text": "{\"a\": [1, 2.5, -3e2, true, null], \"b\": {\"c\": \"d\\u00e9\\ud83d\\ude00\"}, \"e\": -0}\n", + "documents": [ + { + "a": [ + 1, + 2.5, + -300.0, + true, + null + ], + "b": { + "c": "dé😀" + }, + "e": 0 + } + ], + "notes": [] + }, + { + "name": "json-with-tabs", + "text": "{\n\t\"a\": [1,\n\t\t2]\n}\n", + "documents": [ + { + "a": [ + 1, + 2 + ] + } + ], + "notes": [] + }, + { + "name": "plain-multi-line", + "text": "a: one\n two\n\n three\nb:\n - item one\n continued\n - two\n", + "documents": [ + { + "a": "one two\nthree", + "b": [ + "item one continued", + "two" + ] + } + ], + "notes": [] + }, + { + "name": "plain-spaces-and-colons", + "text": "a: x:y z\nb: spaced \nc: a - b\nd: a[b]c\n", + "documents": [ + { + "a": "x:y z", + "b": "spaced", + "c": "a - b", + "d": "a[b]c" + } + ], + "notes": [] + }, + { + "name": "tab-after-colon", + "text": "a:\tb\nc: [1,\t2]\n", + "documents": [ + { + "a": "b", + "c": [ + 1, + 2 + ] + } + ], + "notes": [] + }, + { + "name": "double-quoted-escapes", + "text": "a: \"\\x41\\u00e9\\U0001F600\\N\\_\\L\\P\\e\\0\\/\\t\\\\\\\"\"\n", + "documents": [ + { + "a": "Aé😀… 

\u001b\u0000/\t\\\"" + } + ], + "notes": [] + }, + { + "name": "double-quoted-folding", + "text": "a: \"one\n two\n\n three\"\nb: \"trail \n next\"\nc: \"esc\\\n aped\"\nd: \"keep \\\n space\"\n", + "documents": [ + { + "a": "one two\nthree", + "b": "trail next", + "c": "escaped", + "d": "keep space" + } + ], + "notes": [] + }, + { + "name": "single-quoted", + "text": "a: 'it''s'\nb: 'one\n two\n\n\n three'\nc: '\\n stays'\n", + "documents": [ + { + "a": "it's", + "b": "one two\n\nthree", + "c": "\\n stays" + } + ], + "notes": [] + }, + { + "name": "surrogate-pair-escape", + "text": "a: \"\\ud83d\\ude00\"\n", + "documents": [ + { + "a": "😀" + } + ], + "notes": [] + }, + { + "name": "nel-is-not-a-break", + "text": "a: \"x\\Ny\"\nb: x…y\n", + "documents": [ + { + "a": "x…y", + "b": "x…y" + } + ], + "notes": [] + }, + { + "name": "literal", + "text": "a: |\n one\n two\nb: |\n three\n", + "documents": [ + { + "a": "one\ntwo\n", + "b": "three\n" + } + ], + "notes": [] + }, + { + "name": "literal-chomping", + "text": "strip: |-\n x\n\nclip: |\n y\n\nkeep: |+\n z\n\nlast: 1\n", + "documents": [ + { + "strip": "x", + "clip": "y\n", + "keep": "z\n\n", + "last": 1 + } + ], + "notes": [] + }, + { + "name": "literal-keep-at-end", + "text": "|+\n a\n\n", + "documents": [ + "a\n\n" + ], + "notes": [] + }, + { + "name": "literal-no-final-break", + "text": "a: |\n no break at the end", + "documents": [ + { + "a": "no break at the end" + } + ], + "notes": [] + }, + { + "name": "literal-indentation-indicator", + "text": "a: |2\n three spaces\n two\nb: |1-\n two\n", + "documents": [ + { + "a": " three spaces\ntwo\n", + "b": " two" + } + ], + "notes": [] + }, + { + "name": "literal-leading-empty-lines", + "text": "a: |\n\n\n after empty lines\n", + "documents": [ + { + "a": "\n\nafter empty lines\n" + } + ], + "notes": [] + }, + { + "name": "literal-more-indented-lines", + "text": "a: |\n top\n indented\n back\n", + "documents": [ + { + "a": "top\n indented\nback\n" + } + ], + "notes": [] + }, + { + "name": "folded", + "text": "a: >\n one\n two\n\n three\n", + "documents": [ + { + "a": "one two\nthree\n" + } + ], + "notes": [] + }, + { + "name": "folded-more-indented", + "text": ">\n folded\n line\n\n next\n line\n * bullet\n\n * list\n * lines\n\n last\n line\n", + "documents": [ + "folded line\nnext line\n * bullet\n\n * list\n * lines\n\nlast line\n" + ], + "notes": [] + }, + { + "name": "folded-chomping", + "text": "a: >-\n x\n y\n\nb: >+\n z\n\n", + "documents": [ + { + "a": "x y", + "b": "z\n\n" + } + ], + "notes": [] + }, + { + "name": "empty-blocks", + "text": "a: |\nb: >-\nc: |+\n\nd: 1\n", + "documents": [ + { + "a": "", + "b": "", + "c": "\n", + "d": 1 + } + ], + "notes": [] + }, + { + "name": "block-as-document", + "text": "--- |\n block doc\n--- >-\n folded\n doc\n", + "documents": [ + "block doc\n", + "folded doc" + ], + "notes": [] + }, + { + "name": "anchors-and-aliases", + "text": "base: &b {x: 1, y: [2, 3]}\ncopy: *b\nlist: [*b, *b]\nscalar: &s hello\nagain: *s\n", + "documents": [ + { + "base": { + "x": 1, + "y": [ + 2, + 3 + ] + }, + "copy": { + "x": 1, + "y": [ + 2, + 3 + ] + }, + "list": [ + { + "x": 1, + "y": [ + 2, + 3 + ] + }, + { + "x": 1, + "y": [ + 2, + 3 + ] + } + ], + "scalar": "hello", + "again": "hello" + } + ], + "notes": [] + }, + { + "name": "anchor-redefined", + "text": "a: &x 1\nb: *x\nc: &x 2\nd: *x\n", + "documents": [ + { + "a": 1, + "b": 1, + "c": 2, + "d": 2 + } + ], + "notes": [] + }, + { + "name": "merge-order", + "text": "base: &b\n x: 1\n y: 2\nuse:\n w: 0\n <<: *b\n z: 3\n", + "documents": [ + { + "base": { + "x": 1, + "y": 2 + }, + "use": { + "w": 0, + "x": 1, + "y": 2, + "z": 3 + } + } + ], + "notes": [] + }, + { + "name": "merge-list-first-wins", + "text": "a: &a {x: 1, y: 1}\nb: &b {y: 2, z: 2}\nc:\n <<: [*a, *b]\n", + "documents": [ + { + "a": { + "x": 1, + "y": 1 + }, + "b": { + "y": 2, + "z": 2 + }, + "c": { + "x": 1, + "y": 1, + "z": 2 + } + } + ], + "notes": [] + }, + { + "name": "merge-own-key-wins", + "text": "base: &b {x: 1, y: 2}\nuse:\n <<: *b\n y: 9\nalso:\n y: 8\n <<: *b\n", + "documents": [ + { + "base": { + "x": 1, + "y": 2 + }, + "use": { + "x": 1, + "y": 9 + }, + "also": { + "y": 8, + "x": 1 + } + } + ], + "notes": [] + }, + { + "name": "merge-quoted-is-a-key", + "text": "a: &a {x: 1}\nb:\n '<<': *a\n", + "documents": [ + { + "a": { + "x": 1 + }, + "b": { + "<<": { + "x": 1 + } + } + } + ], + "notes": [] + }, + { + "name": "documents", + "text": "---\na: 1\n---\n- b\n--- text\n", + "documents": [ + { + "a": 1 + }, + [ + "b" + ], + "text" + ], + "notes": [] + }, + { + "name": "document-end-markers", + "text": "a: 1\n...\n---\nb: 2\n...\n", + "documents": [ + { + "a": 1 + }, + { + "b": 2 + } + ], + "notes": [] + }, + { + "name": "empty-documents", + "text": "---\n---\n...\n", + "documents": [ + null, + null + ], + "notes": [] + }, + { + "name": "yaml-1.2-directive", + "text": "%YAML 1.2\n---\na: 1\n", + "documents": [ + { + "a": 1 + } + ], + "notes": [] + }, + { + "name": "yaml-1.1-directive", + "text": "%YAML 1.1\n---\na: yes\n", + "documents": [ + { + "a": "yes" + } + ], + "notes": [ + [ + 1, + 1, + "warning", + "yaml-version" + ] + ] + }, + { + "name": "markers-in-text", + "text": "a: ---x\nb: '---'\nc: x ... y\n", + "documents": [ + { + "a": "---x", + "b": "---", + "c": "x ... y" + } + ], + "notes": [] + }, + { + "name": "crlf-line-breaks", + "text": "a: 1\r\nb:\r\n - x\r\nc: |\r\n y\r\n", + "documents": [ + { + "a": 1, + "b": [ + "x" + ], + "c": "y\n" + } + ], + "notes": [] + }, + { + "name": "byte-order-mark", + "text": "a: 1\n", + "documents": [ + { + "a": 1 + } + ], + "notes": [] + }, + { + "name": "tab-in-indentation", + "text": "a:\n\tb: 1\n", + "error": { + "rule": "tab-indent", + "line": 2, + "column": 1 + } + }, + { + "name": "custom-tag", + "text": "Resources:\n Name: !Ref Bucket\n", + "error": { + "rule": "tag", + "line": 2, + "column": 9 + } + }, + { + "name": "gitlab-reference-tag", + "text": "script:\n - !reference [.setup, script]\n", + "error": { + "rule": "tag", + "line": 2, + "column": 5 + } + }, + { + "name": "yaml-1.1-tag", + "text": "when: !!timestamp 2026-01-01\n", + "error": { + "rule": "tag", + "line": 1, + "column": 7 + } + }, + { + "name": "tag-on-the-wrong-value", + "text": "a: !!int abc\n", + "error": { + "rule": "tag-value", + "line": 1, + "column": 10 + } + }, + { + "name": "tag-on-the-wrong-collection", + "text": "a: !!seq {b: 1}\n", + "error": { + "rule": "tag-value", + "line": 1, + "column": 4 + } + }, + { + "name": "unknown-alias", + "text": "a: *nope\n", + "error": { + "rule": "unknown-alias", + "line": 1, + "column": 4 + } + }, + { + "name": "recursive-alias", + "text": "a: &x [1, *x]\n", + "error": { + "rule": "recursive-alias", + "line": 1, + "column": 11 + } + }, + { + "name": "list-as-key", + "text": "[a, b]: c\n", + "error": { + "rule": "complex-key", + "line": 1, + "column": 1 + } + }, + { + "name": "alias-as-key", + "text": "base: &b k\n*b : v\n", + "error": { + "rule": "complex-key", + "line": 2, + "column": 1 + } + }, + { + "name": "anchor-on-key", + "text": "&a key: v\n", + "error": { + "rule": "complex-key", + "line": 1, + "column": 4 + } + }, + { + "name": "explicit-key-not-text", + "text": "? - a\n: b\n", + "error": { + "rule": "complex-key", + "line": 1, + "column": 3 + } + }, + { + "name": "map-on-the-key-line", + "text": "a: b: c\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 4 + } + }, + { + "name": "list-on-the-key-line", + "text": "a: - b\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 4 + } + }, + { + "name": "indent-lines-up-with-nothing", + "text": "a:\n b: 1\n c: 2\n", + "error": { + "rule": "not-yaml", + "line": 3, + "column": 3 + } + }, + { + "name": "key-under-a-value", + "text": "a: 1\n b: 2\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 3 + } + }, + { + "name": "key-after-list", + "text": "- a\nb: 1\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 1 + } + }, + { + "name": "item-among-keys", + "text": "a: 1\n- b\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 1 + } + }, + { + "name": "no-colon", + "text": "a: 1\nb\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 1 + } + }, + { + "name": "unclosed-double-quote", + "text": "a: \"open\nb: 1\n", + "error": { + "rule": "unclosed-quote", + "line": 1, + "column": 4 + } + }, + { + "name": "unclosed-single-quote", + "text": "a: 'open\n", + "error": { + "rule": "unclosed-quote", + "line": 1, + "column": 4 + } + }, + { + "name": "unclosed-list", + "text": "a: [1, 2\nb: 3\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 4 + } + }, + { + "name": "missing-comma", + "text": "{a: 1 b: 2}\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 8 + } + }, + { + "name": "bad-escape", + "text": "a: \"\\q\"\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 5 + } + }, + { + "name": "short-hex-escape", + "text": "a: \"\\x4\"\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 5 + } + }, + { + "name": "control-character", + "text": "a: b\u0007c\n", + "error": { + "rule": "control-character", + "line": 1, + "column": 5 + } + }, + { + "name": "tag-directive", + "text": "%TAG ! tag:example.com,2000:\n---\na: 1\n", + "error": { + "rule": "directive", + "line": 1, + "column": 1 + } + }, + { + "name": "directive-without-document", + "text": "%YAML 1.2\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 1 + } + }, + { + "name": "more-after-the-document", + "text": "{a: 1}\nb: 2\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 1 + } + }, + { + "name": "reserved-indicator", + "text": "a: @handle\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 4 + } + }, + { + "name": "merge-of-a-scalar", + "text": "a:\n <<: 5\n", + "error": { + "rule": "merge", + "line": 2, + "column": 3 + } + }, + { + "name": "alias-bomb", + "text": "a: &a [x,x,x,x,x,x,x,x,x,x]\nb: &b [*a,*a,*a,*a,*a,*a,*a,*a,*a,*a]\nc: &c [*b,*b,*b,*b,*b,*b,*b,*b,*b,*b]\nd: &d [*c,*c,*c,*c,*c,*c,*c,*c,*c,*c]\ne: &e [*d,*d,*d,*d,*d,*d,*d,*d,*d,*d]\nf: &f [*e,*e,*e,*e,*e,*e,*e,*e,*e,*e]\n", + "error": { + "rule": "alias-limit", + "line": 6, + "column": 29 + } + }, + { + "name": "too-deep", + "text": "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]\n", + "error": { + "rule": "too-deep", + "line": 1, + "column": 101 + } + }, + { + "name": "number-too-long", + "text": "a: 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999\n", + "error": { + "rule": "number", + "line": 1, + "column": 4 + } + }, + { + "name": "indentation-indicator-0", + "text": "a: |0\n x\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 5 + } + }, + { + "name": "text-after-block-header", + "text": "a: | text\n x\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 6 + } + }, + { + "name": "empty-line-wider-than-block", + "text": "a: |\n \n text\n", + "error": { + "rule": "not-yaml", + "line": 3, + "column": 3 + } + }, + { + "name": "two-anchors", + "text": "a: &x &y 1\n", + "error": { + "rule": "not-yaml", + "line": 1, + "column": 7 + } + }, + { + "name": "alias-with-an-anchor", + "text": "a: &x 1\nb: &y *x\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 7 + } + }, + { + "name": "text-after-document-end", + "text": "a: 1\n... junk\n", + "error": { + "rule": "not-yaml", + "line": 2, + "column": 5 + } + }, + { + "name": "empty", + "text": " \n\n", + "error": { + "rule": "empty" + } + }, + { + "name": "only-comments", + "text": "# just\n# comments\n", + "error": { + "rule": "empty" + } + } + ] +} diff --git a/tests/shared/yaml.json b/tests/shared/yaml-write.json similarity index 100% rename from tests/shared/yaml.json rename to tests/shared/yaml-write.json