forked from microsoft/AL-Go-Actions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGithub-Helper.psm1
809 lines (752 loc) · 30 KB
/
Github-Helper.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
function GetExtendedErrorMessage {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "", Justification="We want to ignore errors")]
Param(
$errorRecord
)
$exception = $errorRecord.Exception
$message = $exception.Message
try {
$errorDetails = $errorRecord.ErrorDetails | ConvertFrom-Json
$message += " $($errorDetails.error)`n$($errorDetails.error_description)"
}
catch {
# ignore errors
}
try {
if ($exception -is [System.Management.Automation.MethodInvocationException]) {
$exception = $exception.InnerException
}
$webException = [System.Net.WebException]$exception
$webResponse = $webException.Response
try {
if ($webResponse.StatusDescription) {
$message += "`n$($webResponse.StatusDescription)"
}
}
catch {
# ignore errors
}
$reqstream = $webResponse.GetResponseStream()
$sr = new-object System.IO.StreamReader $reqstream
$result = $sr.ReadToEnd()
try {
$json = $result | ConvertFrom-Json
$message += "`n$($json.Message)"
}
catch {
$message += "`n$result"
}
try {
$correlationX = $webResponse.GetResponseHeader('ms-correlation-x')
if ($correlationX) {
$message += " (ms-correlation-x = $correlationX)"
}
}
catch {
# ignore errors
}
}
catch{
# ignore errors
}
$message
}
function InvokeWebRequest {
Param(
[Hashtable] $headers,
[string] $method,
[string] $body,
[string] $outFile,
[string] $uri,
[switch] $retry,
[switch] $ignoreErrors
)
try {
$params = @{ "UseBasicParsing" = $true }
if ($headers) {
$params += @{ "headers" = $headers }
}
if ($method) {
$params += @{ "method" = $method }
}
if ($body) {
$params += @{ "body" = $body }
}
if ($outfile) {
$params += @{ "outfile" = $outfile }
}
try {
$result = Invoke-WebRequest @params -Uri $uri
}
catch [System.Net.WebException] {
$response = $_.Exception.Response
$responseUri = $response.ResponseUri.AbsoluteUri
if ($response.StatusCode -eq 404 -and $responseUri -ne $uri) {
Write-Host "::Warning::Repository ($uri) was renamed or moved, please update your references with the new name. Trying $responseUri, as suggested by GitHub."
$result = Invoke-WebRequest @params -Uri $responseUri
}
else {
throw
}
}
$result
}
catch {
$message = GetExtendedErrorMessage -errorRecord $_
if ($retry) {
Write-Host $message
Write-Host "...retrying in 1 minute"
Start-Sleep -Seconds 60
try {
Invoke-WebRequest @params -Uri $uri
return
}
catch {
Write-Host "Retry failed as well"
}
}
if ($ignoreErrors.IsPresent) {
Write-Host $message
}
else {
Write-Host "::Error::$message"
throw $message
}
}
}
function GetDependencies {
Param(
$probingPathsJson,
[string] $api_url = $ENV:GITHUB_API_URL,
[string] $saveToPath = (Join-Path $ENV:GITHUB_WORKSPACE ".dependencies")
)
if (!(Test-Path $saveToPath)) {
New-Item $saveToPath -ItemType Directory | Out-Null
}
$downloadedList = @()
foreach($mask in 'Apps','TestApps') {
foreach($dependency in $probingPathsJson) {
$projects = $dependency.projects
$buildMode = $dependency.buildMode
# change the mask to include the build mode
if($buildMode -ne "Default") {
$mask = "$buildMode$mask"
}
Write-Host "Locating $mask artifacts for projects: $projects"
if ($dependency.release_status -eq "thisBuild") {
$missingProjects = @()
foreach($project in $projects.Split(',')) {
$project = $project.Replace('\','_').Replace('/','_') # sanitize project name
$downloadName = Join-Path $saveToPath "thisbuild-$project-$($mask)"
if (Test-Path $downloadName -PathType Container) {
$folder = Get-Item $downloadName
Get-ChildItem -Path $folder | ForEach-Object {
if ($mask -like '*TestApps') {
$downloadedList += @("($($_.FullName))")
}
else {
$downloadedList += @($_.FullName)
}
Write-Host "$($_.FullName) found from previous job"
}
}
elseif ($mask -notlike '*TestApps') {
Write-Host "$project not built, downloading from artifacts"
$missingProjects += @($project)
}
}
if ($missingProjects) {
$dependency.release_status = 'latestBuild'
$dependency.branch = $dependency.baseBranch
$dependency.projects = $missingProjects -join ","
}
}
$projects = $dependency.projects
$repository = ([uri]$dependency.repo).AbsolutePath.Replace(".git", "").TrimStart("/")
if ($dependency.release_status -eq "latestBuild") {
$artifacts = GetArtifacts -token $dependency.authTokenSecret -api_url $api_url -repository $repository -mask $mask -projects $projects -version $dependency.version -branch $dependency.branch
if ($artifacts) {
$artifacts | ForEach-Object {
$download = DownloadArtifact -path $saveToPath -token $dependency.authTokenSecret -artifact $_
if ($download) {
if ($mask -like '*TestApps') {
$downloadedList += @("($download)")
}
else {
$downloadedList += @($download)
}
}
else {
Write-Host -ForegroundColor Red "Unable to download artifact $_"
}
}
}
else {
Write-Host -ForegroundColor Red "Could not find any $mask artifacts for projects $projects, version $($dependency.version)"
}
}
elseif ($dependency.release_status -ne "thisBuild" -and $dependency.release_status -ne "include") {
$releases = GetReleases -api_url $api_url -token $dependency.authTokenSecret -repository $repository
if ($dependency.version -ne "latest") {
$releases = $releases | Where-Object { ($_.tag_name -eq $dependency.version) }
}
switch ($dependency.release_status) {
"release" { $release = $releases | Where-Object { -not ($_.prerelease -or $_.draft ) } | Select-Object -First 1 }
"prerelease" { $release = $releases | Where-Object { ($_.prerelease ) } | Select-Object -First 1 }
"draft" { $release = $releases | Where-Object { ($_.draft ) } | Select-Object -First 1 }
Default { throw "Invalid release status '$($dependency.release_status)' is encountered." }
}
if (!($release)) {
throw "Could not find a release that matches the criteria."
}
$download = DownloadRelease -token $dependency.authTokenSecret -projects $projects -api_url $api_url -repository $repository -path $saveToPath -release $release -mask $mask
if ($download) {
if ($mask -like '*TestApps') {
$downloadedList += @("($download)")
}
else {
$downloadedList += @($download)
}
}
}
}
}
return $downloadedList
}
function CmdDo {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingEmptyCatchBlock", "", Justification="We want to ignore errors")]
Param(
[string] $command = "",
[string] $arguments = "",
[switch] $silent,
[switch] $returnValue,
[string] $inputStr = ""
)
$oldNoColor = "$env:NO_COLOR"
$env:NO_COLOR = "Y"
$oldEncoding = [Console]::OutputEncoding
try { [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 } catch {}
try {
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $command
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
if ($inputStr) {
$pinfo.RedirectStandardInput = $true
}
$pinfo.WorkingDirectory = Get-Location
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $arguments
$pinfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Minimized
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
if ($inputStr) {
$p.StandardInput.WriteLine($inputStr)
$p.StandardInput.Close()
}
$outtask = $p.StandardOutput.ReadToEndAsync()
$errtask = $p.StandardError.ReadToEndAsync()
$p.WaitForExit();
$message = $outtask.Result
$err = $errtask.Result
if ("$err" -ne "") {
$message += "$err"
}
$message = $message.Trim()
if ($p.ExitCode -eq 0) {
if (!$silent) {
Write-Host $message
}
if ($returnValue) {
$message.Replace("`r","").Split("`n")
}
}
else {
$message += "`n`nExitCode: "+$p.ExitCode + "`nCommandline: $command $arguments"
throw $message
}
}
finally {
try { [Console]::OutputEncoding = $oldEncoding } catch {}
$env:NO_COLOR = $oldNoColor
}
}
function invoke-gh {
Param(
[parameter(mandatory = $false, ValueFromPipeline = $true)]
[string] $inputStr = "",
[switch] $silent,
[switch] $returnValue,
[parameter(mandatory = $true, position = 0)][string] $command,
[parameter(mandatory = $false, position = 1, ValueFromRemainingArguments = $true)] $remaining
)
Process {
$arguments = "$command "
foreach($parameter in $remaining) {
if ("$parameter".IndexOf(" ") -ge 0 -or "$parameter".IndexOf('"') -ge 0) {
if ($parameter.length -gt 15000) {
$parameter = "$($parameter.Substring(0,15000))...`n`n**Truncated due to size limits!**"
}
$arguments += """$($parameter.Replace('"','\"'))"" "
}
else {
$arguments += "$parameter "
}
}
cmdDo -command gh -arguments $arguments -silent:$silent -returnValue:$returnValue -inputStr $inputStr
}
}
function invoke-git {
Param(
[parameter(mandatory = $false, ValueFromPipeline = $true)]
[string] $inputStr = "",
[switch] $silent,
[switch] $returnValue,
[parameter(mandatory = $true, position = 0)][string] $command,
[parameter(mandatory = $false, position = 1, ValueFromRemainingArguments = $true)] $remaining
)
Process {
$arguments = "$command "
foreach($parameter in $remaining) {
if ("$parameter".IndexOf(" ") -ge 0 -or "$parameter".IndexOf('"') -ge 0) {
$arguments += """$($parameter.Replace('"','\"'))"" "
}
else {
$arguments += "$parameter "
}
}
cmdDo -command git -arguments $arguments -silent:$silent -returnValue:$returnValue -inputStr $inputStr
}
}
# Convert a semantic version object to a semantic version string
#
# The SemVer object has the following properties:
# Prefix: 'v' or ''
# Major: the major version number
# Minor: the minor version number
# Patch: the patch version number
# Addt0: the first additional segment (zzz means not specified)
# Addt1: the second additional segment (zzz means not specified)
# Addt2: the third additional segment (zzz means not specified)
# Addt3: the fourth additional segment (zzz means not specified)
# Addt4: the fifth additional segment (zzz means not specified)
#
# Returns the SemVer string
# # [v]major.minor.patch[-addt0[.addt1[.addt2[.addt3[.addt4]]]]]
function SemVerObjToSemVerStr {
Param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
$semVerObj
)
Process {
try {
$str = "$($semVerObj.Prefix)$($semVerObj.Major).$($semVerObj.Minor).$($semVerObj.Patch)"
for ($i=0; $i -lt 5; $i++) {
$seg = $semVerObj."Addt$i"
if ($seg -eq 'zzz') { break }
if ($i -eq 0) { $str += "-$($seg)" } else { $str += ".$($seg)" }
}
$str
}
catch {
throw "'$SemVerObj' cannot be recognized as a semantic version object (internal error)"
}
}
}
# Convert a semantic version string to a semantic version object
# SemVer strings supported are defined under https://semver.org, additionally allowing a leading 'v' (as supported by GitHub semver sorting)
#
# The string has the following format:
# if allowMajorMinorOnly is specified:
# [v]major.minor.[patch[-addt0[.addt1[.addt2[.addt3[.addt4]]]]]]
# else
# [v]major.minor.patch[-addt0[.addt1[.addt2[.addt3[.addt4]]]]]
#
# Returns the SemVer object. The SemVer object has the following properties:
# Prefix: 'v' or ''
# Major: the major version number
# Minor: the minor version number
# Patch: the patch version number
# Addt0: the first additional segment (zzz means not specified)
# Addt1: the second additional segment (zzz means not specified)
# Addt2: the third additional segment (zzz means not specified)
# Addt3: the fourth additional segment (zzz means not specified)
# Addt4: the fifth additional segment (zzz means not specified)
function SemVerStrToSemVerObj {
Param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string] $semVerStr,
[switch] $allowMajorMinorOnly
)
Process {
$obj = New-Object PSCustomObject
try {
# Only allowed prefix is a 'v'.
# This is supported by GitHub when sorting tags
$prefix = ''
$verstr = $semVerStr
if ($semVerStr -like 'v*') {
$prefix = 'v'
$verStr = $semVerStr.Substring(1)
}
# Next part is a version number with 2 or 3 segments
# 2 segments are allowed only if $allowMajorMinorOnly is specified
$version = [System.Version]"$($verStr.split('-')[0])"
if ($version.Revision -ne -1) { throw "not semver" }
if ($version.Build -eq -1) {
if ($allowMajorMinorOnly) {
$version = [System.Version]"$($version.Major).$($version.Minor).0"
$idx = $semVerStr.IndexOf('-')
if ($idx -eq -1) {
$semVerStr = "$semVerStr.0"
}
else {
$semVerstr = $semVerstr.insert($idx, '.0')
}
}
else {
throw "not semver"
}
}
# Add properties to the object
$obj | Add-Member -MemberType NoteProperty -Name "Prefix" -Value $prefix
$obj | Add-Member -MemberType NoteProperty -Name "Major" -Value ([int]$version.Major)
$obj | Add-Member -MemberType NoteProperty -Name "Minor" -Value ([int]$version.Minor)
$obj | Add-Member -MemberType NoteProperty -Name "Patch" -Value ([int]$version.Build)
0..4 | ForEach-Object {
# default segments to 'zzz' for sorting of SemVer Objects to work as GitHub does
$obj | Add-Member -MemberType NoteProperty -Name "Addt$_" -Value 'zzz'
}
$idx = $verStr.IndexOf('-')
if ($idx -gt 0) {
$segments = $verStr.SubString($idx+1).Split('.')
if ($segments.Count -gt 5) {
throw "max. 5 segments"
}
# Add all 5 segments to the object
# If the segment is a number, it is converted to an integer
# If the segment is a string, it cannot be -ge 'zzz' (would be sorted wrongly)
0..($segments.Count-1) | ForEach-Object {
$result = 0
if ([int]::TryParse($segments[$_], [ref] $result)) {
$obj."Addt$_" = [int]$result
}
else {
if ($segments[$_] -ge 'zzz') {
throw "Unsupported segment"
}
$obj."Addt$_" = $segments[$_]
}
}
}
# Check that the object can be converted back to the original string
$newStr = SemVerObjToSemVerStr -semVerObj $obj
if ($newStr -cne $semVerStr) {
throw "Not equal"
}
}
catch {
throw "'$semVerStr' cannot be recognized as a semantic version string (https://semver.org)"
}
$obj
}
}
function GetReleases {
Param(
[string] $token,
[string] $api_url = $ENV:GITHUB_API_URL,
[string] $repository = $ENV:GITHUB_REPOSITORY
)
Write-Host "Analyzing releases $api_url/repos/$repository/releases"
$releases = @(InvokeWebRequest -Headers (GetHeader -token $token) -Uri "$api_url/repos/$repository/releases" | ConvertFrom-Json)
if ($releases.Count -gt 1) {
# Sort by SemVer tag
try {
$sortedReleases = $releases.tag_name |
ForEach-Object { SemVerStrToSemVerObj -semVerStr $_ } |
Sort-Object -Property Major,Minor,Patch,Addt0,Addt1,Addt2,Addt3,Addt4 -Descending |
ForEach-Object { SemVerObjToSemVerStr -semVerObj $_ } | ForEach-Object {
$tag_name = $_
$releases | Where-Object { $_.tag_name -eq $tag_name }
}
$sortedReleases
}
catch {
Write-Host "::Warning::Some of the release tags cannot be recognized as a semantic version string (https://semver.org). Using default GitHub sorting for releases, which will not work for release branches"
$releases
}
}
else {
$releases
}
}
function GetLatestRelease {
Param(
[string] $token,
[string] $api_url = $ENV:GITHUB_API_URL,
[string] $repository = $ENV:GITHUB_REPOSITORY,
[string] $ref = $ENV:GITHUB_REFNAME
)
Write-Host "Getting the latest release from $api_url/repos/$repository/releases/latest - branch $ref"
# Get all releases from GitHub, sorted by SemVer tag
# If any release tag is not a valid SemVer tag, use default GitHub sorting and issue a warning
# Default github sorting will return the latest historically created release as the latest release - not the highest version
$releases = GetReleases -token $token -api_url $api_url -repository $repository
# Get Latest release
$latestRelease = $releases | Where-Object { -not ($_.prerelease -or $_.draft) } | Select-Object -First 1
$releaseBranchPrefix = 'release/'
if ($ref -like "$releaseBranchPrefix*") {
# If release branch, get the latest release from that the release branch
# This is given by the latest release with the same major.minor as the release branch
$semVerObj = SemVerStrToSemVerObj -semVerStr $ref.SubString($releaseBranchPrefix.Length) -allowMajorMinorOnly
$latestRelease = $releases | Where-Object {
$releaseSemVerObj = SemVerStrToSemVerObj -semVerStr $_.tag_name
$semVerObj.Major -eq $releaseSemVerObj.Major -and $semVerObj.Minor -eq $releaseSemVerObj.Minor
} | Select-Object -First 1
}
$latestRelease
}
function GetHeader {
param (
[string] $token,
[string] $accept = "application/vnd.github+json",
[string] $apiVersion = "2022-11-28"
)
$headers = @{
"Accept" = $accept
"X-GitHub-Api-Version" = $apiVersion
}
if (![string]::IsNullOrEmpty($token)) {
$headers["Authorization"] = "token $token"
}
return $headers
}
function GetReleaseNotes {
Param(
[string] $token,
[string] $repository = $ENV:GITHUB_REPOSITORY,
[string] $api_url = $ENV:GITHUB_API_URL,
[string] $tag_name,
[string] $previous_tag_name,
[string] $target_commitish
)
Write-Host "Generating release note $api_url/repos/$repository/releases/generate-notes"
$postParams = @{
tag_name = $tag_name;
}
if ($previous_tag_name) {
$postParams["previous_tag_name"] = $previous_tag_name
}
if ($target_commitish) {
$postParams["target_commitish"] = $target_commitish
}
InvokeWebRequest -Headers (GetHeader -token $token) -Method POST -Body ($postParams | ConvertTo-Json) -Uri "$api_url/repos/$repository/releases/generate-notes"
}
function DownloadRelease {
Param(
[string] $token,
[string] $projects = "*",
[string] $api_url = $ENV:GITHUB_API_URL,
[string] $repository = $ENV:GITHUB_REPOSITORY,
[string] $path,
[string] $mask = "Apps",
$release
)
if ($projects -eq "") { $projects = "*" }
Write-Host "Downloading release $($release.Name), projects $projects, type $mask"
if ([string]::IsNullOrEmpty($token)) {
$token = invoke-gh -silent -returnValue auth token
}
$headers = GetHeader -token $token -accept "application/octet-stream"
foreach($project in $projects.Split(',')) {
$project = $project.Replace('\','_').Replace('/','_')
Write-Host "project '$project'"
$assetPattern1 = "$project-*-$mask-*.zip"
$assetPattern2 = "$project-$mask-*.zip"
Write-Host "AssetPatterns: '$assetPattern1' | '$assetPattern2'"
$assets = @($release.assets | Where-Object { $_.name -like $assetPattern1 -or $_.name -like $assetPattern2 })
foreach($asset in $assets) {
$uri = "$api_url/repos/$repository/releases/assets/$($asset.id)"
Write-Host $uri
$filename = Join-Path $path $asset.name
InvokeWebRequest -Headers $headers -Uri $uri -OutFile $filename
$filename
}
}
}
function CheckRateLimit {
Param(
[string] $token = ''
)
$headers = GetHeader -token $token
$rate = (InvokeWebRequest -Headers $headers -Uri "https://api.github.com/rate_limit").Content | ConvertFrom-Json
$rate | ConvertTo-Json -Depth 99 | Out-Host
$rate = $rate.rate
$percent = [int]($rate.remaining*100/$rate.limit)
Write-Host "$($rate.remaining) API calls remaining out of $($rate.limit) ($percent%)"
if ($percent -lt 10) {
$resetTimeStamp = ([datetime] '1970-01-01Z').AddSeconds($rate.reset)
$waitTime = $resetTimeStamp.Subtract([datetime]::Now)
Write-Host "Less than 10% API calls left, waiting for $($waitTime.TotalSeconds) seconds for limits to reset."
Start-Sleep -seconds ($waitTime.TotalSeconds+1)
}
}
# Get Content of UTF8 encoded file as a string with LF line endings
# No empty line at the end of the file
function Get-ContentLF {
Param(
[parameter(mandatory = $true, ValueFromPipeline = $false)]
[string] $path
)
Process {
(Get-Content -Path $path -Encoding UTF8 -Raw).Replace("`r", "").TrimEnd("`n")
}
}
# Set-Content defaults to culture specific ANSI encoding, which is not what we want
# Set-Content defaults to environment specific line endings, which is not what we want
# This function forces UTF8 encoding and LF line endings
function Set-ContentLF {
Param(
[parameter(mandatory = $true, ValueFromPipeline = $false)]
[string] $path,
[parameter(mandatory = $true, ValueFromPipeline = $true)]
$content
)
Process {
$path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($path)
if ($content -is [array]) {
$content = $content -join "`n"
}
else {
$content = "$content".Replace("`r", "")
}
[System.IO.File]::WriteAllText($path, "$content`n")
}
}
# Format Object to JSON and write to file with LF line endings and formatted as PowerShell 7 would do it
# PowerShell 5.1 formats JSON differently than PowerShell 7, so we need to use pwsh to format it
# PowerShell 5.1 format:
# {
# "key": "value"
# }
# PowerShell 7 format:
# {
# "key": "value"
# }
function Set-JsonContentLF {
Param(
[parameter(mandatory = $true, ValueFromPipeline = $false)]
[string] $path,
[parameter(mandatory = $true, ValueFromPipeline = $true)]
[object] $object
)
Process {
$object | ConvertTo-Json -Depth 99 | Set-ContentLF -path $path
if ($PSVersionTable.PSVersion.Major -lt 6) {
try {
$path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($path)
. pwsh (Join-Path $PSScriptRoot 'prettyfyjson.ps1') $path
}
catch {
Write-Host "WARNING: pwsh (PowerShell 7) not installed, json will be formatted by PowerShell $($PSVersionTable.PSVersion)"
}
}
}
}
function GetArtifacts {
Param(
[string] $token,
[string] $api_url = $ENV:GITHUB_API_URL,
[string] $repository = $ENV:GITHUB_REPOSITORY,
[string] $mask = "Apps",
[string] $branch = "main",
[string] $projects,
[string] $version
)
$headers = GetHeader -token $token
$total_count = 0
if ($version -eq 'latest') { $version = '*' }
# Download all artifacts matching branch and version
# We might have results from multiple workflow runs, but we will have all artifacts from the workflow run that created the first matching artifact
# Use the buildOutput artifact to determine the workflow run id (as that will always be there)
$artifactPattern = "*-$branch-*-$version"
# Use buildOutput artifact to determine the workflow run id to avoid excessive API calls
# Reason: A project called xx-main will match the artifact pattern *-main-*-version, and there might not be any artifacts matching the mask
$buildOutputPattern = "*-$branch-BuildOutput-$version"
Write-Host "Analyzing artifacts matching $artifactPattern"
while ($true) {
if ($total_count -eq 0) {
# First iteration - initialize variables
$matchingArtifacts = @()
$buildOutputArtifacts = @()
$per_page = 100
$page_no = 1
}
$uri = "$api_url/repos/$repository/actions/artifacts?per_page=$($per_page)&page=$($page_no)"
Write-Host $uri
$artifacts = InvokeWebRequest -Headers $headers -Uri $uri | ConvertFrom-Json
# If no artifacts are read, we are done
if ($artifacts.artifacts.Count -eq 0) {
break
}
if ($total_count -eq 0) {
$total_count = $artifacts.total_count
}
elseif ($total_count -ne $artifacts.total_count) {
# The total count changed, restart the loop
$total_count = 0
continue
}
$matchingArtifacts += @($artifacts.artifacts | Where-Object { !$_.expired -and $_.name -like $artifactPattern })
$buildOutputArtifacts += @($artifacts.artifacts | Where-Object { !$_.expired -and $_.name -like $buildOutputPattern })
if ($buildOutputArtifacts.Count -gt 0) {
# We have matching artifacts.
# If the last artifact in the list of artifacts read is not from the same workflow run, there are no more matching artifacts
if ($artifacts.artifacts[$artifacts.artifacts.Count-1].workflow_run.id -ne $buildOutputArtifacts[0].workflow_run.id) {
break
}
}
if ($total_count -le $page_no*$per_page) {
# no more pages
break
}
$page_no += 1
}
if ($buildOutputArtifacts.Count -eq 0) {
Write-Host "No matching buildOutput artifacts found"
return
}
Write-Host "Matching artifacts:"
# We have all matching artifacts from the workflow run (and maybe more runs)
# Now we need to filter out the artifacts that match the projects we need
$result = $matchingArtifacts | Where-Object { $_.workflow_run.id -eq $buildOutputArtifacts[0].workflow_run.id } | ForEach-Object {
foreach($project in $projects.Split(',')) {
$project = $project.Replace('\','_').Replace('/','_')
$artifactPattern = "$project-$branch-$mask-$version"
if ($_.name -like $artifactPattern) {
Write-Host "- $($_.name)"
return $_
}
}
}
if (-not $result) {
Write-Host "- No matching artifacts found"
}
}
function DownloadArtifact {
Param(
[string] $token,
[string] $path,
$artifact
)
Write-Host "Downloading artifact $($artifact.Name)"
Write-Host $artifact.archive_download_url
if ([string]::IsNullOrEmpty($token)) {
$token = invoke-gh -silent -returnValue auth token
}
$headers = GetHeader -token $token
$outFile = Join-Path $path "$($artifact.Name).zip"
InvokeWebRequest -Headers $headers -Uri $artifact.archive_download_url -OutFile $outFile
$outFile
}