├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── LICENSE ├── README.md ├── Tests └── powershell-yaml.Tests.ps1 ├── build.ps1 ├── lib ├── net47 │ ├── LICENSE.txt │ ├── PowerShellYamlSerializer.dll │ ├── YamlDotNet.dll │ └── YamlDotNet.xml └── netstandard2.1 │ ├── LICENSE.txt │ ├── PowerShellYamlSerializer.dll │ ├── YamlDotNet.dll │ └── YamlDotNet.xml ├── powershell-yaml.psd1 ├── powershell-yaml.psm1 └── src ├── PowerShellYamlSerializer.cs └── PowerShellYamlSerializer.csproj /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: powershell-yaml 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-${{ github.head_ref || github.ref_name }} 11 | cancel-in-progress: true 12 | 13 | permissions: {} 14 | 15 | jobs: 16 | powershell_tests: 17 | name: Pester tests on powershell.exe 18 | runs-on: ${{ matrix.os }} 19 | strategy: 20 | fail-fast: false 21 | matrix: 22 | os: [windows-2019, windows-2022] 23 | 24 | steps: 25 | - uses: actions/checkout@v3 26 | - name: Install modules 27 | shell: powershell 28 | run: | 29 | Set-PSRepository PSGallery -InstallationPolicy Trusted 30 | Install-Module Assert -ErrorAction Stop -MaximumVersion 0.9.6 -Force 31 | Install-Module Pester -ErrorAction Stop -MaximumVersion 5.6.1 -Force 32 | - name: Run tests 33 | shell: powershell 34 | run: | 35 | Invoke-Pester 36 | 37 | pwsh_tests: 38 | name: Pester tests 39 | runs-on: ${{ matrix.os }} 40 | strategy: 41 | fail-fast: false 42 | matrix: 43 | os: [ubuntu-22.04, ubuntu-24.04, macos-latest, windows-2019, windows-2022] 44 | 45 | steps: 46 | - uses: actions/checkout@v3 47 | - name: Install modules 48 | shell: pwsh 49 | run: | 50 | Set-PSRepository PSGallery -InstallationPolicy Trusted 51 | Install-Module Assert -ErrorAction Stop -MaximumVersion 0.9.6 -Force 52 | Install-Module Pester -ErrorAction Stop -MaximumVersion 5.6.1 -Force 53 | - name: Run tests 54 | shell: pwsh 55 | run: | 56 | Remove-Module Pester -ErrorAction SilentlyContinue 57 | Import-Module pester -Version 5.6.1 58 | 59 | $PSVersionTable 60 | 61 | Invoke-Pester -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | src/obj 2 | src/bin 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016-2023 Cloudbase Solutions SRL 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # powershell-yaml 2 | 3 | [![Actions Status](https://github.com/cloudbase/powershell-yaml/workflows/powershell-yaml/badge.svg)](https://github.com/cloudbase/powershell-yaml/actions) 4 | 5 | This powershell module is a thin wrapper on top of [YamlDotNet](https://github.com/aaubry/YamlDotNet "YamlDotNet") that serializes and un-serializes simple powershell objects to and from YAML. It was tested on powershell versions 4 and 5, supports [Nano Server](https://technet.microsoft.com/en-us/library/mt126167.aspx "Nano") and apparently works with powershell on Linux. I suspect it works on Mac as well, but I have not had a chance to test it. 6 | 7 | The ```lib``` folder contains the YamlDotNet assemblies. They are not really required, just a fall-back in case your system does not already have them installed and loaded. Feel free to remove the ```lib``` folder if you prefer to add the required assemblies yourself. 8 | 9 | ## Installation 10 | 11 | This module is available for installation via [Powershell Gallery](http://www.powershellgallery.com/). Simply run the following command: 12 | 13 | ```powershell 14 | Install-Module powershell-yaml 15 | ``` 16 | 17 | ## ConvertTo-Yaml 18 | 19 | ```powershell 20 | Import-Module powershell-yaml 21 | 22 | PS C:\> $yaml = ConvertTo-Yaml @{"hello"="world"; "anArray"=@(1,2,3); "nested"=@{"array"=@("this", "is", "an", "array")}} 23 | PS C:\> $yaml 24 | anArray: 25 | - 1 26 | - 2 27 | - 3 28 | nested: 29 | array: 30 | - this 31 | - is 32 | - an 33 | - array 34 | hello: world 35 | ``` 36 | 37 | ## ConvertFrom-Yaml 38 | 39 | ### Single YAML document 40 | 41 | ```powershell 42 | Import-Module powershell-yaml 43 | 44 | PS C:\> $yaml = @" 45 | anArray: 46 | - 1 47 | - 2 48 | - 3 49 | nested: 50 | array: 51 | - this 52 | - is 53 | - an 54 | - array 55 | hello: world 56 | "@ 57 | 58 | PS C:\> $obj = ConvertFrom-Yaml $yaml 59 | PS C:\> $obj 60 | 61 | Name Value 62 | ---- ----- 63 | anArray {1, 2, 3} 64 | nested {array} 65 | hello world 66 | 67 | PS C:\> $obj.GetType() 68 | 69 | IsPublic IsSerial Name BaseType 70 | -------- -------- ---- -------- 71 | True True Hashtable System.Object 72 | ``` 73 | 74 | ### Multiple YAML documents 75 | 76 | Unserializing multiple documents results in an array representing the contents of each document. The result of this does not translate back to the same documents if you pass it back through ConvertTo-Yaml. 77 | 78 | ```powershell 79 | Import-Module powershell-yaml 80 | 81 | PS C:\> $yaml = @" 82 | --- 83 | anArray: 84 | - 1 85 | - 2 86 | - 3 87 | nested: 88 | array: 89 | - this 90 | - is 91 | - an 92 | - array 93 | hello: world 94 | --- 95 | second: document 96 | goodbye: world 97 | "@ 98 | 99 | PS C:\> $obj = ConvertFrom-Yaml $yaml -AllDocuments 100 | PS C:\> $obj 101 | 102 | Name Value 103 | ---- ----- 104 | anArray {1, 2, 3} 105 | nested {array} 106 | hello world 107 | goodbye world 108 | second document 109 | 110 | PS C:\> $obj.GetType() 111 | 112 | IsPublic IsSerial Name BaseType 113 | -------- -------- ---- -------- 114 | True True Object[] System.Array 115 | 116 | PS C:\> $obj[0] 117 | 118 | Name Value 119 | ---- ----- 120 | anArray {1, 2, 3} 121 | nested {array} 122 | hello world 123 | 124 | PS C:\> $obj[1] 125 | 126 | Name Value 127 | ---- ----- 128 | goodbye world 129 | second document 130 | ``` 131 | 132 | ## Merge keys support 133 | 134 | ```powershell 135 | 136 | $mergingYaml = @" 137 | --- 138 | default: &default 139 | value1: 1 140 | value2: 2 141 | 142 | hoge: 143 | <<: *default 144 | value3: 3 145 | "@ 146 | 147 | ConvertFrom-Yaml -Yaml $mergingYaml -UseMergingParser 148 | 149 | Name Value 150 | ---- ----- 151 | default {value1, value2} 152 | hoge {value2, value3, value1} 153 | 154 | ``` 155 | 156 | Important note: For the time being, overwriting keys will throw a duplicate key exception. 157 | 158 | ```powershell 159 | $mergingYamlWithDuplicates = @" 160 | --- 161 | default: &default 162 | value1: 1 163 | value2: 2 164 | 165 | hoge: 166 | <<: *default 167 | # this is a duplicate 168 | value1: 44 169 | value3: 3 170 | "@ 171 | ``` 172 | 173 | ## Converting from YAML to JSON 174 | 175 | The awesome YamlDotNet assembly allows us to serialize an object in a JSON compatible way. Unfortunately it does not support indentation. Here is a simple example: 176 | 177 | ```powershell 178 | Import-Module powershell-yaml 179 | 180 | PS C:\> $yaml = @" 181 | anArray: 182 | - 1 183 | - 2 184 | - 3 185 | nested: 186 | array: 187 | - this 188 | - is 189 | - an 190 | - array 191 | hello: world 192 | "@ 193 | 194 | PS C:\> $obj = ConvertFrom-Yaml $yaml 195 | PS C:\> $obj 196 | 197 | Name Value 198 | ---- ----- 199 | anArray {1, 2, 3} 200 | nested {array} 201 | hello world 202 | 203 | PS C:\> ConvertTo-Yaml -JsonCompatible $obj 204 | {"anArray": [1, 2, 3], "nested": {"array": ["this", "is", "an", "array"]}, "hello": "world"} 205 | 206 | # Or you could do it in one line. 207 | PS C:\> ConvertFrom-Yaml $yaml | ConvertTo-Yaml -JsonCompatible 208 | {"anArray": [1, 2, 3], "nested": {"array": ["this", "is", "an", "array"]}, "hello": "world"} 209 | 210 | ``` 211 | 212 | ## Using tags 213 | 214 | Using tags is prefered as opposed to allowing ```powershell-yaml``` to infer the type. Whenever there is a risc of ambiguity, use tags to make sure your values are converted using the intended type. This module supports the [tags specified by the core schema](http://yaml.org/spec/1.2-old/spec.html#id2804923), and aditionally the ```!!timestamp``` tag. 215 | 216 | ```powershell 217 | Import-Module powershell-yaml 218 | 219 | PS C:\> $data = @" 220 | aPhoneNumber: !!str +40123456789 221 | aPhoneNrWithoutTags: +40123456789 222 | "@ 223 | PS C:\> ConvertFrom-Yaml $data 224 | 225 | Name Value 226 | ---- ----- 227 | aPhoneNrWithoutTags 40123456789 228 | aPhoneNumber +40123456789 229 | 230 | PS C:\> $obj = ConvertFrom-Yaml $data 231 | PS C:\> $obj.aPhoneNumber.GetType() 232 | 233 | IsPublic IsSerial Name BaseType 234 | -------- -------- ---- -------- 235 | True True String System.Object 236 | 237 | PS C:\> $obj.aPhoneNrWithoutTags.GetType() 238 | 239 | IsPublic IsSerial Name BaseType 240 | -------- -------- ---- -------- 241 | True True Int64 System.ValueType 242 | ``` 243 | 244 | As you can see, the phone number without tags was cast to ```Int64```. This is most likely not the desired result and a case where tags should be used. 245 | 246 | ## Controlling output formatting 247 | 248 | By default `ConvertTo-Yaml` will output in `Block` style. You can control the output formatting by using `-Options` parameter and specifying one of the following values: `UseFlowStyle` or `UseSequenceFlowStyle`. The `UseFlowStyle` option will output everything in `Flow` style. The `UseSequenceFlowStyle` option will output sequences in `Flow` style and everything else in `Block` style. 249 | 250 | Here is an example of using the `UseFlowStyle` option: 251 | 252 | ```powershell 253 | Import-Module powershell-yaml 254 | 255 | PS C:\> $data = @{ 256 | "anArray" = @(1, 2, 3) 257 | "nested" = @{ 258 | "array" = @("this", "is", "an", "array") 259 | } 260 | "hello" = "world" 261 | } 262 | 263 | PS C:\> ConvertTo-Yaml $data -Options UseFlowStyle 264 | {anArray: [1, 2, 3], nested: {array: [this, is, an, array]}, hello: world} 265 | ``` 266 | 267 | Here is an example of using the `UseSequenceFlowStyle` option: 268 | 269 | ```powershell 270 | PS C:\> ConvertTo-Yaml $data -Options UseSequenceFlowStyle 271 | 272 | anArray: [1, 2, 3] 273 | nested: 274 | array: [this, is, an, array] 275 | hello: world 276 | ``` 277 | 278 | There is another tweak you can use. When using the default `Block` style, sequences are not indented. You can toggle this by passing in the `WithIndentedSequences` option. 279 | 280 | Here are examples with and without indented sequences: 281 | 282 | ```powershell 283 | PS C:\> ConvertTo-Yaml $data 284 | anArray: 285 | - 1 286 | - 2 287 | - 3 288 | nested: 289 | array: 290 | - this 291 | - is 292 | - an 293 | - array 294 | hello: world 295 | 296 | 297 | PS C:\> ConvertTo-Yaml $data -Options WithIndentedSequences 298 | anArray: 299 | - 1 300 | - 2 301 | - 3 302 | nested: 303 | array: 304 | - this 305 | - is 306 | - an 307 | - array 308 | hello: world 309 | ``` 310 | 311 | ## Running the tests 312 | 313 | Before running the associated unit tests; please make sure you have 314 | [Pester](https://github.com/pester/pester) installed, as it is the testing 315 | framework of choice. 316 | 317 | After Pester is up and running, the tests may be ran by simply entering the 318 | tests directory and running `Invoke-Pester`: 319 | 320 | ```powershell 321 | PS C:\> Install-Module Pester 322 | PS C:\> Install-Module Assert 323 | PS C:\> git clone https://github.com/cloudbase/powershell-yaml.git $HOME\powershell-yaml 324 | PS C:\> cd $HOME\powershell-yaml 325 | PS C:\Users\Guest\powershell-yaml> powershell.exe -NonInteractive -Command {Invoke-Pester} 326 | ``` 327 | -------------------------------------------------------------------------------- /Tests/powershell-yaml.Tests.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2016-2024 Cloudbase Solutions Srl 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | # 15 | 16 | # pinning this module to an exact version, 17 | # because the options api will be merged with Assert-Equivalent 18 | # before release of 1.0.0 19 | Import-Module Assert -Version 0.9.6 20 | 21 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 22 | $moduleHome = Split-Path -Parent $here 23 | 24 | $moduleName = "powershell-yaml" 25 | $modulePath = Join-Path $moduleHome "powershell-yaml.psd1" 26 | Import-Module $modulePath 27 | 28 | InModuleScope $moduleName { 29 | $compareStrictly = Get-EquivalencyOption -Comparator Equality 30 | 31 | Describe "Test flow styles" { 32 | Context "Mappings, sequences and PSCustomObjects" { 33 | It "Should serialize Block flow (default) correctly" { 34 | $obj = [ordered]@{ 35 | aStringKey = "test" 36 | anIntKey = 1 37 | anArrayKey = @(1, 2, 3) 38 | } 39 | $expected = @" 40 | aStringKey: test 41 | anIntKey: 1 42 | anArrayKey: 43 | - 1 44 | - 2 45 | - 3 46 | 47 | "@ 48 | $serialized = ConvertTo-Yaml $obj 49 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 50 | 51 | $pso = [pscustomobject]$obj 52 | $serialized = ConvertTo-Yaml $pso 53 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 54 | } 55 | 56 | It "Should serialize Flow flow correctly" { 57 | $obj = [ordered]@{ 58 | aStringKey = "test" 59 | anIntKey = 1 60 | anArrayKey = @(1, 2, 3) 61 | } 62 | $expected = @" 63 | {aStringKey: test, anIntKey: 1, anArrayKey: [1, 2, 3]} 64 | 65 | "@ 66 | $serialized = ConvertTo-Yaml -Options UseFlowStyle $obj 67 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 68 | 69 | $pso = [pscustomobject]$obj 70 | $serialized = ConvertTo-Yaml -Options UseFlowStyle $pso 71 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 72 | } 73 | 74 | It "Should serialize SequenceFlowStyle correctly" { 75 | $obj = [ordered]@{ 76 | aStringKey = "test" 77 | anIntKey = 1 78 | anArrayKey = @(1, 2, 3) 79 | } 80 | $expected = @" 81 | aStringKey: test 82 | anIntKey: 1 83 | anArrayKey: [1, 2, 3] 84 | 85 | "@ 86 | $serialized = ConvertTo-Yaml -Options UseSequenceFlowStyle $obj 87 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 88 | 89 | $pso = [pscustomobject]$obj 90 | $serialized = ConvertTo-Yaml -Options UseSequenceFlowStyle $pso 91 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 92 | } 93 | 94 | It "Should serialize JsonCompatible correctly" { 95 | $obj = [ordered]@{ 96 | aStringKey = "test" 97 | anIntKey = 1 98 | anArrayKey = @(1, 2, 3) 99 | } 100 | $expected = @" 101 | {"aStringKey": "test", "anIntKey": 1, "anArrayKey": [1, 2, 3]} 102 | 103 | "@ 104 | $serialized = ConvertTo-Yaml -Options JsonCompatible $obj 105 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 106 | 107 | if ($PSVersionTable['PSEdition'] -eq 'Core') { 108 | $deserializedWithJSonCommandlet = $serialized | ConvertFrom-Json -AsHashtable 109 | Assert-Equivalent -Options $compareStrictly -Expected $obj -Actual $deserializedWithJSonCommandlet 110 | } 111 | 112 | $pso = [pscustomobject]$obj 113 | $serialized = ConvertTo-Yaml -Options JsonCompatible $pso 114 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $serialized 115 | 116 | if ($PSVersionTable['PSEdition'] -eq 'Core') { 117 | $deserializedWithJSonCommandlet = $serialized | ConvertFrom-Json -AsHashtable 118 | Assert-Equivalent -Options $compareStrictly -Expected $obj -Actual $deserializedWithJSonCommandlet 119 | } 120 | } 121 | } 122 | } 123 | 124 | Describe "Test serialized depth" { 125 | Context "Deeply nested objects are serialized correctly" { 126 | It "Should deserialize the entire object" { 127 | $data = @" 128 | children: 129 | appliance: 130 | bla: 131 | bla2: 132 | bla3: 133 | bla4: 134 | bla5: 135 | bla6: 136 | bla7: 137 | bla8: 138 | bla9: 139 | bla10: 140 | bla11: 141 | bla12: 142 | bla13: 143 | bla14: 144 | bla15: 145 | bla16: 146 | bla17: 147 | bla18: 148 | bla19: 149 | bla20: 150 | bla21: 151 | bla22: 152 | bla23: 153 | bla24: 154 | bla25: 155 | bla26: 156 | bla27: 157 | bla28: 158 | bla29: 159 | bla30: 160 | bla31: 161 | bla32: 162 | bla33: 163 | bla34: 164 | bla35: 165 | bla36: 166 | bla37: 167 | bla38: 168 | bla39: 169 | bla40: 170 | bla41: 171 | bla42: 172 | bla43: 173 | bla44: 174 | bla45: 175 | bla46: 176 | bla47: 177 | bla48: 178 | bla49: 179 | bla50: 180 | bla51: 181 | - 192.168.0.1 182 | - 192.168.0.2 183 | - 192.168.0.3 184 | 185 | "@ 186 | $result = cfy $data | cty 187 | Assert-Equivalent -Options $compareStrictly -Expected $data -Actual $result 188 | } 189 | } 190 | } 191 | 192 | Describe "Test PSCustomObject wrapped values are serialized correctly" { 193 | Context "A PSCustomObject that contains an array of PSObjects" { 194 | It "Should serialize correctly" { 195 | $expected = @" 196 | yamlList: 197 | - item1 198 | - item2 199 | 200 | "@ 201 | $data = ConvertFrom-YAml "yamlList: []" | ConvertTo-JSON -Depth 3 | ConvertFrom-Json 202 | $jsData = '["item1", "item2"]' 203 | $data.yamlList = $jsData | ConvertFrom-Json 204 | 205 | $asYaml = ConvertTo-Yaml $data 206 | Assert-Equivalent -Options $compareStrictly -Expected $expected -Actual $asYaml 207 | } 208 | } 209 | Context "A PSCustomObject containing nested PSCustomObjects" { 210 | It "Should serialize correctly" { 211 | $expectBigInt = [System.Numerics.BigInteger]::Parse("9999999999999999999999999999999999999999999999999") 212 | $obj = [PSCustomObject]@{a = Write-Output 'string'; b = Write-Output 1; c = Write-Output @{nested = $true};d = [pscustomobject]$expectBigInt} 213 | $asYaml = ConvertTo-Yaml $obj 214 | $fromYaml = ConvertFrom-Yaml $asYaml 215 | 216 | Assert-Equivalent -Options $compareStrictly -Expected "string" -Actual $fromYaml["a"] 217 | Assert-Equivalent -Options $compareStrictly -Expected 1 -Actual $fromYaml["b"] 218 | Assert-Equivalent -Options $compareStrictly -Expected $expectBigInt -Actual $fromYaml["d"] 219 | } 220 | } 221 | 222 | Context "A hashtable containing nested PSCustomObjects" { 223 | It "Should serialize correctly" { 224 | $expectBigInt = [System.Numerics.BigInteger]::Parse("9999999999999999999999999999999999999999999999999") 225 | $obj = @{a = Write-Output 'string'; b = Write-Output 1; c = Write-Output @{nested = $true};d = [pscustomobject]$expectBigInt} 226 | $asYaml = ConvertTo-Yaml $obj 227 | $fromYaml = ConvertFrom-Yaml $asYaml 228 | 229 | Assert-Equivalent -Options $compareStrictly -Expected "string" -Actual $fromYaml["a"] 230 | Assert-Equivalent -Options $compareStrictly -Expected 1 -Actual $fromYaml["b"] 231 | Assert-Equivalent -Options $compareStrictly -Expected $expectBigInt -Actual $fromYaml["d"] 232 | } 233 | } 234 | 235 | Context "A generic dictionary containing nested PSCustomObjects" { 236 | It "Should serialize correctly" { 237 | $expectBigInt = [System.Numerics.BigInteger]::Parse("9999999999999999999999999999999999999999999999999") 238 | $obj = [System.Collections.Generic.Dictionary[string, object]]::new() 239 | $obj["a"] = Write-Output 'string' 240 | $obj["b"] = Write-Output 1 241 | $obj["c"] = Write-Output @{nested = $true} 242 | $obj["d"] = [pscustomobject]$expectBigInt 243 | 244 | $asYaml = ConvertTo-Yaml $obj 245 | $fromYaml = ConvertFrom-Yaml $asYaml 246 | 247 | Assert-Equivalent -Options $compareStrictly -Expected "string" -Actual $fromYaml["a"] 248 | Assert-Equivalent -Options $compareStrictly -Expected 1 -Actual $fromYaml["b"] 249 | Assert-Equivalent -Options $compareStrictly -Expected $expectBigInt -Actual $fromYaml["d"] 250 | } 251 | } 252 | } 253 | 254 | Describe "Test encode-decode symmetry." { 255 | 256 | Context "Simple-Items" { 257 | It "Should represent identity to encode and decode." -TestCases @( 258 | @{ Expected = 1 } 259 | @{ Expected = "yes" } 260 | @{ Expected = 56 } 261 | @{ Expected = $null } 262 | ) { 263 | param ($Expected) 264 | $actual = ConvertFrom-Yaml (ConvertTo-Yaml $Expected) 265 | 266 | Assert-Equivalent -Options $compareStrictly -Expected $Expected -Actual $actual 267 | } 268 | } 269 | 270 | Context "Nulls and strings" { 271 | BeforeAll { 272 | $global:nullAndString = [ordered]@{"iAmNull"= $null; "iAmEmptyString"=""} 273 | $global:yaml = @" 274 | iAmNull: 275 | iAmEmptyString: "" 276 | 277 | "@ 278 | } 279 | 280 | It "should not serialize null value when -Options OmitNullValues is set" { 281 | $toYaml = ConvertTo-Yaml $nullAndString -Options OmitNullValues 282 | $toYaml | Should -Be "iAmEmptyString: """"$([Environment]::NewLine)" 283 | } 284 | 285 | It "should preserve nulls and empty strings from PowerShell" { 286 | $toYaml = ConvertTo-Yaml $nullAndString 287 | $backFromYaml = ConvertFrom-Yaml $toYaml 288 | 289 | ($null -eq $backFromYaml.iAmNull) | Should -Be $true 290 | $backFromYaml.iAmEmptyString | Should -Be "" 291 | $toYaml | Should -Be $yaml 292 | } 293 | 294 | It "should preserve nulls and empty strings from Yaml" { 295 | $fromYaml = ConvertFrom-Yaml -Ordered $yaml 296 | $backToYaml = ConvertTo-Yaml $fromYaml 297 | 298 | $backToYaml | Should -Be $yaml 299 | ($null -eq $fromYaml.iAmNull) | Should -Be $true 300 | $fromYaml.iAmEmptyString | Should -Be "" 301 | } 302 | } 303 | 304 | Context "Test array handling under various circumstances." { 305 | $arr = 1, 2, "yes", @{ key = "value" }, 5, (1, "no", 3) 306 | 307 | It "Should represent identity to encode/decode arrays as arguments." { 308 | $yaml = ConvertTo-Yaml $arr 309 | $a = ConvertFrom-Yaml $yaml 310 | 311 | Assert-Equivalent -Options $compareStrictly -Actual $a -Expected $arr 312 | } 313 | 314 | It "Should represent identity to encode/decode arrays by piping them in." { 315 | $yaml = $arr | ConvertTo-Yaml 316 | $a = ConvertFrom-Yaml $yaml 317 | 318 | Assert-Equivalent -Options $compareStrictly -Actual $a -Expected $arr 319 | } 320 | 321 | It "Should be irrelevant whether we convert an array by piping it, or referencing them as an argument." { 322 | $arged = ConvertTo-Yaml $arr 323 | $piped = $arr | ConvertTo-Yaml 324 | 325 | Assert-Equivalent -Options $compareStrictly -Actual $piped -Expected $arged 326 | } 327 | } 328 | 329 | Context "Test merging parser" { 330 | BeforeAll { 331 | $global:mergingYaml = @" 332 | --- 333 | default: &default 334 | value1: 1 335 | value2: 2 336 | 337 | hoge: 338 | <<: *default 339 | value3: 3 340 | "@ 341 | 342 | $global:mergingYamlOverwriteCase = @" 343 | --- 344 | default: &default 345 | value1: 1 346 | value2: 2 347 | 348 | hoge: 349 | <<: *default 350 | value1: 33 351 | value3: 3 352 | "@ 353 | } 354 | 355 | It "Should expand merging key with appropriate referenced keys" { 356 | $result = ConvertFrom-Yaml -Yaml $mergingYaml -UseMergingParser 357 | [array]$values = $result.hoge.keys 358 | [array]::sort($values) 359 | Assert-Equivalent -Options $compareStrictly -Actual $values -Expected @("value1", "value2", "value3") 360 | } 361 | 362 | It "Should retain literal key name in the absence or -UseMergingParser" { 363 | $result = ConvertFrom-Yaml -Yaml $mergingYaml 364 | [array]$values = $result.hoge.keys 365 | [array]::sort($values) 366 | Assert-Equivalent -Options $compareStrictly -Actual $values -Expected @("<<", "value3") 367 | } 368 | 369 | It "Shoud Throw duplicate key exception when merging keys" { 370 | # This case does not seem to be treated by YamlDotNet and currently throws 371 | # a duplicate key exception 372 | { ConvertFrom-Yaml -Yaml $mergingYamlOverwriteCase -UseMergingParser } | Should -Throw -PassThru | Select-Object -ExpandProperty Exception | 373 | Should -BeLike "*Duplicate key*" 374 | } 375 | 376 | } 377 | 378 | Context "Test hash handling under various circumstances." { 379 | $hash = @{ 380 | # NOTE: intentionally not considered as YAML requires dict keys 381 | # be strings. As such; decoding the encoding of this would result 382 | # in a hash with the string key of "1", as below: 383 | # 1 = 42; 384 | "1" = 42; 385 | today = @{ 386 | month = "January"; 387 | year = "2016"; 388 | timestamp = Get-Date 389 | }; 390 | arr = 1, 2, 3, "yes", @{ yes = "yes" }; 391 | yes = "no" 392 | } 393 | 394 | It "Should be symmetrical to encode and then decode the hash as an argument." { 395 | $yaml = ConvertTo-Yaml $hash 396 | $h = ConvertFrom-Yaml $yaml 397 | 398 | Assert-Equivalent -Options $compareStrictly -Actual $h -Expected $hash 399 | } 400 | 401 | It "Should be symmetrical to endocode and then decode a hash by piping it." { 402 | $yaml = $hash | ConvertTo-Yaml 403 | $h = ConvertFrom-Yaml $yaml 404 | 405 | Assert-Equivalent -Options $compareStrictly -Actual $h -Expected $hash 406 | } 407 | 408 | It "Shouldn't matter whether we reference or pipe our hashes in to the YAML functions." { 409 | $arged = ConvertTo-Yaml $hash 410 | $piped = $hash | ConvertTo-Yaml 411 | 412 | Assert-Equivalent -Options $compareStrictly -Actual $piped -Expected $arged 413 | } 414 | } 415 | 416 | } 417 | 418 | Describe "Being able to decode an externally provided string." { 419 | 420 | Context "Decoding an arbitrary YAML string correctly." { 421 | BeforeAll { 422 | # testYaml is just a string containing some yaml to be tested below: 423 | $testYaml = @" 424 | wishlist: 425 | - [coats, hats, and, scarves] 426 | - product : A Cool Book. 427 | quantity : 1 428 | description : I love that Cool Book. 429 | price : 55.34 430 | total: 4443.52 431 | int64: $([int64]::MaxValue) 432 | note: > 433 | I can't wait. 434 | To get that Cool Book. 435 | 436 | intsAndDecimals: 437 | aStringTatLooksLikeAFloat: 55,34 438 | aStringThatLooksLikeAnInt: 2018+ 439 | scientificNotationInt: 1e+3 440 | scientificNotationBigInt: 1e+40 441 | intWithTag: !!int "42" 442 | zeroIntWithTag: !!int "0" 443 | zeroIntWithoutTag: 0 444 | scientificNotationIntWithTag: !!int "1e+3" 445 | aDecimalWithATag: !!float "3.9999999999999990" 446 | aDecimalWithoutATag: 3.9999999999999990 447 | decimalInfinity: !!float ".inf" 448 | decimalNegativeInfinity: !!float "-.inf" 449 | 450 | dates: 451 | - !!timestamp 2001-12-15T02:59:43.1Z 452 | - !!timestamp 2001-12-14t21:59:43.10-05:00 453 | - !!timestamp 2001-12-14 21:59:43.10 -5 454 | - !!timestamp 2001-12-15 2:59:43.10 455 | - !!timestamp 2002-12-14 456 | datesAsStrings: 457 | - 2001-12-15T02:59:43.1Z 458 | - 2001-12-14t21:59:43.10-05:00 459 | - 2001-12-14 21:59:43.10 -5 460 | - 2001-12-15 2:59:43.10 461 | - 2002-12-14 462 | 463 | version: 464 | - 1.2.3 465 | noniso8601dates: 466 | - 5/4/2017 467 | - 1.2.3 468 | bools: 469 | - true 470 | - false 471 | - TRUE 472 | - FALSE 473 | - True 474 | - False 475 | "@ 476 | 477 | $global:expected = @{ 478 | wishlist = @( 479 | @("coats", "hats", "and", "scarves"), 480 | @{ 481 | product = "A Cool Book."; 482 | quantity = 1; 483 | description = "I love that Cool Book."; 484 | price = 55.34; 485 | } 486 | ); 487 | intsAndDecimals = @{ 488 | aStringTatLooksLikeAFloat = "55,34"; 489 | aStringThatLooksLikeAnInt = "2018+" 490 | scientificNotationInt = [int32]1000 491 | scientificNotationBigInt = [System.Numerics.BigInteger]::Parse("10000000000000000000000000000000000000000") 492 | intWithTag = 42 493 | zeroIntWithTag = 0 494 | zeroIntWithoutTag = 0 495 | scientificNotationIntWithTag = 1000 496 | aDecimalWithATag = [decimal]::Parse("3.9999999999999990", [System.Globalization.CultureInfo]::InvariantCulture) 497 | aDecimalWithoutATag = [decimal]::Parse("3.9999999999999990", [System.Globalization.CultureInfo]::InvariantCulture) 498 | decimalInfinity = [double]::PositiveInfinity 499 | decimalNegativeInfinity = [double]::NegativeInfinity 500 | } 501 | total = 4443.52; 502 | int64 = ([int64]::MaxValue); 503 | note = ("I can't wait. To get that Cool Book.`n"); 504 | dates = @( 505 | [DateTime]::Parse('2001-12-15T02:59:43.1Z'), 506 | [DateTime]::Parse('2001-12-14t21:59:43.10-05:00'), 507 | [DateTime]::Parse('2001-12-14 21:59:43.10 -5'), 508 | [DateTime]::Parse('2001-12-15 2:59:43.10'), 509 | [DateTime]::Parse('2002-12-14') 510 | ); 511 | datesAsStrings = @( 512 | "2001-12-15T02:59:43.1Z", 513 | "2001-12-14t21:59:43.10-05:00", 514 | "2001-12-14 21:59:43.10 -5", 515 | "2001-12-15 2:59:43.10", 516 | "2002-12-14" 517 | ); 518 | version = "1.2.3"; 519 | noniso8601dates = @( '5/4/2017', '1.2.3' ); 520 | bools = @( $true, $false, $true, $false, $true, $false ); 521 | } 522 | 523 | $global:res = ConvertFrom-Yaml $testYaml 524 | } 525 | 526 | It "Should decode the YAML string as expected." { 527 | $wishlist = $res['wishlist'] 528 | $wishlist | Should -Not -BeNullOrEmpty 529 | $wishlist.Count | Should -Be 2 530 | $wishlist[0] | Should -Not -BeNullOrEmpty 531 | $wishlist[0].Count | Should -Be 4 532 | $wishlist[0][0] | Should -Be $expected['wishlist'][0][0] 533 | $wishlist[0][1] | Should -Be $expected['wishlist'][0][1] 534 | $wishlist[0][2] | Should -Be $expected['wishlist'][0][2] 535 | $wishlist[0][3] | Should -Be $expected['wishlist'][0][3] 536 | $product = $res['wishlist'][1] 537 | $product | Should -Not -BeNullOrEmpty 538 | $expectedProduct = $expected['wishlist'][1] 539 | $product['product'] | Should -Be $expectedProduct['product'] 540 | $product['quantity'] | Should -Be $expectedProduct['quantity'] 541 | $product['description'] | Should -Be $expectedProduct['description'] 542 | $product['price'] | Should -Be $expectedProduct['price'] 543 | 544 | $res['total'] | Should -Be $expected['total'] 545 | $res['note'] | Should -Be $expected['note'] 546 | 547 | $expectedIntsAndDecimals = $expected['intsAndDecimals'] 548 | 549 | $intsAndDecimals = $res['intsAndDecimals'] 550 | $intsAndDecimals['aStringTatLooksLikeAFloat'] | Should -Be $expectedIntsAndDecimals['aStringTatLooksLikeAFloat'] 551 | $intsAndDecimals['aStringTatLooksLikeAFloat'] | Should -BeOfType ([string]) 552 | $intsAndDecimals['aStringThatLooksLikeAnInt'] | Should -Be $expectedIntsAndDecimals['aStringThatLooksLikeAnInt'] 553 | $intsAndDecimals['aStringThatLooksLikeAnInt'] | Should -BeOfType ([string]) 554 | $intsAndDecimals['zeroIntWithTag'] | Should -Be $expectedIntsAndDecimals['zeroIntWithTag'] 555 | $intsAndDecimals['zeroIntWithTag'] | Should -BeOfType ([int32]) 556 | $intsAndDecimals['zeroIntWithoutTag'] | Should -Be $expectedIntsAndDecimals['zeroIntWithoutTag'] 557 | $intsAndDecimals['zeroIntWithoutTag'] | Should -BeOfType ([int32]) 558 | $intsAndDecimals['scientificNotationInt'] | Should -Be $expectedIntsAndDecimals['scientificNotationInt'] 559 | $intsAndDecimals['scientificNotationInt'] | Should -BeOfType ([int32]) 560 | $intsAndDecimals['scientificNotationBigInt'] | Should -Be $expectedIntsAndDecimals['scientificNotationBigInt'] 561 | $intsAndDecimals['scientificNotationBigInt'] | Should -BeOfType ([System.Numerics.BigInteger]) 562 | $intsAndDecimals['intWithTag'] | Should -Be $expectedIntsAndDecimals['intWithTag'] 563 | $intsAndDecimals['intWithTag'] | Should -BeOfType ([int32]) 564 | $intsAndDecimals['scientificNotationIntWithTag'] | Should -Be $expectedIntsAndDecimals['scientificNotationIntWithTag'] 565 | $intsAndDecimals['scientificNotationIntWithTag'] | Should -BeOfType ([int32]) 566 | $intsAndDecimals['aDecimalWithATag'] | Should -Be $expectedIntsAndDecimals['aDecimalWithATag'] 567 | $intsAndDecimals['aDecimalWithATag'] | Should -BeOfType ([decimal]) 568 | $intsAndDecimals['aDecimalWithoutATag'] | Should -Be $expectedIntsAndDecimals['aDecimalWithoutATag'] 569 | $intsAndDecimals['aDecimalWithoutATag'] | Should -BeOfType ([decimal]) 570 | $intsAndDecimals['decimalInfinity'] | Should -Be $expectedIntsAndDecimals['decimalInfinity'] 571 | $intsAndDecimals['decimalInfinity'] | Should -BeOfType ([double]) 572 | $intsAndDecimals['decimalNegativeInfinity'] | Should -Be $expectedIntsAndDecimals['decimalNegativeInfinity'] 573 | $intsAndDecimals['decimalNegativeInfinity'] | Should -BeOfType ([double]) 574 | 575 | $res['dates'] | Should -Not -BeNullOrEmpty 576 | $res['dates'].Count | Should -Be $expected['dates'].Count 577 | for( $idx = 0; $idx -lt $expected['dates'].Count; ++$idx ) 578 | { 579 | $res['dates'][$idx] | Should -BeOfType ([datetime]) 580 | $res['dates'][$idx] | Should -Be $expected['dates'][$idx] 581 | } 582 | 583 | $res['datesAsStrings'] | Should -Not -BeNullOrEmpty 584 | $res['datesAsStrings'].Count | Should -Be $expected['datesAsStrings'].Count 585 | for( $idx = 0; $idx -lt $expected['datesAsStrings'].Count; ++$idx ) 586 | { 587 | $res['datesAsStrings'][$idx] | Should -BeOfType ([string]) 588 | $res['datesAsStrings'][$idx] | Should -Be $expected['dates'][$idx] 589 | } 590 | 591 | $res['version'] | Should -BeOfType ([string]) 592 | $res['version'] | Should -Be $expected['version'] 593 | 594 | $res['noniso8601dates'] | Should -Not -BeNullOrEmpty 595 | $res['noniso8601dates'].Count | Should -Be $expected['noniso8601dates'].Count 596 | for( $idx = 0; $idx -lt $expected['noniso8601dates'].Count; ++$idx ) 597 | { 598 | $res['noniso8601dates'][$idx] | Should -BeOfType ([string]) 599 | $res['noniso8601dates'][$idx] | Should -Be $expected['noniso8601dates'][$idx] 600 | } 601 | 602 | Assert-Equivalent -Options $compareStrictly -Actual $res -Expected $expected 603 | } 604 | } 605 | } 606 | 607 | Describe "Test ConvertTo-Yaml can serialize more complex nesting" { 608 | BeforeAll { 609 | $global:sample = [PSCustomObject]@{ 610 | a1 = "a" 611 | a2 = [PSCustomObject]@{ 612 | "a1" = "a" 613 | a2 = [PSCustomObject]@{ 614 | a1 = [PSCustomObject]@{ 615 | "a1" = "a" 616 | a2 = [PSCustomObject]@{ 617 | a1 = "a" 618 | } 619 | a3 = [ordered]@{ 620 | a1 = @("a", "b") 621 | } 622 | a4 = @("a", "b") 623 | } 624 | } 625 | a3 = @( 626 | [PSCustomObject]@{ 627 | a1 = "a" 628 | a2 = $False 629 | } 630 | ) 631 | } 632 | } 633 | 634 | $global:sample2 = [PSCustomObject]@{ 635 | b1 = "b" 636 | b2 = [PSCustomObject]@{ 637 | b1 = "b" 638 | b2 = [PSCustomObject]@{ 639 | "b" = "b" 640 | } 641 | } 642 | b3 = [ordered]@{ 643 | b1 = @("b1", "b2") 644 | } 645 | b4 = $True 646 | b5 = [PSCustomObject]@{ 647 | b = "b" 648 | } 649 | } 650 | 651 | $global:expected_json = '{"a1":"a","a2":{"a1":"a","a2":{"a1":{"a1":"a","a2":{"a1":"a"},"a3":{"a1":["a","b"]},"a4":["a","b"]}},"a3":[{"a1":"a","a2":false}]}}' 652 | $global:expected_json2 = '{"b1":"b","b2":{"b1":"b","b2":{"b":"b"}},"b3":{"b1":["b1","b2"]},"b4":true,"b5":{"b":"b"}}' 653 | $global:expected_block_yaml = @" 654 | a1: a 655 | a2: 656 | a1: a 657 | a2: 658 | a1: 659 | a1: a 660 | a2: 661 | a1: a 662 | a3: 663 | a1: 664 | - a 665 | - b 666 | a4: 667 | - a 668 | - b 669 | a3: 670 | - a1: a 671 | a2: false 672 | 673 | "@ 674 | 675 | $global:expected_flow_yaml = '{a1: a, a2: {a1: a, a2: {a1: {a1: a, a2: {a1: a}, a3: {a1: [a, b]}, a4: [a, b]}}, a3: [{a1: a, a2: false}]}}' 676 | $global:expected_block_yaml2 = @" 677 | b1: b 678 | b2: 679 | b1: b 680 | b2: 681 | b: b 682 | b3: 683 | b1: 684 | - b1 685 | - b2 686 | b4: true 687 | b5: 688 | b: b 689 | 690 | "@ 691 | $global:expected_flow_yaml2 = '{b1: b, b2: {b1: b, b2: {b: b}}, b3: {b1: [b1, b2]}, b4: true, b5: {b: b}}' 692 | } 693 | 694 | It "Should serialize nested PSCustomObjects to YAML" { 695 | $yaml = ConvertTo-Yaml $sample 696 | $yaml | Should -Be $expected_block_yaml 697 | 698 | $yaml = ConvertTo-Yaml $sample2 699 | $yaml | Should -Be $expected_block_yaml2 700 | } 701 | 702 | It "Should serialize nested PSCustomObjects to YAML flow format" { 703 | $yaml = ConvertTo-Yaml $sample -Options UseFlowStyle 704 | $yaml.Replace($([Environment]::NewLine), "") | Should -Be $expected_flow_yaml 705 | 706 | $yaml = ConvertTo-Yaml $sample2 -Options UseFlowStyle 707 | $yaml.Replace($([Environment]::NewLine), "") | Should -Be $expected_flow_yaml2 708 | } 709 | 710 | It "Should serialize nested PSCustomObjects to JSON" { 711 | # Converted with powershell-yaml 712 | $json = ConvertTo-Yaml $sample -Options JsonCompatible 713 | $json.Replace(" ", "").Replace($([Environment]::NewLine), "") | Should -Be $expected_json 714 | 715 | # Converted with ConvertTo-Json 716 | $withJsonCommandlet = ConvertTo-Json -Compress -Depth 100 $sample 717 | $withJsonCommandlet | Should -Be $expected_json 718 | 719 | # Converted with powershell-yaml 720 | $json = ConvertTo-Yaml $sample2 -Options JsonCompatible 721 | $json.Replace(" ", "").Replace($([Environment]::NewLine), "") | Should -Be $expected_json2 722 | 723 | # Converted with ConvertTo-Json 724 | $withJsonCommandlet = ConvertTo-Json -Compress -Depth 100 $sample2 725 | $withJsonCommandlet | Should -Be $expected_json2 726 | } 727 | } 728 | 729 | Describe "Test ConvertTo-Yaml -OutFile parameter behavior" { 730 | 731 | Context "Providing -OutFile with invalid prefix." { 732 | BeforeAll { 733 | $testPath = "/some/bogus/path" 734 | $global:testObject = 42 735 | # mock Test-Path to fail so the test for the directory of the -OutFile fails: 736 | Mock Test-Path { return $false } -Verifiable -ParameterFilter { $OutFile -eq $testPath } 737 | } 738 | 739 | It "Should refuse to work with an -OutFile with an invalid prefix." { 740 | { ConvertTo-Yaml $testObject -OutFile $testPath } | Should -Throw "Parent folder for specified path does not exist" 741 | } 742 | 743 | It "Should verify that all the required mocks were called." { 744 | Assert-VerifiableMock 745 | } 746 | } 747 | 748 | Context "Providing existing -OutFile without -Force." { 749 | BeforeAll { 750 | $testPath = "/some/bogus/path" 751 | $global:testObject = "A random string this time." 752 | # mock Test-Path to succeed so the -OutFile seems to exist: 753 | Mock Test-Path { return $true } -Verifiable -ParameterFilter { $OutFile -eq $testPath } 754 | } 755 | 756 | It "Should refuse to work for an existing -OutFile but no -Force flag." { 757 | { ConvertTo-Yaml $testObject -OutFile $testPath } | Should -Throw "Target file already exists. Use -Force to overwrite." 758 | } 759 | 760 | It "Should verify that all the required mocks were called." { 761 | Assert-VerifiableMock 762 | } 763 | } 764 | 765 | Context "Providing a valid -OutFile." { 766 | BeforeAll { 767 | $global:testObject = @{ yes = "No"; "arr" = @(1, 2, 3) } 768 | $testPath = [System.IO.Path]::GetTempFileName() 769 | Remove-Item -Force $testPath # must be deleted for the test 770 | } 771 | 772 | It "Should succesfully write the expected content to the specified -OutFile." { 773 | $yaml = ConvertTo-Yaml $testObject 774 | ConvertTo-Yaml $testObject -OutFile $testPath 775 | 776 | Compare-Object $yaml (Get-Content -Raw $testPath) | Should -Be $null 777 | 778 | } 779 | 780 | # NOTE: the below assertion relies on the above writing its file. 781 | It "Should succesfully write the expected content to the specified -OutFile with -Force even if it exists." { 782 | $newTestObject = @(1, "two", @("arr", "ay"), @{ yes = "no"; answer = 42 }) 783 | 784 | $yaml = ConvertTo-Yaml $newTestObject 785 | ConvertTo-Yaml $newTestObject -OutFile $testPath -Force 786 | 787 | Compare-Object $yaml (Get-Content -Raw $testPath) | Should -Be $null 788 | } 789 | } 790 | 791 | } 792 | 793 | Describe "Generic Casting Behaviour" { 794 | Context "Node Style is 'Plain'" { 795 | BeforeAll { 796 | $global:value = @' 797 | T1: 001 798 | '@ 799 | } 800 | 801 | It 'Should be an int' { 802 | $result = ConvertFrom-Yaml -Yaml $value 803 | $result.T1 | Should -BeOfType System.Int32 804 | } 805 | 806 | It 'Should be value of 1' { 807 | $result = ConvertFrom-Yaml -Yaml $value 808 | $result.T1 | Should -Be 1 809 | } 810 | 811 | It 'Should not be value of 001' { 812 | $result = ConvertFrom-Yaml -Yaml $value 813 | $result.T1 | Should -Not -Be '001' 814 | } 815 | } 816 | 817 | Context "Node Style is 'SingleQuoted'" { 818 | BeforeAll { 819 | $global:value = @' 820 | T1: '001' 821 | '@ 822 | } 823 | 824 | It 'Should be a string' { 825 | $result = ConvertFrom-Yaml -Yaml $value 826 | $result.T1 | Should -BeOfType System.String 827 | } 828 | 829 | It 'Should be value of 001' { 830 | $result = ConvertFrom-Yaml -Yaml $value 831 | $result.T1 | Should -Be '001' 832 | } 833 | 834 | It 'Should not be value of 1' { 835 | $result = ConvertFrom-Yaml -Yaml $value 836 | $result.T1 | Should -Not -Be '1' 837 | } 838 | } 839 | 840 | Context "Node Style is 'DoubleQuoted'" { 841 | BeforeAll { 842 | $global:value = @' 843 | T1: "001" 844 | '@ 845 | } 846 | 847 | It 'Should be a string' { 848 | $result = ConvertFrom-Yaml -Yaml $value 849 | $result.T1 | Should -BeOfType System.String 850 | } 851 | 852 | It 'Should be value of 001' { 853 | $result = ConvertFrom-Yaml -Yaml $value 854 | $result.T1 | Should -Be '001' 855 | } 856 | 857 | It 'Should not be value of 1' { 858 | $result = ConvertFrom-Yaml -Yaml $value 859 | $result.T1 | Should -Not -Be '1' 860 | } 861 | } 862 | } 863 | 864 | Describe 'Strings containing other primitives' { 865 | Context 'String contains an int' { 866 | BeforeAll { 867 | $global:value = @{key="1"} 868 | } 869 | It 'Should serialise with double quotes' { 870 | $result = ConvertTo-Yaml $value 871 | $result | Should -Be "key: ""1""$([Environment]::NewLine)" 872 | } 873 | } 874 | Context 'String contains a float' { 875 | BeforeAll { 876 | $global:value = @{key="0.25"} 877 | } 878 | It 'Should serialise with double quotes' { 879 | $result = ConvertTo-Yaml $value 880 | $result | Should -Be "key: ""0.25""$([Environment]::NewLine)" 881 | } 882 | } 883 | Context 'String is "true"' { 884 | BeforeAll { 885 | $global:value = @{key="true"} 886 | } 887 | It 'Should serialise with double quotes' { 888 | $result = ConvertTo-Yaml $value 889 | $result | Should -Be "key: ""true""$([Environment]::NewLine)" 890 | } 891 | } 892 | Context 'String is "false"' { 893 | BeforeAll { 894 | $global:value = @{key="false"} 895 | } 896 | It 'Should serialise with double quotes' { 897 | $result = ConvertTo-Yaml $value 898 | $result | Should -Be "key: ""false""$([Environment]::NewLine)" 899 | } 900 | } 901 | Context 'String is "null"' { 902 | BeforeAll { 903 | $global:value = @{key="null"} 904 | } 905 | It 'Should serialise with double quotes' { 906 | $result = ConvertTo-Yaml $value 907 | $result | Should -Be "key: ""null""$([Environment]::NewLine)" 908 | } 909 | } 910 | Context 'String is "~" (alternative syntax for null)' { 911 | BeforeAll { 912 | $global:value = @{key="~"} 913 | } 914 | It 'Should serialise with double quotes' { 915 | $result = ConvertTo-Yaml $value 916 | $result | Should -Be "key: ""~""$([Environment]::NewLine)" 917 | } 918 | } 919 | Context 'String is empty' { 920 | BeforeAll { 921 | $global:value = @{key=""} 922 | } 923 | It 'Should serialise with double quotes' { 924 | $result = ConvertTo-Yaml $value 925 | $result | Should -Be "key: """"$([Environment]::NewLine)" 926 | } 927 | } 928 | } 929 | 930 | Describe 'Numbers are parsed as the smallest type possible' { 931 | BeforeAll { 932 | $global:value = @' 933 | bigInt: 99999999999999999999999999999999999 934 | int32: 2147483647 935 | int64: 9223372036854775807 936 | decimal: 3.10 937 | reallyLongDecimal: 3.9999999999999990 938 | '@ 939 | } 940 | 941 | It 'Should be a BigInt' { 942 | $result = ConvertFrom-Yaml -Yaml $value 943 | $result.bigInt | Should -BeOfType System.Numerics.BigInteger 944 | } 945 | 946 | It "Should round-trip decimals with trailing 0" { 947 | $result = ConvertFrom-Yaml -Yaml $value 948 | $result.decimal | Should -Be ([decimal]3.10) 949 | $result.reallyLongDecimal | Should -Be ([decimal]::Parse("3.9999999999999990", [cultureinfo]::InvariantCulture)) 950 | 951 | ConvertTo-Yaml $result["decimal"] | Should -Be "3.10$([Environment]::NewLine)" 952 | ConvertTo-Yaml $result["reallyLongDecimal"] | Should -Be "3.9999999999999990$([Environment]::NewLine)" 953 | } 954 | 955 | It 'Should be of proper type and value' { 956 | $result = ConvertFrom-Yaml -Yaml $value 957 | $result.bigInt | Should -Be ([System.Numerics.BigInteger]::Parse("99999999999999999999999999999999999")) 958 | $result.int32 | Should -Be ([int32]2147483647) 959 | $result.int64 | Should -Be ([int64]9223372036854775807) 960 | $result.decimal | Should -Be ([decimal]3.10) 961 | } 962 | } 963 | 964 | Describe 'PSCustomObjects' { 965 | Context 'Classes with PSCustomObjects' { 966 | It 'Should serialise as a hash' { 967 | $nestedPsO = [PSCustomObject]@{ 968 | Nested = 'NestedValue' 969 | } 970 | $nestedHashTable = @{ 971 | "aKey" = $nestedPsO 972 | } 973 | $nestedArray = @( 974 | $nestedPsO 975 | ) 976 | $PsO = [PSCustomObject]@{ 977 | Name = 'Value' 978 | Nested = $nestedPsO 979 | NestedHashTable = $nestedHashTable 980 | NestedArray = $nestedArray 981 | NullValue = $null 982 | } 983 | 984 | class TestClass { 985 | [PSCustomObject]$PsO 986 | [string]$Ok 987 | } 988 | $Class = [TestClass]@{ 989 | PsO = $PsO 990 | Ok = 'aye' 991 | } 992 | $asYaml = ConvertTo-Yaml $Class 993 | $result = ConvertFrom-Yaml -Yaml $asYaml -Ordered 994 | [System.Collections.Specialized.OrderedDictionary]$ret = [System.Collections.Specialized.OrderedDictionary]::new() 995 | $ret["PsO"] = [System.Collections.Specialized.OrderedDictionary]::new() 996 | $ret["PsO"]["Name"] = "Value" 997 | $ret["PsO"]["Nested"] = [System.Collections.Specialized.OrderedDictionary]::new() 998 | $ret["PsO"]["Nested"]["Nested"] = "NestedValue" 999 | $ret["PsO"]["NestedHashTable"] = [ordered]@{ 1000 | "aKey" = [ordered]@{ 1001 | "Nested" = "NestedValue" 1002 | } 1003 | } 1004 | $ret["PsO"]["NestedArray"] = @( 1005 | [ordered]@{ 1006 | "Nested" = "NestedValue" 1007 | } 1008 | ) 1009 | $ret["PsO"]["NullValue"] = $null 1010 | $ret["Ok"] = "aye" 1011 | Assert-Equivalent -Options $compareStrictly -Expected $ret -Actual $result 1012 | } 1013 | } 1014 | 1015 | Context 'PSObject with null value is skipped when -Options OmitNullValues' { 1016 | BeforeAll { 1017 | $global:value = [PSCustomObject]@{ 1018 | key1 = "value1" 1019 | key2 = $null 1020 | } 1021 | } 1022 | It 'Should serialise as a hash with only the non-null value' { 1023 | $result = ConvertTo-Yaml $value -Options OmitNullValues 1024 | $result | Should -Be "key1: value1$([Environment]::NewLine)" 1025 | } 1026 | } 1027 | 1028 | Context 'PSObject with null value is included when -Options OmitNullValues is not set' { 1029 | BeforeAll { 1030 | $global:value = [PSCustomObject]@{ 1031 | key1 = "value1" 1032 | key2 = $null 1033 | } 1034 | } 1035 | It 'Should serialise as a hash with the null value' { 1036 | $result = ConvertTo-Yaml $value 1037 | $result | Should -Be "key1: value1$([Environment]::NewLine)key2: $null$([Environment]::NewLine)" 1038 | } 1039 | } 1040 | 1041 | Context 'PSCustomObject with a single property' { 1042 | BeforeAll { 1043 | $global:value = [PSCustomObject]@{key="value"} 1044 | } 1045 | It 'Should serialise as a hash' { 1046 | $result = ConvertTo-Yaml $value 1047 | $result | Should -Be "key: value$([Environment]::NewLine)" 1048 | } 1049 | } 1050 | Context 'PSCustomObject with multiple properties' { 1051 | BeforeAll { 1052 | $global:value = [PSCustomObject]@{key1="value1"; key2="value2"} 1053 | } 1054 | It 'Should serialise as a hash' { 1055 | $result = ConvertTo-Yaml $value 1056 | $result | Should -Be "key1: value1$([Environment]::NewLine)key2: value2$([Environment]::NewLine)" 1057 | } 1058 | It 'Should deserialise as a hash' { 1059 | $asYaml = ConvertTo-Yaml $value 1060 | $result = ConvertFrom-Yaml -Yaml $asYaml -Ordered 1061 | Assert-Equivalent -Options $compareStrictly -Expected @{key1="value1"; key2="value2"} -Actual ([hashtable]$result) 1062 | } 1063 | } 1064 | } 1065 | 1066 | Describe 'StringQuotingEmitter' { 1067 | BeforeAll { 1068 | $oldYamlPkgUrl = 'https://www.nuget.org/api/v2/package/YamlDotNet/11.2.1' 1069 | $pkgPath = Join-Path -Path $TestDrive -ChildPath 'YamlDotNet-11.2.1.nupkg' 1070 | $oldYamlPkgDirPath = Join-Path -Path $TestDrive -ChildPath 'YamlDotNet-11.2.1' 1071 | $ProgressPreference = 'SilentlyContinue' 1072 | Invoke-WebRequest -Uri $oldYamlPkgUrl -UseBasicParsing -OutFile $pkgPath 1073 | New-Item -Path $oldYamlPkgDirPath -ItemType Directory 1074 | Add-Type -AssemblyName 'System.IO.Compression.FileSystem' 1075 | [IO.Compression.ZipFile]::ExtractToDirectory($pkgPath, $oldYamlPkgDirPath) 1076 | } 1077 | 1078 | $targetFrameworks = @('net45', 'netstandard1.3') 1079 | if ($PSVersionTable['PSEdition'] -eq 'Core') 1080 | { 1081 | $targetFrameworks = @('netstandard1.3', 'netstandard2.1') 1082 | } 1083 | 1084 | It 'can be compiled on import with <_>/YamlDotNet.dll loaded' -ForEach $targetFrameworks { 1085 | $targetFramework = $_ 1086 | $yamlDotnetAssemblyPath = 1087 | Join-Path -Path $TestDrive -ChildPath "YamlDotNet-11.2.1\lib\${targetFramework}\YamlDotNet.dll" -Resolve 1088 | $modulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\powershell-yaml.psd1' -Resolve 1089 | 1090 | { 1091 | # Do this in the background because YamlDotNet.dll is already loaded in this session and the way we 1092 | # found to reproduce this issue is by loading YamlDotNet 11.2.1 then importing powershell-yaml. 1093 | Start-Job { 1094 | $yamlDotnetAssemblyPath = $using:yamlDotnetAssemblyPath 1095 | $modulePath = $using:modulePath 1096 | 1097 | Add-Type -Path $yamlDotnetAssemblyPath 1098 | Import-Module $modulePath 1099 | } | Receive-Job -Wait -AutoRemoveJob -ErrorAction Stop 1100 | } | Should -Not -Throw 1101 | } 1102 | } 1103 | } 1104 | -------------------------------------------------------------------------------- /build.ps1: -------------------------------------------------------------------------------- 1 | # Copyright 2016-2024 Cloudbase Solutions Srl 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | # 15 | 16 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 17 | 18 | dotnet build --configuration Release $here/src/ 19 | 20 | $destinations = @("netstandard2.1", "net47") 21 | 22 | foreach ($item in $destinations) { 23 | $src = Join-Path $here "src" "bin" "Release" $item "PowerShellYamlSerializer.dll" 24 | $dst = Join-Path $here "lib" $item "PowerShellYamlSerializer.dll" 25 | 26 | Copy-Item -Force $src $dst 27 | } 28 | -------------------------------------------------------------------------------- /lib/net47/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Antoine Aubry and contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /lib/net47/PowerShellYamlSerializer.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudbase/powershell-yaml/e54508c83ed969d47584e6db7013fc1d2784d080/lib/net47/PowerShellYamlSerializer.dll -------------------------------------------------------------------------------- /lib/net47/YamlDotNet.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudbase/powershell-yaml/e54508c83ed969d47584e6db7013fc1d2784d080/lib/net47/YamlDotNet.dll -------------------------------------------------------------------------------- /lib/netstandard2.1/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Antoine Aubry and contributors 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /lib/netstandard2.1/PowerShellYamlSerializer.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudbase/powershell-yaml/e54508c83ed969d47584e6db7013fc1d2784d080/lib/netstandard2.1/PowerShellYamlSerializer.dll -------------------------------------------------------------------------------- /lib/netstandard2.1/YamlDotNet.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cloudbase/powershell-yaml/e54508c83ed969d47584e6db7013fc1d2784d080/lib/netstandard2.1/YamlDotNet.dll -------------------------------------------------------------------------------- /powershell-yaml.psd1: -------------------------------------------------------------------------------- 1 | # Copyright 2016-2024 Cloudbase Solutions Srl 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | # 15 | # Module manifest for module 'powershell-yaml' 16 | # 17 | # Generated by: Gabriel Adrian Samfira 18 | # 19 | # Generated on: 10/01/2016 20 | # 21 | 22 | @{ 23 | 24 | # Script module or binary module file associated with this manifest. 25 | RootModule = 'powershell-yaml.psm1' 26 | 27 | # Version number of this module. 28 | ModuleVersion = '0.4.12' 29 | 30 | PrivateData = @{ 31 | PSData = @{ 32 | LicenseUri = 'https://github.com/cloudbase/powershell-yaml/blob/master/LICENSE' 33 | ProjectUri = 'https://github.com/cloudbase/powershell-yaml' 34 | ReleaseNotes = @' 35 | # 0.4.12 36 | 37 | Bugfixes: 38 | * Fix potential erroneous load of assembly by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/180 39 | 40 | # 0.4.11 41 | 42 | Bugfixes: 43 | * Fix nested PSCustomObjects in hashtables by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/169 44 | * Use decimal as first option when parsing floats by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/170. Thanks @amis92 for the suggestion! 45 | * Fix lint errors by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/172 46 | * Use decimals instead of double for tagged floats by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/174 47 | 48 | Misc: 49 | * Add aditional tests by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/171 50 | * Update README.md by @gabriel-samfira in https://github.com/cloudbase/powershell-yaml/pull/173 51 | 52 | # 0.4.10 53 | 54 | Bugfixes: 55 | * A broken if statement mistakingly considered 0 as false and converted a 0 valued int to BigInteger (https://github.com/cloudbase/powershell-yaml/pull/165). 56 | * Fixes JSONCompatible flag after we implemented an IDictionary and PSCustomObject type converters (https://github.com/cloudbase/powershell-yaml/pull/166). 57 | 58 | # 0.4.9 59 | 60 | Changes in this version: 61 | * Revert commit 7980c7c "Fix losing case sensitive keys" (https://github.com/cloudbase/powershell-yaml/pull/159) . This change added a breaking change which was not properly documented before release, breaking some applications. This change will be re-added in a later version. 62 | * Unwrap PScustomObjects before serializing (https://github.com/cloudbase/powershell-yaml/pull/158) 63 | '@ 64 | } 65 | } 66 | 67 | # ID used to uniquely identify this module 68 | GUID = '6a75a662-7f53-425a-9777-ee61284407da' 69 | 70 | # Author of this module 71 | Author = 'Gabriel Adrian Samfira','Alessandro Pilotti' 72 | 73 | # Company or vendor of this module 74 | CompanyName = 'Cloudbase Solutions SRL' 75 | 76 | # Copyright statement for this module 77 | Copyright = '(c) 2016-2024 Cloudbase Solutions SRL. All rights reserved.' 78 | 79 | # Description of the functionality provided by this module 80 | Description = 'Powershell module for serializing and deserializing YAML' 81 | 82 | # Minimum version of the Windows PowerShell engine required by this module 83 | PowerShellVersion = '5.0' 84 | 85 | # Functions to export from this module 86 | FunctionsToExport = "ConvertTo-Yaml","ConvertFrom-Yaml" 87 | 88 | AliasesToExport = "cfy","cty" 89 | } 90 | -------------------------------------------------------------------------------- /powershell-yaml.psm1: -------------------------------------------------------------------------------- 1 | # Copyright 2016-2024 Cloudbase Solutions Srl 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); you may 4 | # not use this file except in compliance with the License. You may obtain 5 | # a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 | # License for the specific language governing permissions and limitations 13 | # under the License. 14 | # 15 | 16 | [Flags()] 17 | enum SerializationOptions { 18 | None = 0 19 | Roundtrip = 1 20 | DisableAliases = 2 21 | EmitDefaults = 4 22 | JsonCompatible = 8 23 | DefaultToStaticType = 16 24 | WithIndentedSequences = 32 25 | OmitNullValues = 64 26 | UseFlowStyle = 128 27 | UseSequenceFlowStyle = 256 28 | } 29 | $here = Split-Path -Parent $MyInvocation.MyCommand.Path 30 | $infinityRegex = [regex]::new('^[-+]?(\.inf|\.Inf|\.INF)$', "Compiled, CultureInvariant"); 31 | 32 | function Invoke-LoadFile { 33 | param( 34 | [string]$assemblyPath 35 | ) 36 | 37 | $powershellYamlDotNetAssemblyPath = Join-Path $assemblyPath "YamlDotNet.dll" 38 | $serializerAssemblyPath = Join-Path $assemblyPath "PowerShellYamlSerializer.dll" 39 | $yamlAssembly = [Reflection.Assembly]::LoadFile($powershellYamlDotNetAssemblyPath) 40 | $serializerAssembly = [Reflection.Assembly]::LoadFile($serializerAssemblyPath) 41 | 42 | if ($PSVersionTable['PSEdition'] -eq 'Core') { 43 | # Register the AssemblyResolve event to load dependencies manually. This seems to be needed only on 44 | # PowerShell Core. 45 | $resolver = { 46 | param ($snd, $e) 47 | # This event only needs to run once when the Invoke-LoadFile function is called. 48 | # If it's called again, the variables defined in this functions will not be available, 49 | # so we can safely ignore the event. 50 | if (-not $serializerAssemblyPath -or -not $powershellYamlDotNetAssemblyPath) { 51 | return $null 52 | } 53 | # Load YamlDotNet if it's requested by PowerShellYamlSerializer. Ignore other requests as they might 54 | # originate from other assemblies that are not part of this module and which might have different 55 | # versions of the module that they need to load. 56 | if ($e.Name -match "^YamlDotNet,*" -and $e.RequestingAssembly.Location -eq $serializerAssemblyPath) { 57 | return [System.Reflection.Assembly]::LoadFile($powershellYamlDotNetAssemblyPath) 58 | } 59 | 60 | return $null 61 | } 62 | [System.AppDomain]::CurrentDomain.add_AssemblyResolve($resolver) 63 | # Load the StringQuotingEmitter from PowerShellYamlSerializer to force the resolver handler to fire once. 64 | # This is an ugly hack I am not happy with. 65 | $serializerAssembly.GetType("StringQuotingEmitter") | Out-Null 66 | 67 | # Remove the resolver handler after it has been used. 68 | [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($resolver) 69 | } 70 | 71 | return @{ "yaml"= $yamlAssembly; "quoted" = $serializerAssembly } 72 | } 73 | 74 | function Invoke-LoadAssembly { 75 | $libDir = Join-Path $here "lib" 76 | $assemblies = @{ 77 | "core" = Join-Path $libDir "netstandard2.1"; 78 | "net47" = Join-Path $libDir "net47"; 79 | } 80 | 81 | if ($PSVersionTable.Keys -contains "PSEdition") { 82 | if ($PSVersionTable.PSEdition -eq "Core") { 83 | return (Invoke-LoadFile -assemblyPath $assemblies["core"]) 84 | } 85 | return (Invoke-LoadFile -assemblyPath $assemblies["net47"]) 86 | } else { 87 | return (Invoke-LoadFile -assemblyPath $assemblies["net47"]) 88 | } 89 | } 90 | 91 | $assemblies = Invoke-LoadAssembly 92 | 93 | $yamlDotNetAssembly = $assemblies["yaml"] 94 | $stringQuotedAssembly = $assemblies["quoted"] 95 | 96 | function Get-YamlDocuments { 97 | [CmdletBinding()] 98 | Param( 99 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 100 | [string]$Yaml, 101 | [switch]$UseMergingParser=$false 102 | ) 103 | PROCESS { 104 | $stringReader = new-object System.IO.StringReader($Yaml) 105 | $parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.Parser") 106 | $parser = $parserType::new($stringReader) 107 | if($UseMergingParser) { 108 | $parserType = $yamlDotNetAssembly.GetType("YamlDotNet.Core.MergingParser") 109 | $parser = $parserType::new($parser) 110 | } 111 | 112 | $yamlStream = $yamlDotNetAssembly.GetType("YamlDotNet.RepresentationModel.YamlStream")::new() 113 | $yamlStream.Load($parser) 114 | 115 | $stringReader.Close() 116 | 117 | return $yamlStream 118 | } 119 | } 120 | 121 | function Convert-ValueToProperType { 122 | [CmdletBinding()] 123 | Param( 124 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)] 125 | [System.Object]$Node 126 | ) 127 | PROCESS { 128 | if (!($Node.Value -is [string])) { 129 | return $Node 130 | } 131 | $intTypes = @([int], [long]) 132 | if ([string]::IsNullOrEmpty($Node.Tag) -eq $false) { 133 | switch($Node.Tag) { 134 | "tag:yaml.org,2002:str" { 135 | return $Node.Value 136 | } 137 | "tag:yaml.org,2002:null" { 138 | return $null 139 | } 140 | "tag:yaml.org,2002:bool" { 141 | $parsedValue = $false 142 | if (![boolean]::TryParse($Node.Value, [ref]$parsedValue)) { 143 | Throw ("failed to parse scalar {0} as boolean" -f $Node) 144 | } 145 | return $parsedValue 146 | } 147 | "tag:yaml.org,2002:int" { 148 | $parsedValue = 0 149 | if ($node.Value.Length -gt 2) { 150 | switch ($node.Value.Substring(0, 2)) { 151 | "0o" { 152 | $parsedValue = [Convert]::ToInt64($Node.Value.Substring(2), 8) 153 | } 154 | "0x" { 155 | $parsedValue = [Convert]::ToInt64($Node.Value.Substring(2), 16) 156 | } 157 | default { 158 | if (![System.Numerics.BigInteger]::TryParse($Node.Value, @([Globalization.NumberStyles]::Float, [Globalization.NumberStyles]::Integer), [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)) { 159 | Throw ("failed to parse scalar {0} as long" -f $Node) 160 | } 161 | } 162 | } 163 | } else { 164 | if (![System.Numerics.BigInteger]::TryParse($Node.Value, @([Globalization.NumberStyles]::Float, [Globalization.NumberStyles]::Integer), [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)) { 165 | Throw ("failed to parse scalar {0} as long" -f $Node) 166 | } 167 | } 168 | foreach ($i in $intTypes) { 169 | $asIntType = $parsedValue -as $i 170 | if($null -ne $asIntType) { 171 | return $asIntType 172 | } 173 | } 174 | return $parsedValue 175 | } 176 | "tag:yaml.org,2002:float" { 177 | $parsedValue = 0.0 178 | if ($infinityRegex.Matches($Node.Value).Count -gt 0) { 179 | $prefix = $Node.Value.Substring(0, 1) 180 | switch ($prefix) { 181 | "-" { 182 | return [double]::NegativeInfinity 183 | } 184 | default { 185 | # Prefix is either missing or is a + 186 | return [double]::PositiveInfinity 187 | } 188 | } 189 | } 190 | if (![decimal]::TryParse($Node.Value, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue)) { 191 | Throw ("failed to parse scalar {0} as decimal" -f $Node) 192 | } 193 | return $parsedValue 194 | } 195 | "tag:yaml.org,2002:timestamp" { 196 | # From the YAML spec: http://yaml.org/type/timestamp.html 197 | [DateTime]$parsedValue = [DateTime]::MinValue 198 | $ts = [DateTime]::SpecifyKind($Node.Value, [System.DateTimeKind]::Utc) 199 | $tss = $ts.ToString("o") 200 | if(![datetime]::TryParse($tss, $null, [System.Globalization.DateTimeStyles]::RoundtripKind, [ref] $parsedValue)) { 201 | Throw ("failed to parse scalar {0} as DateTime" -f $Node) 202 | } 203 | return $parsedValue 204 | } 205 | } 206 | } 207 | 208 | if ($Node.Style -eq 'Plain') { 209 | $parsedValue = New-Object -TypeName ([Boolean].FullName) 210 | $result = [boolean]::TryParse($Node,[ref]$parsedValue) 211 | if( $result ) { 212 | return $parsedValue 213 | } 214 | 215 | $parsedValue = New-Object -TypeName ([System.Numerics.BigInteger].FullName) 216 | $result = [System.Numerics.BigInteger]::TryParse($Node, @([Globalization.NumberStyles]::Float, [Globalization.NumberStyles]::Integer), [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue) 217 | if($result) { 218 | $types = @([int], [long]) 219 | foreach($i in $types){ 220 | $asType = $parsedValue -as $i 221 | if($null -ne $asType) { 222 | return $asType 223 | } 224 | } 225 | return $parsedValue 226 | } 227 | $types = @([decimal], [double]) 228 | foreach($i in $types){ 229 | $parsedValue = New-Object -TypeName $i.FullName 230 | $result = $i::TryParse($Node, [Globalization.NumberStyles]::Float, [Globalization.CultureInfo]::InvariantCulture, [ref]$parsedValue) 231 | if( $result ) { 232 | return $parsedValue 233 | } 234 | } 235 | } 236 | 237 | if ($Node.Style -eq 'Plain' -and $Node.Value -in '','~','null','Null','NULL') { 238 | return $null 239 | } 240 | 241 | return $Node.Value 242 | } 243 | } 244 | 245 | function Convert-YamlMappingToHashtable { 246 | [CmdletBinding()] 247 | Param( 248 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 249 | $Node, 250 | [switch] $Ordered 251 | ) 252 | PROCESS { 253 | if ($Ordered) { $ret = [ordered]@{} } else { $ret = @{} } 254 | foreach($i in $Node.Children.Keys) { 255 | $ret[$i.Value] = Convert-YamlDocumentToPSObject $Node.Children[$i] -Ordered:$Ordered 256 | } 257 | return $ret 258 | } 259 | } 260 | 261 | function Convert-YamlSequenceToArray { 262 | [CmdletBinding()] 263 | Param( 264 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 265 | $Node, 266 | [switch]$Ordered 267 | ) 268 | PROCESS { 269 | $ret = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]") 270 | foreach($i in $Node.Children){ 271 | $ret.Add((Convert-YamlDocumentToPSObject $i -Ordered:$Ordered)) 272 | } 273 | return ,$ret 274 | } 275 | } 276 | 277 | function Convert-YamlDocumentToPSObject { 278 | [CmdletBinding()] 279 | Param( 280 | [Parameter(Mandatory=$true, ValueFromPipeline=$true)] 281 | [System.Object]$Node, 282 | [switch]$Ordered 283 | ) 284 | PROCESS { 285 | switch($Node.GetType().FullName){ 286 | "YamlDotNet.RepresentationModel.YamlMappingNode"{ 287 | return Convert-YamlMappingToHashtable $Node -Ordered:$Ordered 288 | } 289 | "YamlDotNet.RepresentationModel.YamlSequenceNode" { 290 | return Convert-YamlSequenceToArray $Node -Ordered:$Ordered 291 | } 292 | "YamlDotNet.RepresentationModel.YamlScalarNode" { 293 | return (Convert-ValueToProperType $Node) 294 | } 295 | } 296 | } 297 | } 298 | 299 | function Convert-HashtableToDictionary { 300 | Param( 301 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)] 302 | [hashtable]$Data 303 | ) 304 | foreach($i in $($data.PSBase.Keys)) { 305 | $Data[$i] = Convert-PSObjectToGenericObject $Data[$i] 306 | } 307 | return $Data 308 | } 309 | 310 | function Convert-OrderedHashtableToDictionary { 311 | Param( 312 | [Parameter(Mandatory=$true,ValueFromPipeline=$true)] 313 | [System.Collections.Specialized.OrderedDictionary] $Data 314 | ) 315 | foreach ($i in $($data.PSBase.Keys)) { 316 | $Data[$i] = Convert-PSObjectToGenericObject $Data[$i] 317 | } 318 | return $Data 319 | } 320 | 321 | function Convert-ListToGenericList { 322 | Param( 323 | [Parameter(Mandatory=$false,ValueFromPipeline=$true)] 324 | [array]$Data=@() 325 | ) 326 | $ret = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]") 327 | for($i=0; $i -lt $Data.Count; $i++) { 328 | $ret.Add((Convert-PSObjectToGenericObject $Data[$i])) 329 | } 330 | return ,$ret 331 | } 332 | 333 | function Convert-PSObjectToGenericObject { 334 | Param( 335 | [Parameter(Mandatory=$false,ValueFromPipeline=$true)] 336 | [System.Object]$Data 337 | ) 338 | 339 | if ($null -eq $data) { 340 | return $data 341 | } 342 | 343 | $dataType = $data.GetType() 344 | if (([System.Collections.Specialized.OrderedDictionary].IsAssignableFrom($dataType))){ 345 | return Convert-OrderedHashtableToDictionary $data 346 | } elseif (([System.Collections.IDictionary].IsAssignableFrom($dataType))){ 347 | return Convert-HashtableToDictionary $data 348 | } elseif (([System.Collections.IList].IsAssignableFrom($dataType))) { 349 | return Convert-ListToGenericList $data 350 | } 351 | return $data 352 | } 353 | 354 | function ConvertFrom-Yaml { 355 | [CmdletBinding()] 356 | Param( 357 | [Parameter(Mandatory=$false, ValueFromPipeline=$true, Position=0)] 358 | [string]$Yaml, 359 | [switch]$AllDocuments=$false, 360 | [switch]$Ordered, 361 | [switch]$UseMergingParser=$false 362 | ) 363 | 364 | BEGIN { 365 | $d = "" 366 | } 367 | PROCESS { 368 | if($Yaml -is [string]) { 369 | $d += $Yaml + "`n" 370 | } 371 | } 372 | 373 | END { 374 | if($d -eq ""){ 375 | return 376 | } 377 | $documents = Get-YamlDocuments -Yaml $d -UseMergingParser:$UseMergingParser 378 | if (!$documents.Count) { 379 | return 380 | } 381 | if($documents.Count -eq 1){ 382 | return Convert-YamlDocumentToPSObject $documents[0].RootNode -Ordered:$Ordered 383 | } 384 | if(!$AllDocuments) { 385 | return Convert-YamlDocumentToPSObject $documents[0].RootNode -Ordered:$Ordered 386 | } 387 | $ret = @() 388 | foreach($i in $documents) { 389 | $ret += Convert-YamlDocumentToPSObject $i.RootNode -Ordered:$Ordered 390 | } 391 | return $ret 392 | } 393 | } 394 | 395 | function Get-Serializer { 396 | Param( 397 | [Parameter(Mandatory=$true)][SerializationOptions]$Options 398 | ) 399 | 400 | $builder = $yamlDotNetAssembly.GetType("YamlDotNet.Serialization.SerializerBuilder")::new() 401 | $JsonCompatible = $Options.HasFlag([SerializationOptions]::JsonCompatible) 402 | 403 | if ($Options.HasFlag([SerializationOptions]::Roundtrip)) { 404 | $builder = $builder.EnsureRoundtrip() 405 | } 406 | if ($Options.HasFlag([SerializationOptions]::DisableAliases)) { 407 | $builder = $builder.DisableAliases() 408 | } 409 | if ($Options.HasFlag([SerializationOptions]::EmitDefaults)) { 410 | $builder = $builder.EmitDefaults() 411 | } 412 | if ($JsonCompatible) { 413 | $builder = $builder.JsonCompatible() 414 | } 415 | if ($Options.HasFlag([SerializationOptions]::DefaultToStaticType)) { 416 | $resolver = $yamlDotNetAssembly.GetType("YamlDotNet.Serialization.TypeResolvers.StaticTypeResolver")::new() 417 | $builder = $builder.WithTypeResolver($resolver) 418 | } 419 | if ($Options.HasFlag([SerializationOptions]::WithIndentedSequences)) { 420 | $builder = $builder.WithIndentedSequences() 421 | } 422 | 423 | $omitNull = $Options.HasFlag([SerializationOptions]::OmitNullValues) 424 | $useFlowStyle = $Options.HasFlag([SerializationOptions]::UseFlowStyle) 425 | $useSequenceFlowStyle = $Options.HasFlag([SerializationOptions]::UseSequenceFlowStyle) 426 | 427 | $stringQuoted = $stringQuotedAssembly.GetType("BuilderUtils") 428 | $builder = $stringQuoted::BuildSerializer($builder, $omitNull, $useFlowStyle, $useSequenceFlowStyle, $JsonCompatible) 429 | 430 | return $builder.Build() 431 | } 432 | 433 | function ConvertTo-Yaml { 434 | [CmdletBinding(DefaultParameterSetName = 'NoOptions')] 435 | Param( 436 | [Parameter(ValueFromPipeline = $true, Position=0)] 437 | [System.Object]$Data, 438 | 439 | [string]$OutFile, 440 | 441 | [Parameter(ParameterSetName = 'Options')] 442 | [SerializationOptions]$Options = [SerializationOptions]::Roundtrip, 443 | 444 | [Parameter(ParameterSetName = 'NoOptions')] 445 | [switch]$JsonCompatible, 446 | [switch]$UseFlowStyle, 447 | 448 | [switch]$KeepArray, 449 | 450 | [switch]$Force 451 | ) 452 | BEGIN { 453 | $d = [System.Collections.Generic.List[object]](New-Object "System.Collections.Generic.List[object]") 454 | } 455 | PROCESS { 456 | if($data -is [System.Object]) { 457 | $d.Add($data) 458 | } 459 | } 460 | END { 461 | if ($d -eq $null -or $d.Count -eq 0) { 462 | return 463 | } 464 | if ($d.Count -eq 1 -and !($KeepArray)) { 465 | $d = $d[0] 466 | } 467 | $norm = Convert-PSObjectToGenericObject $d 468 | if ($OutFile) { 469 | $parent = Split-Path $OutFile 470 | if (!(Test-Path $parent)) { 471 | Throw "Parent folder for specified path does not exist" 472 | } 473 | if ((Test-Path $OutFile) -and !$Force) { 474 | Throw "Target file already exists. Use -Force to overwrite." 475 | } 476 | $wrt = New-Object "System.IO.StreamWriter" $OutFile 477 | } else { 478 | $wrt = New-Object "System.IO.StringWriter" 479 | } 480 | 481 | if ($PSCmdlet.ParameterSetName -eq 'NoOptions') { 482 | $Options = 0 483 | if ($JsonCompatible) { 484 | # No indent options :~( 485 | $Options = [SerializationOptions]::JsonCompatible 486 | } 487 | } 488 | 489 | try { 490 | $serializer = Get-Serializer $Options 491 | $serializer.Serialize($wrt, $norm) 492 | } 493 | catch{ 494 | $_ 495 | } 496 | finally { 497 | $wrt.Close() 498 | } 499 | if ($OutFile) { 500 | return 501 | } else { 502 | return $wrt.ToString() 503 | } 504 | } 505 | } 506 | 507 | New-Alias -Name cfy -Value ConvertFrom-Yaml 508 | New-Alias -Name cty -Value ConvertTo-Yaml 509 | 510 | Export-ModuleMember -Function ConvertFrom-Yaml,ConvertTo-Yaml -Alias cfy,cty 511 | -------------------------------------------------------------------------------- /src/PowerShellYamlSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Numerics; 3 | using System.Text.RegularExpressions; 4 | using System.Collections; 5 | using System.Management.Automation; 6 | using System.Collections.Generic; 7 | using YamlDotNet.Core; 8 | using YamlDotNet.Serialization; 9 | using YamlDotNet.Serialization.EventEmitters; 10 | using YamlDotNet.Core.Events; 11 | using YamlDotNet.Serialization.NamingConventions; 12 | using YamlDotNet.Serialization.ObjectGraphVisitors; 13 | 14 | public sealed class NullValueGraphVisitor : ChainedObjectGraphVisitor 15 | { 16 | public NullValueGraphVisitor(IObjectGraphVisitor nextVisitor) 17 | : base(nextVisitor) 18 | { 19 | } 20 | 21 | public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { 22 | if (value.Value == null) { 23 | return false; 24 | } 25 | return base.EnterMapping(key, value, context, serializer); 26 | } 27 | 28 | public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { 29 | if (value.Value == null) { 30 | return false; 31 | } 32 | return base.EnterMapping(key, value, context, serializer); 33 | } 34 | } 35 | 36 | public class BigIntegerTypeConverter : IYamlTypeConverter { 37 | public bool Accepts(Type type) { 38 | return typeof(BigInteger).IsAssignableFrom(type); 39 | } 40 | 41 | public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { 42 | var value = parser.Consume().Value; 43 | var bigNr = BigInteger.Parse(value); 44 | return bigNr; 45 | } 46 | 47 | public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) { 48 | var bigNr = (BigInteger)value; 49 | emitter.Emit(new Scalar(AnchorName.Empty, TagName.Empty, bigNr.ToString(), ScalarStyle.Plain, true, false)); 50 | } 51 | } 52 | 53 | public class IDictionaryTypeConverter : IYamlTypeConverter { 54 | 55 | private bool omitNullValues; 56 | private bool useFlowStyle; 57 | 58 | public IDictionaryTypeConverter(bool omitNullValues = false, bool useFlowStyle = false) { 59 | this.omitNullValues = omitNullValues; 60 | this.useFlowStyle = useFlowStyle; 61 | } 62 | 63 | public bool Accepts(Type type) { 64 | return typeof(IDictionary).IsAssignableFrom(type); 65 | } 66 | 67 | public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { 68 | var deserializedObject = rootDeserializer(typeof(IDictionary)) as IDictionary; 69 | return deserializedObject; 70 | } 71 | 72 | public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) { 73 | var hObj = (IDictionary)value; 74 | var mappingStyle = this.useFlowStyle ? MappingStyle.Flow : MappingStyle.Block; 75 | 76 | emitter.Emit(new MappingStart(AnchorName.Empty, TagName.Empty, true, mappingStyle)); 77 | foreach (DictionaryEntry entry in hObj) { 78 | if(entry.Value == null) { 79 | if (this.omitNullValues == true) { 80 | continue; 81 | } 82 | serializer(entry.Key, entry.Key.GetType()); 83 | emitter.Emit(new Scalar(AnchorName.Empty, "tag:yaml.org,2002:null", "", ScalarStyle.Plain, true, false)); 84 | continue; 85 | } 86 | serializer(entry.Key, entry.Key.GetType()); 87 | var objType = entry.Value.GetType(); 88 | var val = entry.Value; 89 | if (entry.Value is PSObject nestedObj) { 90 | var nestedType = nestedObj.BaseObject.GetType(); 91 | if (nestedType != typeof(System.Management.Automation.PSCustomObject)) { 92 | objType = nestedObj.BaseObject.GetType(); 93 | val = nestedObj.BaseObject; 94 | } 95 | serializer(val, objType); 96 | } else { 97 | serializer(entry.Value, entry.Value.GetType()); 98 | } 99 | } 100 | emitter.Emit(new MappingEnd()); 101 | } 102 | } 103 | 104 | public class PSObjectTypeConverter : IYamlTypeConverter { 105 | 106 | private bool omitNullValues; 107 | private bool useFlowStyle; 108 | 109 | public PSObjectTypeConverter(bool omitNullValues = false, bool useFlowStyle = false) { 110 | this.omitNullValues = omitNullValues; 111 | this.useFlowStyle = useFlowStyle; 112 | } 113 | 114 | public bool Accepts(Type type) { 115 | return typeof(PSObject).IsAssignableFrom(type); 116 | } 117 | 118 | public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) 119 | { 120 | // We don't really need to do any custom deserialization. 121 | var deserializedObject = rootDeserializer(typeof(IDictionary)) as IDictionary; 122 | return deserializedObject; 123 | } 124 | 125 | public void WriteYaml(IEmitter emitter, object value, Type type, ObjectSerializer serializer) { 126 | var psObj = (PSObject)value; 127 | if (!typeof(IDictionary).IsAssignableFrom(psObj.BaseObject.GetType()) && !typeof(PSCustomObject).IsAssignableFrom(psObj.BaseObject.GetType())) { 128 | serializer(psObj.BaseObject, psObj.BaseObject.GetType()); 129 | return; 130 | } 131 | var mappingStyle = this.useFlowStyle ? MappingStyle.Flow : MappingStyle.Block; 132 | emitter.Emit(new MappingStart(AnchorName.Empty, TagName.Empty, true, mappingStyle)); 133 | foreach (var prop in psObj.Properties) { 134 | if (prop.Value == null) { 135 | if (this.omitNullValues == true) { 136 | continue; 137 | } 138 | serializer(prop.Name, prop.Name.GetType()); 139 | emitter.Emit(new Scalar(AnchorName.Empty, "tag:yaml.org,2002:null", "", ScalarStyle.Plain, true, false)); 140 | } else { 141 | serializer(prop.Name, prop.Name.GetType()); 142 | var objType = prop.Value.GetType(); 143 | var val = prop.Value; 144 | if (prop.Value is PSObject nestedPsObj) { 145 | var nestedType = nestedPsObj.BaseObject.GetType(); 146 | if (nestedType != typeof(System.Management.Automation.PSCustomObject)) { 147 | objType = nestedPsObj.BaseObject.GetType(); 148 | val = nestedPsObj.BaseObject; 149 | } 150 | } 151 | serializer(val, objType); 152 | 153 | } 154 | } 155 | emitter.Emit(new MappingEnd()); 156 | } 157 | } 158 | 159 | public class StringQuotingEmitter: ChainedEventEmitter { 160 | // Patterns from https://yaml.org/spec/1.2/spec.html#id2804356 161 | private static Regex quotedRegex = new Regex(@"^(\~|null|true|false|on|off|yes|no|y|n|[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\.inf))?$", RegexOptions.Compiled | RegexOptions.IgnoreCase); 162 | public StringQuotingEmitter(IEventEmitter next): base(next) {} 163 | 164 | public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { 165 | var typeCode = eventInfo.Source.Value != null 166 | ? Type.GetTypeCode(eventInfo.Source.Type) 167 | : TypeCode.Empty; 168 | 169 | switch (typeCode) { 170 | case TypeCode.Char: 171 | if (Char.IsDigit((char)eventInfo.Source.Value)) { 172 | eventInfo.Style = ScalarStyle.DoubleQuoted; 173 | } 174 | break; 175 | case TypeCode.String: 176 | var val = eventInfo.Source.Value.ToString(); 177 | if (quotedRegex.IsMatch(val)) 178 | { 179 | eventInfo.Style = ScalarStyle.DoubleQuoted; 180 | } else if (val.IndexOf('\n') > -1) { 181 | eventInfo.Style = ScalarStyle.Literal; 182 | } 183 | break; 184 | } 185 | 186 | base.Emit(eventInfo, emitter); 187 | } 188 | } 189 | 190 | public class FlowStyleAllEmitter: ChainedEventEmitter { 191 | public FlowStyleAllEmitter(IEventEmitter next): base(next) {} 192 | 193 | public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { 194 | eventInfo.Style = MappingStyle.Flow; 195 | base.Emit(eventInfo, emitter); 196 | } 197 | 198 | public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter){ 199 | eventInfo.Style = SequenceStyle.Flow; 200 | nextEmitter.Emit(eventInfo, emitter); 201 | } 202 | } 203 | 204 | public class FlowStyleSequenceEmitter: ChainedEventEmitter { 205 | public FlowStyleSequenceEmitter(IEventEmitter next): base(next) {} 206 | 207 | public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter){ 208 | eventInfo.Style = SequenceStyle.Flow; 209 | nextEmitter.Emit(eventInfo, emitter); 210 | } 211 | } 212 | 213 | class BuilderUtils { 214 | public static SerializerBuilder BuildSerializer( 215 | SerializerBuilder builder, 216 | bool omitNullValues = false, 217 | bool useFlowStyle = false, 218 | bool useSequenceFlowStyle = false, 219 | bool jsonCompatible = false) { 220 | 221 | if (jsonCompatible == true) { 222 | useFlowStyle = true; 223 | useSequenceFlowStyle = true; 224 | } 225 | 226 | builder = builder 227 | .WithEventEmitter(next => new StringQuotingEmitter(next)) 228 | .WithTypeConverter(new BigIntegerTypeConverter()) 229 | .WithTypeConverter(new IDictionaryTypeConverter(omitNullValues, useFlowStyle)) 230 | .WithTypeConverter(new PSObjectTypeConverter(omitNullValues, useFlowStyle)); 231 | if (omitNullValues == true) { 232 | builder = builder 233 | .WithEmissionPhaseObjectGraphVisitor(args => new NullValueGraphVisitor(args.InnerVisitor)); 234 | } 235 | if (useFlowStyle == true) { 236 | builder = builder.WithEventEmitter(next => new FlowStyleAllEmitter(next)); 237 | } 238 | if (useSequenceFlowStyle == true) { 239 | builder = builder.WithEventEmitter(next => new FlowStyleSequenceEmitter(next)); 240 | } 241 | 242 | return builder; 243 | } 244 | } 245 | -------------------------------------------------------------------------------- /src/PowerShellYamlSerializer.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1;net47 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | --------------------------------------------------------------------------------