Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(checkver): improve JSONPath extraction support #4522

Merged
merged 10 commits into from
Nov 29, 2021
9 changes: 8 additions & 1 deletion bin/checkver.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,14 @@ while ($in_progress -gt 0) {
}

if ($jsonpath) {
$ver = json_path $page $jsonpath
# Return only a single value if regex is absent
$single = [String]::IsNullOrEmpty($regex)
pratikpc marked this conversation as resolved.
Show resolved Hide resolved
# If reverse is ON and regex is ON,
# Then reverse would have no effect because regex handles reverse
# on its own
# So in this case we have to disable reverse
$reverse = $reverse -and $single
niheaven marked this conversation as resolved.
Show resolved Hide resolved
$ver = json_path $page $jsonpath $null $reverse $single
pratikpc marked this conversation as resolved.
Show resolved Hide resolved
if (!$ver) {
$ver = json_path_legacy $page $jsonpath
}
Expand Down
34 changes: 18 additions & 16 deletions lib/json.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -92,31 +92,33 @@ function ConvertToPrettyJson {
}
}

function json_path([String] $json, [String] $jsonpath, [Hashtable] $substitutions) {
function json_path([String] $json, [String] $jsonpath, [Hashtable] $substitutions, [Boolean] $reverse, [Boolean] $single) {
Add-Type -Path "$psscriptroot\..\supporting\validator\bin\Newtonsoft.Json.dll"
if ($null -ne $substitutions) {
$jsonpath = substitute $jsonpath $substitutions ($jsonpath -like "*=~*")
}
try {
$obj = [Newtonsoft.Json.Linq.JObject]::Parse($json)
$obj = [Newtonsoft.Json.Linq.JValue]::Parse($json)
} catch [Newtonsoft.Json.JsonReaderException] {
try {
$obj = [Newtonsoft.Json.Linq.JArray]::Parse($json)
} catch [Newtonsoft.Json.JsonReaderException] {
return $null
}
return $null
}

try {
try {
$result = $obj.SelectToken($jsonpath, $true)
} catch [Newtonsoft.Json.JsonException] {
return $null
$result = $obj.SelectTokens($jsonpath, $true)
if ($reverse) {
# Return versions in reverse order
$result = [System.Linq.Enumerable]::Reverse($result)
}
return $result.ToString()
} catch [System.Management.Automation.MethodInvocationException] {
write-host -f DarkRed $_
return $null
if ($single) {
# Extract First value
$result = [System.Linq.Enumerable]::First($result)
# Convert first value to string
$result = $result.ToString()
} else {
$result = "$([String]::Join('\n', $result))"
}
return $result
} catch [Exception] {
Write-Host $_ -ForegroundColor DarkRed
}

return $null
Expand Down