-
Notifications
You must be signed in to change notification settings - Fork 78
/
powershell-yaml.psm1
503 lines (456 loc) · 17.6 KB
/
powershell-yaml.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# Copyright 2016-2024 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
[Flags()]
enum SerializationOptions {
None = 0
Roundtrip = 1
DisableAliases = 2
EmitDefaults = 4
JsonCompatible = 8
DefaultToStaticType = 16
WithIndentedSequences = 32
OmitNullValues = 64
UseFlowStyle = 128
UseSequenceFlowStyle = 256
}
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$infinityRegex = [regex]::new('^[-+]?(\.inf|\.Inf|\.INF)$', "Compiled, CultureInvariant");
function Invoke-LoadFile {
param(
[string]$assemblyPath
)
$global:powershellYamlDotNetAssemblyPath = Join-Path $assemblyPath "YamlDotNet.dll"
$serializerAssemblyPath = Join-Path $assemblyPath "PowerShellYamlSerializer.dll"
$yamlAssembly = [Reflection.Assembly]::LoadFile($powershellYamlDotNetAssemblyPath)
$serializerAssembly = [Reflection.Assembly]::LoadFile($serializerAssemblyPath)
if ($PSVersionTable['PSEdition'] -eq 'Core') {
# Register the AssemblyResolve event to load dependencies manually. This seems to be needed only on
# PowerShell Core.
[System.AppDomain]::CurrentDomain.add_AssemblyResolve({
param ($sender, $e)
$pth = $powershellYamlDotNetAssemblyPath
# Load YamlDotNet if it's requested by PowerShellYamlSerializer. Ignore other requests as they might
# originate from other assemblies that are not part of this module and which might have different
# versions of the module that they need to load.
if ($e.Name -like "*YamlDotNet*" -and $e.RequestingAssembly -like "*PowerShellYamlSerializer*" ) {
return [System.Reflection.Assembly]::LoadFile($powershellYamlDotNetAssemblyPath)
}
return $null
})
# Load the StringQuotingEmitter from PowerShellYamlSerializer to force the resolver handler to fire once.
# This will load the YamlDotNet assembly and expand the global variable $powershellYamlDotNetAssemblyPath.
# We then remove it to avoid polluting the global scope.
# This is an ugly hack I am not happy with.
$serializerAssembly.GetType("StringQuotingEmitter") | Out-Null
}
Remove-Variable -Name powershellYamlDotNetAssemblyPath -Scope Global
return @{ "yaml"= $yamlAssembly; "quoted" = $serializerAssembly }
}
function Invoke-LoadAssembly {
$libDir = Join-Path $here "lib"
$assemblies = @{
"core" = Join-Path $libDir "netstandard2.1";
"net47" = Join-Path $libDir "net47";
}
if ($PSVersionTable.Keys -contains "PSEdition") {
if ($PSVersionTable.PSEdition -eq "Core") {
return (Invoke-LoadFile -assemblyPath $assemblies["core"])
}
return (Invoke-LoadFile -assemblyPath $assemblies["net47"])
} else {
return (Invoke-LoadFile -assemblyPath $assemblies["net47"])
}
}
$assemblies = Invoke-LoadAssembly
$yamlDotNetAssembly = $assemblies["yaml"]
$stringQuotedAssembly = $assemblies["quoted"]
function Get-YamlDocuments {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$Yaml,
[switch]$UseMergingParser=$false
)
PROCESS {
$stringReader = new-object System.IO.StringReader($Yaml)
$parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.Parser")
$parser = $parserType::new($stringReader)
if($UseMergingParser) {
$parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.MergingParser")
$parser = $parserType::new($parser)
}
$yamlStream = $yamlDotNetAssembly.GetType("YamlDotNet.RepresentationModel.YamlStream")::new()
$yamlStream.Load($parser)
$stringReader.Close()
return $yamlStream
}
}
function Convert-ValueToProperType {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Object]$Node
)
PROCESS {
if (!($Node.Value -is [string])) {
return $Node
}
$intTypes = @([int], [long])
if ([string]::IsNullOrEmpty($Node.Tag) -eq $false) {
switch($Node.Tag) {
"tag:yaml.org,2002:str" {
return $Node.Value
}
"tag:yaml.org,2002:null" {
return $null
}
"tag:yaml.org,2002:bool" {
$parsedValue = $false
if (![boolean]::TryParse($Node.Value, [ref]$parsedValue)) {
Throw ("failed to parse scalar {0} as boolean" -f $Node)
}
return $parsedValue
}
"tag:yaml.org,2002:int" {
$parsedValue = 0
if ($node.Value.Length -gt 2) {
switch ($node.Value.Substring(0, 2)) {
"0o" {
$parsedValue = [Convert]::ToInt64($Node.Value.Substring(2), 8)
}
"0x" {
$parsedValue = [Convert]::ToInt64($Node.Value.Substring(2), 16)
}
default {
if (![System.Numerics.BigInteger]::TryParse($Node.Value, @([Globalization.NumberStyles]::Float, [Globalization.NumberStyles]::Integer), [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)) {
Throw ("failed to parse scalar {0} as long" -f $Node)
}
}
}
} else {
if (![System.Numerics.BigInteger]::TryParse($Node.Value, @([Globalization.NumberStyles]::Float, [Globalization.NumberStyles]::Integer), [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)) {
Throw ("failed to parse scalar {0} as long" -f $Node)
}
}
foreach ($i in $intTypes) {
$asIntType = $parsedValue -as $i
if($asIntType) {
return $asIntType
}
}
return $parsedValue
}
"tag:yaml.org,2002:float" {
$parsedValue = 0.0
if ($infinityRegex.Matches($Node.Value)) {
$prefix = $Node.Value.Substring(0, 1)
switch ($prefix) {
"-" {
return [double]::NegativeInfinity
}
default {
# Prefix is either missing or is a +
return [double]::PositiveInfinity
}
}
}
if (![double]::TryParse($Node.Value, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)) {
Throw ("failed to parse scalar {0} as double" -f $Node)
}
return $parsedValue
}
"tag:yaml.org,2002:timestamp" {
# From the YAML spec: http://yaml.org/type/timestamp.html
[DateTime]$parsedValue = [DateTime]::MinValue
$ts = [DateTime]::SpecifyKind($Node.Value, [System.DateTimeKind]::Utc)
$tss = $ts.ToString("o")
if(![datetime]::TryParse($tss, $null, [System.Globalization.DateTimeStyles]::RoundtripKind, [ref] $parsedValue)) {
Throw ("failed to parse scalar {0} as DateTime" -f $Node)
}
return $parsedValue
}
}
}
if ($Node.Style -eq 'Plain') {
$parsedValue = New-Object -TypeName ([Boolean].FullName)
$result = [boolean]::TryParse($Node,[ref]$parsedValue)
if( $result ) {
return $parsedValue
}
$parsedValue = New-Object -TypeName ([System.Numerics.BigInteger].FullName)
$result = [System.Numerics.BigInteger]::TryParse($Node, @([Globalization.NumberStyles]::Float, [Globalization.NumberStyles]::Integer), [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)
if($result) {
$types = @([int], [long])
foreach($i in $types){
$asType = $parsedValue -as $i
if($asType) {
return $asType
}
}
return $parsedValue
}
$types = @([double], [decimal])
foreach($i in $types){
$parsedValue = New-Object -TypeName $i.FullName
$result = $i::TryParse($Node, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)
if( $result ) {
return $parsedValue
}
}
}
if ($Node.Style -eq 'Plain' -and $Node.Value -in '','~','null','Null','NULL') {
return $null
}
return $Node.Value
}
}
function Convert-YamlMappingToHashtable {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
$Node,
[switch] $Ordered
)
PROCESS {
if ($Ordered) { $ret = [System.Collections.Specialized.OrderedDictionary]::new() } else { $ret = [hashtable]::new() }
foreach($i in $Node.Children.Keys) {
$ret[$i.Value] = Convert-YamlDocumentToPSObject $Node.Children[$i] -Ordered:$Ordered
}
return $ret
}
}
function Convert-YamlSequenceToArray {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
$Node,
[switch]$Ordered
)
PROCESS {
$ret = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]")
foreach($i in $Node.Children){
$ret.Add((Convert-YamlDocumentToPSObject $i -Ordered:$Ordered))
}
return ,$ret
}
}
function Convert-YamlDocumentToPSObject {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[System.Object]$Node,
[switch]$Ordered
)
PROCESS {
switch($Node.GetType().FullName){
"YamlDotNet.RepresentationModel.YamlMappingNode"{
return Convert-YamlMappingToHashtable $Node -Ordered:$Ordered
}
"YamlDotNet.RepresentationModel.YamlSequenceNode" {
return Convert-YamlSequenceToArray $Node -Ordered:$Ordered
}
"YamlDotNet.RepresentationModel.YamlScalarNode" {
return (Convert-ValueToProperType $Node)
}
}
}
}
function Convert-HashtableToDictionary {
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[hashtable]$Data
)
foreach($i in $($data.PSBase.Keys)) {
$Data[$i] = Convert-PSObjectToGenericObject $Data[$i]
}
return $Data
}
function Convert-OrderedHashtableToDictionary {
Param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Collections.Specialized.OrderedDictionary] $Data
)
foreach ($i in $($data.PSBase.Keys)) {
$Data[$i] = Convert-PSObjectToGenericObject $Data[$i]
}
return $Data
}
function Convert-ListToGenericList {
Param(
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[array]$Data=@()
)
$ret = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]")
for($i=0; $i -lt $Data.Count; $i++) {
$ret.Add((Convert-PSObjectToGenericObject $Data[$i]))
}
return ,$ret
}
function Convert-PSObjectToGenericObject {
Param(
[Parameter(Mandatory=$false,ValueFromPipeline=$true)]
[System.Object]$Data
)
if ($null -eq $data) {
return $data
}
$dataType = $data.GetType()
if (([System.Collections.Specialized.OrderedDictionary].IsAssignableFrom($dataType))){
return Convert-OrderedHashtableToDictionary $data
} elseif (([System.Collections.IDictionary].IsAssignableFrom($dataType))){
return Convert-HashtableToDictionary $data
} elseif (([System.Collections.IList].IsAssignableFrom($dataType))) {
return Convert-ListToGenericList $data
}
return $data
}
function ConvertFrom-Yaml {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false, ValueFromPipeline=$true, Position=0)]
[string]$Yaml,
[switch]$AllDocuments=$false,
[switch]$Ordered,
[switch]$UseMergingParser=$false
)
BEGIN {
$d = ""
}
PROCESS {
if($Yaml -is [string]) {
$d += $Yaml + "`n"
}
}
END {
if($d -eq ""){
return
}
$documents = Get-YamlDocuments -Yaml $d -UseMergingParser:$UseMergingParser
if (!$documents.Count) {
return
}
if($documents.Count -eq 1){
return Convert-YamlDocumentToPSObject $documents[0].RootNode -Ordered:$Ordered
}
if(!$AllDocuments) {
return Convert-YamlDocumentToPSObject $documents[0].RootNode -Ordered:$Ordered
}
$ret = @()
foreach($i in $documents) {
$ret += Convert-YamlDocumentToPSObject $i.RootNode -Ordered:$Ordered
}
return $ret
}
}
function Get-Serializer {
Param(
[Parameter(Mandatory=$true)][SerializationOptions]$Options
)
$builder = $yamlDotNetAssembly.GetType("YamlDotNet.Serialization.SerializerBuilder")::new()
if ($Options.HasFlag([SerializationOptions]::Roundtrip)) {
$builder = $builder.EnsureRoundtrip()
}
if ($Options.HasFlag([SerializationOptions]::DisableAliases)) {
$builder = $builder.DisableAliases()
}
if ($Options.HasFlag([SerializationOptions]::EmitDefaults)) {
$builder = $builder.EmitDefaults()
}
if ($Options.HasFlag([SerializationOptions]::JsonCompatible)) {
$builder = $builder.JsonCompatible()
}
if ($Options.HasFlag([SerializationOptions]::DefaultToStaticType)) {
$resolver = $yamlDotNetAssembly.GetType("YamlDotNet.Serialization.TypeResolvers.StaticTypeResolver")::new()
$builder = $builder.WithTypeResolver($resolver)
}
if ($Options.HasFlag([SerializationOptions]::WithIndentedSequences)) {
$builder = $builder.WithIndentedSequences()
}
$omitNull = $Options.HasFlag([SerializationOptions]::OmitNullValues)
$useFlowStyle = $Options.HasFlag([SerializationOptions]::UseFlowStyle)
$useSequenceFlowStyle = $Options.HasFlag([SerializationOptions]::UseSequenceFlowStyle)
$stringQuoted = $stringQuotedAssembly.GetType("BuilderUtils")
$builder = $stringQuoted::BuildSerializer($builder, $omitNull, $useFlowStyle, $useSequenceFlowStyle)
return $builder.Build()
}
function ConvertTo-Yaml {
[CmdletBinding(DefaultParameterSetName = 'NoOptions')]
Param(
[Parameter(ValueFromPipeline = $true, Position=0)]
[System.Object]$Data,
[string]$OutFile,
[Parameter(ParameterSetName = 'Options')]
[SerializationOptions]$Options = [SerializationOptions]::Roundtrip,
[Parameter(ParameterSetName = 'NoOptions')]
[switch]$JsonCompatible,
[switch]$UseFlowStyle,
[switch]$KeepArray,
[switch]$Force
)
BEGIN {
$d = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]")
}
PROCESS {
if($data -is [System.Object]) {
$d.Add($data)
}
}
END {
if ($d -eq $null -or $d.Count -eq 0) {
return
}
if ($d.Count -eq 1 -and !($KeepArray)) {
$d = $d[0]
}
$norm = Convert-PSObjectToGenericObject $d
if ($OutFile) {
$parent = Split-Path $OutFile
if (!(Test-Path $parent)) {
Throw "Parent folder for specified path does not exist"
}
if ((Test-Path $OutFile) -and !$Force) {
Throw "Target file already exists. Use -Force to overwrite."
}
$wrt = New-Object "System.IO.StreamWriter" $OutFile
} else {
$wrt = New-Object "System.IO.StringWriter"
}
if ($PSCmdlet.ParameterSetName -eq 'NoOptions') {
$Options = 0
if ($JsonCompatible) {
# No indent options :~(
$Options = [SerializationOptions]::JsonCompatible
}
}
try {
$serializer = Get-Serializer $Options
$serializer.Serialize($wrt, $norm)
}
catch{
$_
}
finally {
$wrt.Close()
}
if ($OutFile) {
return
} else {
return $wrt.ToString()
}
}
}
New-Alias -Name cfy -Value ConvertFrom-Yaml
New-Alias -Name cty -Value ConvertTo-Yaml
Export-ModuleMember -Function ConvertFrom-Yaml,ConvertTo-Yaml -Alias cfy,cty