Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Created February 15, 2024 02:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinGrote/cbe668c224214fa0d953b90edff6b023 to your computer and use it in GitHub Desktop.
Save JustinGrote/cbe668c224214fa0d953b90edff6b023 to your computer and use it in GitHub Desktop.
Download multiple parts of an OpenAPI spec
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