From 6f4ff8799ee55dedb2c4a21508bf4790415dddda Mon Sep 17 00:00:00 2001 From: Leonard Jonathan Oh Date: Sat, 17 Feb 2024 17:35:37 +0000 Subject: [PATCH] Fix: Error out when `versions.json` is empty or invalid JSON --- .../Get-DockerImageVariantsVersions.Tests.ps1 | 25 ++++++++++++++++--- .../Get-DockerImageVariantsVersions.ps1 | 11 +++++++- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.Tests.ps1 b/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.Tests.ps1 index c68b369..04611f4 100644 --- a/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.Tests.ps1 +++ b/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.Tests.ps1 @@ -26,14 +26,33 @@ Describe "Get-DockerImageVariantsVersions" -Tag 'Unit' { } | Should -Throw } - It "Gets version.json" { + It "Errors when versions.json is empty" { + Mock Get-Content {} + + Get-DockerImageVariantsVersions -ErrorVariable err 2>$null + + $err | Should -Not -Be $null + } + + It "Gets when versions.json is empty" { + Mock Get-Content { + '' + } + + Get-DockerImageVariantsVersions -ErrorVariable err 2>$null + + $err | Should -Not -Be $null + } + + It "Gets versions.json" { Mock Get-Content { - '[ "0.1.0", "0.2.0" ]' + '{ "somecoolpackage": { "versions": [ "0.0.1" ] } }' } $versions = Get-DockerImageVariantsVersions - $versions | Should -Be @( '0.1.0', '0.2.0' ) + $versions -is [PSCustomObject] + $versions.psobject.Properties.Name | Should -Not -Be $null } } diff --git a/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.ps1 b/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.ps1 index 1281467..372a580 100644 --- a/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.ps1 +++ b/src/Generate-DockerImageVariantsHelpers/public/Get-DockerImageVariantsVersions.ps1 @@ -6,7 +6,16 @@ function Get-DockerImageVariantsVersions { $ErrorActionPreference = 'Stop' try { $VERSIONS_JSON_FILE = "./generate/definitions/versions.json" - Get-Content $VERSIONS_JSON_FILE -Encoding utf8 -Raw | ConvertFrom-Json + $content = Get-Content $VERSIONS_JSON_FILE -Encoding utf8 -Raw + if ($null -eq $content) { + throw "$VERSIONS_JSON_FILE is empty" + }else { + $o = ConvertFrom-Json -InputObject $content + if ($o -isnot [PSCustomObject]) { + throw "$VERSIONS_JSON_FILE does not contain valid JSON" + } + $o + } }catch { if ($callerEA -eq 'Stop') { throw