Skip to content

Commit

Permalink
optimize CompatiblConvertFrom-Yaml to use a script-level variable to …
Browse files Browse the repository at this point in the history
…store progress
  • Loading branch information
scbedd committed Nov 5, 2024
1 parent b9caa61 commit c69abe1
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions eng/common/scripts/Helpers/Package-Helpers.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ function GetDocsTocDisplayName($pkg) {
return $displayName
}


if (-not (Test-Path -Path "variable:yqPresent")) {
$script:yqPresent = $null # Initial unset state
}
<#
.SYNOPSIS
This function is a safe wrapper around `yq` and `ConvertFrom-Yaml` to convert YAML content to a PowerShell HashTable object
Expand All @@ -68,27 +70,29 @@ Get-Content -Raw path/to/file.yml | CompatibleConvertFrom-Yaml
#>
function CompatibleConvertFrom-Yaml {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Content
)

if (!($Content)) {
throw "Content to parse is a required input."
}

# Initialize any variables or checks that need to be done once
$yqPresent = Get-Command 'yq' -ErrorAction SilentlyContinue
if (-not $yqPresent) {
. (Join-Path $PSScriptRoot PSModule-Helpers.ps1)
Install-ModuleIfNotInstalled -WhatIf:$false "powershell-yaml" "0.4.1" | Import-Module
if ($null -eq $script:yqPresent) {
$script:yqPresent = [bool](Get-Command 'yq' -ErrorAction SilentlyContinue)

if (-not $script:yqPresent) {
Write-Host "yqPresent evaluated to null, then false."
. (Join-Path $PSScriptRoot PSModule-Helpers.ps1)
Install-ModuleIfNotInstalled -WhatIf:$false "powershell-yaml" "0.4.1" | Import-Module
}
}

# Process the content (for example, you could convert from YAML here)
if ($yqPresent) {
return ($content | yq -o=json | ConvertFrom-Json -AsHashTable)
if ($script:yqPresent) {
return ($content | yq -o=json | ConvertFrom-Json -AsHashTable)
}
else {
return ConvertFrom-Yaml $content
return ConvertFrom-Yaml $content
}
}

Expand Down

0 comments on commit c69abe1

Please sign in to comment.