-
Notifications
You must be signed in to change notification settings - Fork 30
/
AL-Go-Helper.ps1
2504 lines (2311 loc) · 111 KB
/
AL-Go-Helper.ps1
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Param(
[switch] $local
)
$gitHubHelperPath = Join-Path $PSScriptRoot 'Github-Helper.psm1'
if (Test-Path $gitHubHelperPath) {
Import-Module $gitHubHelperPath
# If we are adding more dependencies here, then localDevEnv and cloudDevEnv needs to be updated
}
$errorActionPreference = "Stop"; $ProgressPreference = "SilentlyContinue"; Set-StrictMode -Version 2.0
$ALGoFolderName = '.AL-Go'
$ALGoSettingsFile = Join-Path '.AL-Go' 'settings.json'
$RepoSettingsFile = Join-Path '.github' 'AL-Go-Settings.json'
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'defaultCICDPushBranches', Justification = 'False positive.')]
$defaultCICDPushBranches = @( 'main', 'release/*', 'feature/*' )
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'defaultCICDPullRequestBranches', Justification = 'False positive.')]
$defaultCICDPullRequestBranches = @( 'main' )
$runningLocal = $local.IsPresent
$defaultBcContainerHelperVersion = "latest" # Must be double quotes. Will be replaced by BcContainerHelperVersion if necessary in the deploy step - ex. "https://github.com/organization/navcontainerhelper/archive/refs/heads/branch.zip"
$notSecretProperties = @("Scopes","TenantId","BlobName","ContainerName","StorageAccountName","ServerUrl","ppUserName")
$runAlPipelineOverrides = @(
"DockerPull"
"NewBcContainer"
"ImportTestToolkitToBcContainer"
"CompileAppInBcContainer"
"GetBcContainerAppInfo"
"PublishBcContainerApp"
"UnPublishBcContainerApp"
"InstallBcAppFromAppSource"
"SignBcContainerApp"
"ImportTestDataInBcContainer"
"RunTestsInBcContainer"
"GetBcContainerAppRuntimePackage"
"RemoveBcContainer"
"InstallMissingDependencies"
"PreCompileApp"
"PostCompileApp"
)
# Well known AppIds
$systemAppId = "63ca2fa4-4f03-4f2b-a480-172fef340d3f"
$baseAppId = "437dbf0e-84ff-417a-965d-ed2bb9650972"
$applicationAppId = "c1335042-3002-4257-bf8a-75c898ccb1b8"
$permissionsMockAppId = "40860557-a18d-42ad-aecb-22b7dd80dc80"
$testRunnerAppId = "23de40a6-dfe8-4f80-80db-d70f83ce8caf"
$anyAppId = "e7320ebb-08b3-4406-b1ec-b4927d3e280b"
$libraryAssertAppId = "dd0be2ea-f733-4d65-bb34-a28f4624fb14"
$libraryVariableStorageAppId = "5095f467-0a01-4b99-99d1-9ff1237d286f"
$systemApplicationTestLibraryAppId = "9856ae4f-d1a7-46ef-89bb-6ef056398228"
$TestsTestLibrariesAppId = "5d86850b-0d76-4eca-bd7b-951ad998e997"
$performanceToolkitAppId = "75f1590f-55c5-4501-ae63-bada5534e852"
$performanceToolkitApps = @($performanceToolkitAppId)
$testLibrariesApps = @($systemApplicationTestLibraryAppId, $TestsTestLibrariesAppId)
$testFrameworkApps = @($anyAppId, $libraryAssertAppId, $libraryVariableStorageAppId) + $testLibrariesApps
$testRunnerApps = @($permissionsMockAppId, $testRunnerAppId) + $performanceToolkitApps + $testLibrariesApps + $testFrameworkApps
$isPsCore = $PSVersionTable.PSVersion -ge "6.0.0"
if ($isPsCore) {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'byteEncodingParam', Justification = 'False positive.')]
$byteEncodingParam = @{ "asByteStream" = $true }
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'allowUnencryptedAuthenticationParam', Justification = 'False positive.')]
$allowUnencryptedAuthenticationParam = @{ "allowUnencryptedAuthentication" = $true }
}
else {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'byteEncodingParam', Justification = 'False positive.')]
$byteEncodingParam = @{ "Encoding" = "byte" }
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', 'allowUnencryptedAuthenticationParam', Justification = 'False positive.')]
$allowUnencryptedAuthenticationParam = @{ }
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidAssignmentToAutomaticVariable', 'isWindows', Justification = 'Will only run on PS5')]
$isWindows = $true
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidAssignmentToAutomaticVariable', 'isLinux', Justification = 'Will only run on PS5')]
$isLinux = $false
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidAssignmentToAutomaticVariable', 'isMacOS', Justification = 'Will only run on PS5')]
$IsMacOS = $false
}
# Copy a HashTable to ensure non case sensitivity (Issue #385)
function Copy-HashTable() {
[CmdletBinding()]
[OutputType([System.Collections.HashTable])]
Param(
[parameter(ValueFromPipeline)]
[hashtable] $object
)
Process {
$ht = @{}
if ($object) {
$object.Keys | ForEach-Object {
$ht[$_] = $object[$_]
}
}
$ht
}
}
function IsPropertySecret {
param (
[string] $propertyName
)
return $notSecretProperties -notcontains $propertyName
}
function ConvertTo-HashTable() {
[CmdletBinding()]
[OutputType([System.Collections.HashTable])]
Param(
[parameter(ValueFromPipeline)]
$object,
[switch] $recurse
)
Process {
function AddValueToHashTable {
Param(
[hashtable] $ht,
[string] $name,
$value,
[switch] $recurse
)
if ($ht.Contains($name)) {
throw "Duplicate key $name"
}
if ($recurse -and ($value -is [System.Collections.Specialized.OrderedDictionary] -or $value -is [hashtable] -or $value -is [System.Management.Automation.PSCustomObject])) {
$ht[$name] = ConvertTo-HashTable $value -recurse
}
elseif ($recurse -and $value -is [array]) {
$ht[$name] = @($value | ForEach-Object {
if (($_ -is [System.Collections.Specialized.OrderedDictionary]) -or ($_ -is [hashtable]) -or ($_ -is [System.Management.Automation.PSCustomObject])) {
ConvertTo-HashTable $_ -recurse
}
else {
$_
}
})
}
else {
$ht[$name] = $value
}
}
$ht = @{}
if ($object -is [System.Collections.Specialized.OrderedDictionary] -or $object -is [hashtable]) {
foreach($key in $object.Keys) {
AddValueToHashTable -ht $ht -name $key -value $object."$key" -recurse:$recurse
}
}
elseif ($object -is [System.Management.Automation.PSCustomObject]) {
foreach($property in $object.PSObject.Properties) {
AddValueToHashTable -ht $ht -name $property.Name -value $property.Value -recurse:$recurse
}
}
$ht
}
}
function OutputError {
Param(
[string] $message
)
if ($runningLocal) {
throw $message
}
else {
Write-Host "::Error::$($message.Replace("`r",'').Replace("`n",' '))"
$host.SetShouldExit(1)
}
}
function OutputWarning {
Param(
[string] $message
)
if ($runningLocal) {
Write-Host -ForegroundColor Yellow "WARNING: $message"
}
else {
Write-Host "::Warning::$message"
}
}
function OutputNotice {
Param(
[string] $message
)
if ($runningLocal) {
Write-Host $message
}
else {
Write-Host "::Notice::$message"
}
}
function MaskValueInLog {
Param(
[string] $value
)
if (!$runningLocal) {
Write-Host "`r::add-mask::$value"
}
}
function OutputDebug {
Param(
[string] $message
)
if ($runningLocal) {
Write-Host $message
}
else {
Write-Host "::Debug::$message"
}
}
function GetUniqueFolderName {
Param(
[string] $baseFolder,
[string] $folderName
)
$i = 2
$name = $folderName
while (Test-Path (Join-Path $baseFolder $name)) {
$name = "$folderName($i)"
$i++
}
$name
}
function stringToInt {
Param(
[string] $str,
[int] $default = -1
)
$i = 0
if ([int]::TryParse($str.Trim(), [ref] $i)) {
$i
}
else {
$default
}
}
function Expand-7zipArchive {
Param (
[Parameter(Mandatory = $true)]
[string] $Path,
[string] $DestinationPath
)
$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"
$use7zip = $false
if (Test-Path -Path $7zipPath -PathType Leaf) {
try {
$use7zip = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($7zipPath).FileMajorPart -ge 19
}
catch {
$use7zip = $false
}
}
if ($use7zip) {
OutputDebug -message "Using 7zip"
Set-Alias -Name 7z -Value $7zipPath
$command = '7z x "{0}" -o"{1}" -aoa -r' -f $Path, $DestinationPath
Invoke-Expression -Command $command | Out-Null
}
else {
OutputDebug -message "Using Expand-Archive"
Expand-Archive -Path $Path -DestinationPath "$DestinationPath" -Force
}
}
#
# Get Path to BcContainerHelper module (download if necessary)
#
# If $env:BcContainerHelperPath is set, it will be reused (ignoring the ContainerHelperVersion)
#
# ContainerHelperVersion can be:
# - preview (or dev), which will use the preview version downloaded from bccontainerhelper blob storage
# - latest, which will use the latest version downloaded from bccontainerhelper blob storage
# - a specific version, which will use the specific version downloaded from bccontainerhelper blob storage
# - none, which will use the BcContainerHelper module installed on the build agent
# - https://... - direct download url to a zip file containing the BcContainerHelper module
#
# When using direct download url, the module will be downloaded to a temp folder and will not be cached
# When using none, the module will be located in modules and used from there
# When using preview, latest or a specific version number, the module will be downloaded to a cache folder and will be reused if the same version is requested again
# This is to avoid filling up the temp folder with multiple identical versions of BcContainerHelper
# The cache folder is C:\ProgramData\BcContainerHelper on Windows and /home/<username>/.BcContainerHelper on Linux
# A Mutex will be used to ensure multiple agents aren't fighting over the same cache folder
#
# This function will set $env:BcContainerHelperPath, which is the path to the BcContainerHelper.ps1 file for reuse in subsequent calls
#
function GetBcContainerHelperPath([string] $bcContainerHelperVersion) {
if ("$env:BcContainerHelperPath" -and (Test-Path -Path $env:BcContainerHelperPath -PathType Leaf)) {
return $env:BcContainerHelperPath
}
if ($bcContainerHelperVersion -eq 'None') {
$module = Get-Module BcContainerHelper
if (-not $module) {
OutputError "When setting BcContainerHelperVersion to none, you need to ensure that BcContainerHelper is installed on the build agent"
}
$bcContainerHelperPath = Join-Path (Split-Path $module.Path -parent) "BcContainerHelper.ps1" -Resolve
}
else {
if ($isWindows) {
$bcContainerHelperRootFolder = 'C:\ProgramData\BcContainerHelper'
}
else {
$myUsername = (whoami)
$bcContainerHelperRootFolder = "/home/$myUsername/.BcContainerHelper"
}
if (!(Test-Path $bcContainerHelperRootFolder)) {
New-Item -Path $bcContainerHelperRootFolder -ItemType Directory | Out-Null
}
$webclient = New-Object System.Net.WebClient
if ($bcContainerHelperVersion -like "https://*") {
# Use temp space for private versions
$tempName = Join-Path ([System.IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString())
Write-Host "Downloading BcContainerHelper developer version from $bcContainerHelperVersion"
try {
$webclient.DownloadFile($bcContainerHelperVersion, "$tempName.zip")
}
catch {
$tempName = Join-Path $bcContainerHelperRootFolder ([Guid]::NewGuid().ToString())
$bcContainerHelperVersion = "preview"
Write-Host "Download failed, downloading BcContainerHelper $bcContainerHelperVersion version from Blob Storage"
$webclient.DownloadFile("https://bccontainerhelper.blob.core.windows.net/public/$($bcContainerHelperVersion).zip", "$tempName.zip")
}
}
else {
$tempName = Join-Path $bcContainerHelperRootFolder ([Guid]::NewGuid().ToString())
if ($bcContainerHelperVersion -eq "dev") {
# For backwards compatibility, use preview when dev is specified
$bcContainerHelperVersion = 'preview'
}
Write-Host "Downloading BcContainerHelper $bcContainerHelperVersion version from Blob Storage"
$webclient.DownloadFile("https://bccontainerhelper.blob.core.windows.net/public/$($bcContainerHelperVersion).zip", "$tempName.zip")
}
Expand-7zipArchive -Path "$tempName.zip" -DestinationPath $tempName
$bcContainerHelperPath = (Get-Item -Path (Join-Path $tempName "*\BcContainerHelper.ps1")).FullName
Remove-Item -Path "$tempName.zip" -ErrorAction SilentlyContinue
if ($bcContainerHelperVersion -notlike "https://*") {
# Check whether the version is already available in the cache
$version = ([System.IO.File]::ReadAllText((Join-Path $tempName 'BcContainerHelper/Version.txt'), [System.Text.Encoding]::UTF8)).Trim()
$cacheFolder = Join-Path $bcContainerHelperRootFolder $version
# To avoid two agents on the same machine downloading the same version at the same time, use a mutex
$buildMutexName = "DownloadAndImportBcContainerHelper"
$buildMutex = New-Object System.Threading.Mutex($false, $buildMutexName)
try {
try {
if (!$buildMutex.WaitOne(1000)) {
Write-Host "Waiting for other process loading BcContainerHelper"
$buildMutex.WaitOne() | Out-Null
Write-Host "Other process completed loading BcContainerHelper"
}
}
catch [System.Threading.AbandonedMutexException] {
Write-Host "Other process terminated abnormally"
}
if (Test-Path $cacheFolder) {
Remove-Item $tempName -Recurse -Force
}
else {
Rename-Item -Path $tempName -NewName $version
}
}
finally {
$buildMutex.ReleaseMutex()
}
$bcContainerHelperPath = Join-Path $cacheFolder "BcContainerHelper/BcContainerHelper.ps1"
}
}
$env:BcContainerHelperPath = $bcContainerHelperPath
if ($ENV:GITHUB_ENV) {
Add-Content -Encoding UTF8 -Path $ENV:GITHUB_ENV "BcContainerHelperPath=$bcContainerHelperPath"
}
return $bcContainerHelperPath
}
#
# Download and import the BcContainerHelper module based on repository settings
# baseFolder is the repository baseFolder
#
function DownloadAndImportBcContainerHelper([string] $baseFolder = $ENV:GITHUB_WORKSPACE) {
$params = @{ "ExportTelemetryFunctions" = $true }
$repoSettingsPath = Join-Path $baseFolder $repoSettingsFile
# Default BcContainerHelper Version is hardcoded in AL-Go-Helper (replaced during AL-Go deploy)
$bcContainerHelperVersion = $defaultBcContainerHelperVersion
if (Test-Path $repoSettingsPath) {
# Read Repository Settings file (without applying organization variables, repository variables or project settings files)
# Override default BcContainerHelper version from AL-Go-Helper only if new version is specifically specified in repo settings file
$repoSettings = Get-Content $repoSettingsPath -Encoding UTF8 | ConvertFrom-Json | ConvertTo-HashTable
if ($repoSettings.Keys -contains "BcContainerHelperVersion") {
$bcContainerHelperVersion = $repoSettings.BcContainerHelperVersion
Write-Host "Using BcContainerHelper $bcContainerHelperVersion version"
if ($bcContainerHelperVersion -like "https://*") {
throw "Setting BcContainerHelperVersion to a URL in settings is not allowed. Fork the AL-Go repository and use direct AL-Go development instead."
}
if ($bcContainerHelperVersion -ne 'latest' -and $bcContainerHelperVersion -ne 'preview') {
Write-Host "::Warning::Using a specific version of BcContainerHelper is not recommended and will lead to build failures in the future. Consider removing the setting."
}
}
$params += @{ "bcContainerHelperConfigFile" = $repoSettingsPath }
}
if ($bcContainerHelperVersion -eq '') {
$bcContainerHelperVersion = "latest"
}
if ($bcContainerHelperVersion -eq 'private') {
throw "ContainerHelperVersion private is no longer supported. Use direct AL-Go development and a direct download url instead."
}
$bcContainerHelperPath = GetBcContainerHelperPath -bcContainerHelperVersion $bcContainerHelperVersion
Write-Host "Import from $bcContainerHelperPath"
. $bcContainerHelperPath @params
}
function MergeCustomObjectIntoOrderedDictionary {
Param(
[System.Collections.Specialized.OrderedDictionary] $dst,
[PSCustomObject] $src
)
# Loop through all properties in the source object
# If the property does not exist in the destination object, add it with the right type, but no value
# Types supported: PSCustomObject, Object[] and simple types
$src.PSObject.Properties.GetEnumerator() | ForEach-Object {
$prop = $_.Name
$srcProp = $src."$prop"
$srcPropType = $srcProp.GetType().Name
if (-not $dst.Contains($prop)) {
if ($srcPropType -eq "PSCustomObject") {
$dst.Add("$prop", [ordered]@{})
}
elseif ($srcPropType -eq "Object[]") {
$dst.Add("$prop", @())
}
else {
$dst.Add("$prop", $srcProp)
}
}
}
# Loop through all properties in the destination object
# If the property does not exist in the source object, do nothing
# If the property exists in the source object, but is of a different type, throw an error
# If the property exists in the source object:
# If the property is an Object, call this function recursively to merge values
# If the property is an Object[], merge the arrays
# If the property is a simple type, replace the value in the destination object with the value from the source object
@($dst.Keys) | ForEach-Object {
$prop = $_
if ($src.PSObject.Properties.Name -eq $prop) {
$dstProp = $dst."$prop"
$srcProp = $src."$prop"
$dstPropType = $dstProp.GetType().Name
$srcPropType = $srcProp.GetType().Name
if ($srcPropType -eq "PSCustomObject" -and $dstPropType -eq "OrderedDictionary") {
MergeCustomObjectIntoOrderedDictionary -dst $dst."$prop" -src $srcProp
}
elseif ($dstPropType -ne $srcPropType -and !($srcPropType -eq "Int64" -and $dstPropType -eq "Int32")) {
# Under Linux, the Int fields read from the .json file will be Int64, while the settings defaults will be Int32
# This is not seen as an error and will not throw an error
throw "property $prop should be of type $dstPropType, is $srcPropType."
}
else {
if ($srcProp -is [Object[]]) {
$srcProp | ForEach-Object {
$srcElm = $_
$srcElmType = $srcElm.GetType().Name
if ($srcElmType -eq "PSCustomObject") {
# Array of objects are not checked for uniqueness
$ht = [ordered]@{}
$srcElm.PSObject.Properties | Sort-Object -Property Name -Culture "iv-iv" | ForEach-Object {
$ht[$_.Name] = $_.Value
}
$dst."$prop" += @($ht)
}
else {
# Add source element to destination array, but only if it does not already exist
$dst."$prop" = @($dst."$prop" + $srcElm | Select-Object -Unique)
}
}
}
else {
$dst."$prop" = $srcProp
}
}
}
}
}
# Read settings from the settings files
# Settings are read from the following files:
# - ALGoOrgSettings (github Variable) = Organization settings variable
# - .github/AL-Go-Settings.json = Repository Settings file
# - ALGoRepoSettings (github Variable) = Repository settings variable
# - <project>/.AL-Go/settings.json = Project settings file
# - .github/<workflowName>.settings.json = Workflow settings file
# - <project>/.AL-Go/<workflowName>.settings.json = Project workflow settings file
# - <project>/.AL-Go/<userName>.settings.json = User settings file
function ReadSettings {
Param(
[string] $baseFolder = "$ENV:GITHUB_WORKSPACE",
[string] $repoName = "$ENV:GITHUB_REPOSITORY",
[string] $project = '.',
[string] $workflowName = "$ENV:GITHUB_WORKFLOW",
[string] $userName = "$ENV:GITHUB_ACTOR",
[string] $branchName = "$ENV:GITHUB_REF_NAME",
[string] $orgSettingsVariableValue = "$ENV:ALGoOrgSettings",
[string] $repoSettingsVariableValue = "$ENV:ALGoRepoSettings"
)
# If the build is triggered by a pull request the refname will be the merge branch. To apply conditional settings we need to use the base branch
if (($env:GITHUB_EVENT_NAME -eq "pull_request") -and ($branchName -eq $ENV:GITHUB_REF_NAME)) {
$branchName = $env:GITHUB_BASE_REF
}
function GetSettingsObject {
Param(
[string] $path
)
if (Test-Path $path) {
try {
Write-Host "Applying settings from $path"
$settings = Get-Content $path -Encoding UTF8 | ConvertFrom-Json
if ($settings) {
return $settings
}
}
catch {
throw "Error reading $path. Error was $($_.Exception.Message).`n$($_.ScriptStackTrace)"
}
}
else {
Write-Host "No settings found in $path"
}
return $null
}
$repoName = $repoName.SubString("$repoName".LastIndexOf('/') + 1)
$githubFolder = Join-Path $baseFolder ".github"
$workflowName = $workflowName.Trim().Split([System.IO.Path]::getInvalidFileNameChars()) -join ""
# Start with default settings
$settings = [ordered]@{
"type" = "PTE"
"unusedALGoSystemFiles" = @()
"projects" = @()
"powerPlatformSolutionFolder" = ""
"country" = "us"
"artifact" = ""
"companyName" = ""
"repoVersion" = "1.0"
"repoName" = $repoName
"versioningStrategy" = 0
"runNumberOffset" = 0
"appBuild" = 0
"appRevision" = 0
"keyVaultName" = ""
"licenseFileUrlSecretName" = "licenseFileUrl"
"ghTokenWorkflowSecretName" = "ghTokenWorkflow"
"adminCenterApiCredentialsSecretName" = "adminCenterApiCredentials"
"applicationInsightsConnectionStringSecretName" = "applicationInsightsConnectionString"
"keyVaultCertificateUrlSecretName" = ""
"keyVaultCertificatePasswordSecretName" = ""
"keyVaultClientIdSecretName" = ""
"keyVaultCodesignCertificateName" = ""
"codeSignCertificateUrlSecretName" = "codeSignCertificateUrl"
"codeSignCertificatePasswordSecretName" = "codeSignCertificatePassword"
"additionalCountries" = @()
"appDependencies" = @()
"projectName" = ""
"appFolders" = @()
"testDependencies" = @()
"testFolders" = @()
"bcptTestFolders" = @()
"pageScriptingTests" = @()
"restoreDatabases" = @()
"installApps" = @()
"installTestApps" = @()
"installOnlyReferencedApps" = $true
"generateDependencyArtifact" = $false
"skipUpgrade" = $false
"applicationDependency" = "18.0.0.0"
"updateDependencies" = $false
"installTestRunner" = $false
"installTestFramework" = $false
"installTestLibraries" = $false
"installPerformanceToolkit" = $false
"enableCodeCop" = $false
"enableUICop" = $false
"enableCodeAnalyzersOnTestApps" = $false
"customCodeCops" = @()
"failOn" = "error"
"treatTestFailuresAsWarnings" = $false
"rulesetFile" = ""
"enableExternalRulesets" = $false
"vsixFile" = ""
"assignPremiumPlan" = $false
"enableTaskScheduler" = $false
"doNotBuildTests" = $false
"doNotRunTests" = $false
"doNotRunBcptTests" = $false
"doNotRunPageScriptingTests" = $false
"doNotPublishApps" = $false
"doNotSignApps" = $false
"configPackages" = @()
"appSourceCopMandatoryAffixes" = @()
"deliverToAppSource" = [ordered]@{
"mainAppFolder" = ""
"productId" = ""
"includeDependencies" = @()
"continuousDelivery" = $false
}
"obsoleteTagMinAllowedMajorMinor" = ""
"memoryLimit" = ""
"templateUrl" = ""
"templateSha" = ""
"templateBranch" = ""
"appDependencyProbingPaths" = @()
"useProjectDependencies" = $false
"runs-on" = "windows-latest"
"shell" = ""
"githubRunner" = ""
"githubRunnerShell" = ""
"cacheImageName" = "my"
"cacheKeepDays" = 3
"alwaysBuildAllProjects" = $false
"microsoftTelemetryConnectionString" = "InstrumentationKey=cd2cc63e-0f37-4968-b99a-532411a314b8;IngestionEndpoint=https://northeurope-2.in.applicationinsights.azure.com/"
"partnerTelemetryConnectionString" = ""
"sendExtendedTelemetryToMicrosoft" = $false
"environments" = @()
"buildModes" = @()
"useCompilerFolder" = $false
"pullRequestTrigger" = "pull_request_target"
"bcptThresholds" = [ordered]@{
"DurationWarning" = 10
"DurationError" = 25
"NumberOfSqlStmtsWarning" = 5
"NumberOfSqlStmtsError" = 10
}
"fullBuildPatterns" = @()
"excludeEnvironments" = @()
"alDoc" = [ordered]@{
"continuousDeployment" = $false
"deployToGitHubPages" = $true
"maxReleases" = 3
"groupByProject" = $true
"includeProjects" = @()
"excludeProjects" = @()
"header" = "Documentation for {REPOSITORY} {VERSION}"
"footer" = "Documentation for <a href=""https://github.com/{REPOSITORY}"">{REPOSITORY}</a> made with <a href=""https://aka.ms/AL-Go"">AL-Go for GitHub</a>, <a href=""https://go.microsoft.com/fwlink/?linkid=2247728"">ALDoc</a> and <a href=""https://dotnet.github.io/docfx"">DocFx</a>"
"defaultIndexMD" = "## Reference documentation\n\nThis is the generated reference documentation for [{REPOSITORY}](https://github.com/{REPOSITORY}).\n\nYou can use the navigation bar at the top and the table of contents to the left to navigate your documentation.\n\nYou can change this content by creating/editing the **{INDEXTEMPLATERELATIVEPATH}** file in your repository or use the alDoc:defaultIndexMD setting in your repository settings file (.github/AL-Go-Settings.json)\n\n{RELEASENOTES}"
"defaultReleaseMD" = "## Release reference documentation\n\nThis is the generated reference documentation for [{REPOSITORY}](https://github.com/{REPOSITORY}).\n\nYou can use the navigation bar at the top and the table of contents to the left to navigate your documentation.\n\nYou can change this content by creating/editing the **{INDEXTEMPLATERELATIVEPATH}** file in your repository or use the alDoc:defaultReleaseMD setting in your repository settings file (.github/AL-Go-Settings.json)\n\n{RELEASENOTES}"
}
"trustMicrosoftNuGetFeeds" = $true
"commitOptions" = [ordered]@{
"messageSuffix" = ""
"pullRequestAutoMerge" = $false
"pullRequestLabels" = @()
}
"trustedSigning" = [ordered]@{
"Endpoint" = ""
"Account" = ""
"CertificateProfile" = ""
}
"useGitSubmodules" = "false"
"gitSubmodulesTokenSecretName" = "gitSubmodulesToken"
}
# Read settings from files and merge them into the settings object
$settingsObjects = @()
# Read settings from organization settings variable (parameter)
if ($orgSettingsVariableValue) {
$orgSettingsVariableObject = $orgSettingsVariableValue | ConvertFrom-Json
$settingsObjects += @($orgSettingsVariableObject)
}
# Read settings from repository settings file
$repoSettingsObject = GetSettingsObject -Path (Join-Path $baseFolder $RepoSettingsFile)
$settingsObjects += @($repoSettingsObject)
# Read settings from repository settings variable (parameter)
if ($repoSettingsVariableValue) {
$repoSettingsVariableObject = $repoSettingsVariableValue | ConvertFrom-Json
$settingsObjects += @($repoSettingsVariableObject)
}
if ($project) {
# Read settings from project settings file
$projectFolder = Join-Path $baseFolder $project -Resolve
$projectSettingsObject = GetSettingsObject -Path (Join-Path $projectFolder $ALGoSettingsFile)
$settingsObjects += @($projectSettingsObject)
}
if ($workflowName) {
# Read settings from workflow settings file
$workflowSettingsObject = GetSettingsObject -Path (Join-Path $gitHubFolder "$workflowName.settings.json")
$settingsObjects += @($workflowSettingsObject)
if ($project) {
# Read settings from project workflow settings file
$projectWorkflowSettingsObject = GetSettingsObject -Path (Join-Path $projectFolder "$ALGoFolderName/$workflowName.settings.json")
# Read settings from user settings file
$userSettingsObject = GetSettingsObject -Path (Join-Path $projectFolder "$ALGoFolderName/$userName.settings.json")
$settingsObjects += @($projectWorkflowSettingsObject, $userSettingsObject)
}
}
foreach($settingsJson in $settingsObjects) {
if ($settingsJson) {
MergeCustomObjectIntoOrderedDictionary -dst $settings -src $settingsJson
if ($settingsJson.PSObject.Properties.Name -eq "ConditionalSettings") {
foreach($conditionalSetting in $settingsJson.ConditionalSettings) {
if ("$conditionalSetting" -ne "") {
$conditionMet = $true
$conditions = @()
if ($conditionalSetting.PSObject.Properties.Name -eq "branches") {
$conditionMet = $conditionMet -and ($conditionalSetting.branches | Where-Object { $branchName -like $_ })
$conditions += @("branchName: $branchName")
}
if ($conditionalSetting.PSObject.Properties.Name -eq "repositories") {
$conditionMet = $conditionMet -and ($conditionalSetting.repositories | Where-Object { $repoName -like $_ })
$conditions += @("repoName: $repoName")
}
if ($project -and $conditionalSetting.PSObject.Properties.Name -eq "projects") {
$conditionMet = $conditionMet -and ($conditionalSetting.projects | Where-Object { $project -like $_ })
$conditions += @("project: $project")
}
if ($workflowName -and $conditionalSetting.PSObject.Properties.Name -eq "workflows") {
$conditionMet = $conditionMet -and ($conditionalSetting.workflows | Where-Object { $workflowName -like $_ })
$conditions += @("workflowName: $workflowName")
}
if ($userName -and $conditionalSetting.PSObject.Properties.Name -eq "users") {
$conditionMet = $conditionMet -and ($conditionalSetting.users | Where-Object { $userName -like $_ })
$conditions += @("userName: $userName")
}
if ($conditionMet) {
Write-Host "Applying conditional settings for $($conditions -join ", ")"
MergeCustomObjectIntoOrderedDictionary -dst $settings -src $conditionalSetting.settings
}
}
}
}
}
}
# runs-on is used for all jobs except for the build job (basically all jobs which doesn't need a container)
# gitHubRunner is used for the build job (or basically all jobs that needs a container)
#
# shell defaults to "powershell" unless runs-on is Ubuntu (Linux), then it defaults to pwsh
#
# gitHubRunner defaults to "runs-on", unless runs-on is Ubuntu (Linux) as this won't work.
# gitHubRunnerShell defaults to "shell"
#
# The exception for keeping gitHubRunner to Windows-Latest (when set to Ubuntu-*) will be removed when all jobs supports Ubuntu (Linux)
# At some point in the future (likely version 3.0), we will switch to Ubuntu (Linux) as default for "runs-on"
#
if ($settings.shell -eq "") {
if ($settings."runs-on" -like "ubuntu-*") {
$settings.shell = "pwsh"
}
else {
$settings.shell = "powershell"
}
}
if ($settings.githubRunner -eq "") {
if ($settings."runs-on" -like "ubuntu-*") {
$settings.githubRunner = "windows-latest"
}
else {
$settings.githubRunner = $settings."runs-on"
}
}
if ($settings.githubRunnerShell -eq "") {
$settings.githubRunnerShell = $settings.shell
}
# Check that gitHubRunnerShell and Shell is valid
if ($settings.githubRunnerShell -ne "powershell" -and $settings.githubRunnerShell -ne "pwsh") {
throw "Invalid value for setting: gitHubRunnerShell: $($settings.githubRunnerShell)"
}
if ($settings.shell -ne "powershell" -and $settings.shell -ne "pwsh") {
throw "Invalid value for setting: shell: $($settings.githubRunnerShell)"
}
if (($settings.githubRunner -like "ubuntu-*") -and ($settings.githubRunnerShell -eq "powershell")) {
Write-Host "Switching shell to pwsh for ubuntu"
$settings.githubRunnerShell = "pwsh"
}
if($settings.projectName -eq '') {
$settings.projectName = $project # Default to project path as project name
}
$settings
}
function ExcludeUnneededApps {
Param(
[string[]] $folders,
[string[]] $includeOnlyAppIds,
[hashtable] $appIdFolders
)
foreach($folder in $folders) {
if ($includeOnlyAppIds.Contains(($appIdFolders.GetEnumerator() | Where-Object { $_.Value -eq $folder }).Key)) {
$folder
}
}
}
function ResolveProjectFolders {
Param(
[string] $project,
[string] $baseFolder,
[ref] $projectSettings
)
$projectPath = Join-Path $baseFolder $project -Resolve
Push-Location $projectPath
try {
$appFolders = $projectSettings.Value.appFolders
$testFolders = $projectSettings.Value.testFolders
$bcptTestFolders = $projectSettings.Value.bcptTestFolders
# If no app folders are specified in AL-Go settings, check for AL apps in the project folder
if (!$appFolders -and !$testFolders -and !$bcptTestFolders) {
Get-ChildItem -Path $projectPath -Recurse | Where-Object { $_.PSIsContainer -and (Test-Path -Path (Join-Path $_.FullName "app.json")) } | ForEach-Object {
$aLProjectFolder = $_
$appJson = Get-Content (Join-Path $aLProjectFolder.FullName "app.json") -Encoding UTF8 | ConvertFrom-Json
$isTestApp = $false
$isBcptTestApp = $false
# if an AL app has a dependency to a test app, it is a test app
# if an AL app has a dependency to an app from the performance toolkit apps, it is a bcpt test app
if ($appJson.PSObject.Properties.Name -eq "dependencies") {
foreach($dependency in $appJson.dependencies) {
if ($dependency.PSObject.Properties.Name -eq "AppId") {
$id = $dependency.AppId
}
else {
$id = $dependency.Id
}
# Check if the app is a test app or a bcpt app
if ($performanceToolkitApps.Contains($id)) {
$isBcptTestApp = $true
}
elseif ($testRunnerApps.Contains($id)) {
$isTestApp = $true
}
}
}
# Folders are relative to the project folder
$appFolder = Resolve-Path -Path $aLProjectFolder.FullName -Relative
switch ($true) {
$isBcptTestApp { $bcptTestFolders += @($appFolder); break }
$isTestApp { $testFolders += @($appFolder); break }
Default { $appFolders += @($appFolder) }
}
}
}
# Filter out app folders that doesn't contain an app.json file
function FilterFolders($projectPath, $folders) {
if (!$folders) {
return @()
}
$resolvedPaths = @()
foreach ($folder in $folders) {
$aLProjectFolder = Join-Path $projectPath $folder
$resolvedALProjectsPaths = Resolve-Path $aLProjectFolder -Relative -ErrorAction Ignore | Where-Object { Test-Path (Join-Path $_ 'app.json') }
if ($resolvedALProjectsPaths) {
$resolvedPaths += @($resolvedALProjectsPaths)
}
else {
OutputWarning "The folder '$folder' for project '$project' cannot be resolved or does not contain an app.json file. Skipping."
}
}
return $resolvedPaths
}
$projectSettings.Value.appFolders = @(FilterFolders $projectPath $appFolders)
$projectSettings.Value.testFolders = @(FilterFolders $projectPath $testFolders)
$projectSettings.Value.bcptTestFolders = @(FilterFolders $projectPath $bcptTestFolders)
}
finally {
Pop-Location
}
}
function AnalyzeRepo {
Param(
[hashTable] $settings,
[string] $baseFolder = $ENV:GITHUB_WORKSPACE,
[string] $project = '.',
[switch] $doNotCheckArtifactSetting,
[switch] $doNotIssueWarnings,
[string[]] $includeOnlyAppIds
)
$settings = $settings | Copy-HashTable
if (!$runningLocal) {
Write-Host "::group::Analyzing repository"
}
$projectPath = Join-Path $baseFolder $project -Resolve
# Check applicationDependency
[Version]$settings.applicationDependency | Out-null
Write-Host "Checking type"
if ($settings.type -eq "PTE") {
if (!$settings.Contains('enablePerTenantExtensionCop')) {
$settings.Add('enablePerTenantExtensionCop', $true)
}
if (!$settings.Contains('enableAppSourceCop')) {
$settings.Add('enableAppSourceCop', $false)
}
}
elseif ($settings.type -eq "AppSource App") {
if (!$settings.Contains('enablePerTenantExtensionCop')) {
$settings.Add('enablePerTenantExtensionCop', $false)
}
if (!$settings.Contains('enableAppSourceCop')) {
$settings.Add('enableAppSourceCop', $true)
}
if ($settings.enableAppSourceCop -and (-not ($settings.appSourceCopMandatoryAffixes))) {
# Do not throw an error if we only read the Repo Settings file
if (Test-Path (Join-Path $baseFolder $ALGoSettingsFile)) {
throw "For AppSource Apps with AppSourceCop enabled, you need to specify AppSourceCopMandatoryAffixes in $ALGoSettingsFile"
}
}
}
else {
throw "The type, specified in $RepoSettingsFile, must be either 'PTE' or 'AppSource App'. It is '$($settings.type)'."
}
ResolveProjectFolders -baseFolder $baseFolder -project $project -projectSettings ([ref] $settings)
Write-Host "Checking appFolders, testFolders and bcptTestFolders"
$dependencies = [ordered]@{}
$appIdFolders = [ordered]@{}
1..3 | ForEach-Object {
$appFolder = $_ -eq 1
$testFolder = $_ -eq 2
$bcptTestFolder = $_ -eq 3
if ($appFolder) {
$folders = @($settings.appFolders)
$descr = "App folder"
}
elseif ($testFolder) {
$folders = @($settings.testFolders)
$descr = "Test folder"
}
elseif ($bcptTestFolder) {
$folders = @($settings.bcptTestFolders)
$descr = "Bcpt Test folder"
}
else {
throw "Internal error"
}
$folders | ForEach-Object {
$folderName = $_
$folder = Join-Path $projectPath $folderName
$appJsonFile = Join-Path $folder "app.json"
$bcptSuiteFile = Join-Path $folder "bcptSuite.json"
$enumerate = $true
# Check if there are any folders matching $folder
if (!(Get-Item $folder | Where-Object { $_ -is [System.IO.DirectoryInfo] })) {
if (!$doNotIssueWarnings) { OutputWarning -message "$descr $folderName, specified in $ALGoSettingsFile, does not exist" }
}
elseif (-not (Test-Path $appJsonFile -PathType Leaf)) {
if (!$doNotIssueWarnings) { OutputWarning -message "$descr $folderName, specified in $ALGoSettingsFile, does not contain the source code for an app (no app.json file)" }
}
elseif ($bcptTestFolder -and (-not (Test-Path $bcptSuiteFile -PathType Leaf))) {
if (!$doNotIssueWarnings) { OutputWarning -message "$descr $folderName, specified in $ALGoSettingsFile, does not contain a BCPT Suite (bcptSuite.json)" }