# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at https://mozilla.org/MPL/2.0/. # # The Windows twin of scripts/preview.sh (a Fabrica runner on Windows): # # scripts\preview.ps1 open -Project shop -Branch fix-42 -Upstream http://10.0.0.5:8080 [-Ttl 86400] # scripts\preview.ps1 close -Project shop -Branch fix-42 # scripts\preview.ps1 list # # $env:IANITOR_URL, $env:IANITOR_PREVIEW_TOKEN (a `--scope previews` token from the Custos team # vault). An internal (Domi) admin host needs the Domi root in the machine's trusted roots. param( [Parameter(Mandatory = $true, Position = 0)][ValidateSet('open', 'close', 'list')][string]$Action, [string]$Project, [string]$Branch, [string]$Upstream, [int]$Ttl = 0 ) $ErrorActionPreference = 'Stop' if (-not $env:IANITOR_URL -or -not $env:IANITOR_PREVIEW_TOKEN) { throw 'set IANITOR_URL and IANITOR_PREVIEW_TOKEN' } $base = $env:IANITOR_URL.TrimEnd('/') $headers = @{ Authorization = "Bearer $($env:IANITOR_PREVIEW_TOKEN)" } function Call($method, $path, $body) { $p = @{ Method = $method; Uri = "$base$path"; Headers = $headers; UseBasicParsing = $true; ContentType = 'application/json' } if ($body) { $p.Body = [Text.Encoding]::UTF8.GetBytes(($body | ConvertTo-Json -Compress)) } try { $r = Invoke-WebRequest @p return @{ Code = [int]$r.StatusCode; Json = ($r.Content | ConvertFrom-Json) } } catch [System.Net.WebException] { $resp = $_.Exception.Response if (-not $resp) { throw } $text = (New-Object IO.StreamReader($resp.GetResponseStream())).ReadToEnd() return @{ Code = [int]$resp.StatusCode; Json = ($text | ConvertFrom-Json) } } } switch ($Action) { 'open' { $body = @{ project = $Project; branch = $Branch; upstream = $Upstream } if ($Ttl -gt 0) { $body.ttl = $Ttl } $r = Call POST '/api/v1/previews' $body if ($r.Code -ne 202) { throw "preview: $($r.Json.error.message)" } $host_ = $r.Json.preview.hostname for ($i = 0; $i -lt 150; $i++) { $s = Call GET "/api/v1/previews/$host_" $null if ($s.Code -ne 200) { throw "preview: $($s.Json.error.message)" } if ($s.Json.preview.state -eq 'live') { Write-Output $r.Json.preview.url; exit 0 } if ($s.Json.preview.state -eq 'failed') { throw "preview: $($s.Json.preview.problem)" } Start-Sleep -Seconds 2 } throw 'preview: not live after 5 minutes' } 'close' { $r = Call POST '/api/v1/previews/close' @{ project = $Project; branch = $Branch } if ($r.Code -eq 202) { 'closing' } elseif ($r.Code -eq 404) { 'no preview' } else { throw "preview: $($r.Json.error.message)" } } 'list' { $r = Call GET '/api/v1/previews' $null $r.Json.items | ForEach-Object { "$($_.url)`t$($_.project)`t$($_.branch)`t$($_.state)`tuntil $($_.expires_at)" } } }