Created
February 15, 2024 02:40
-
-
Save JustinGrote/cbe668c224214fa0d953b90edff6b023 to your computer and use it in GitHub Desktop.
Download multiple parts of an OpenAPI spec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace System.Collections.Generic | |
function Get-OpenApiDefinition { | |
<# | |
Fetches the OpenAPI definition from the specified URI and for every ref, downloads the relative file to the destination folder. Currently only works with relative refs | |
#> | |
param ( | |
#The source | |
[Parameter(Mandatory)] | |
[Uri]$Uri, | |
#The destination path to download all files/folders | |
[Parameter(Mandatory)] | |
[string]$Destination | |
) | |
[uri]$baseUri = ((Split-Path -Path $Uri) -replace '\\', '/') + '/' | |
$destinationDir = New-Item -ItemType Directory -Path $Destination -Force | |
[HashSet[string]]$files = @() | |
[Queue[string]]$queue = @() | |
$queue.Enqueue($Uri) | |
while ($queue.count -ne 0) { | |
$UriToDownload = $queue.Dequeue() | |
Write-Debug $UriToDownload | |
$definition = Invoke-RestMethod -Uri $UriToDownload | |
$path = $baseUri.MakeRelative($UriToDownload) | |
$outFilePath = Join-Path $destinationDir $path | |
$definition | Out-File -FilePath (New-Item -Path $outFilePath -Force) | |
foreach ($ref in (Get-Refs -Definition $definition)) { | |
$candidateUri = [uri]::new(([uri]$UriToDownload), $ref) | |
#If we have not seen the file yet, process it | |
if ($files.Add($candidateUri)) { | |
$queue.Enqueue($candidateUri) | |
} | |
} | |
} | |
return $files | |
} | |
function Get-Refs { | |
param ( | |
#The OpenAPI definition | |
[string]$Definition | |
) | |
# Look for $ref in the definition | |
$refs = $definition.split("`n") | Select-String -Pattern '\$ref: ["'']?([^"''].+?)#/' | ForEach-Object { $_.Matches.Groups[1].Value } | |
# Deduplicate the refs | |
$uniqueRefs = $refs | Select-Object -Unique | |
return $uniqueRefs | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment