Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1,683 changes: 1,683 additions & 0 deletions LibreDevOpsHelpers/LibreDevOpsHelpers.Yaml/LibreDevOpsHelpers.Yaml.psm1

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions LibreDevOpsHelpers/LibreDevOpsHelpers.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@
'Get-LdoTerraformStackFolders',
'Get-LdoTraceContext',
'Get-LdoUvPython',
'Get-LdoYamlValue',
'Initialize-LdoVenv',
'Install-LdoAzureCli',
'Install-LdoCheckov',
Expand Down
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
2 changes: 1 addition & 1 deletion tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

162 changes: 157 additions & 5 deletions tests/Yaml.Tests.ps1
Original file line number Diff line number Diff line change
@@ -1,20 +1,65 @@
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)
}

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
}
}
Expand Down Expand Up @@ -104,7 +149,7 @@ Describe 'ConvertTo-LdoYaml' {
}

Describe 'Shared cases: writing YAML' {
It '<Name>' -ForEach $yamlCases {
It '<Name>' -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)"
Expand Down Expand Up @@ -134,3 +179,110 @@ Describe 'ConvertTo-LdoYaml quoting' {
}
}

Describe 'Shared cases: reading YAML' {
It '<Name>' -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: <Name>' -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'
}
}
Loading
Loading