forked from microsoft/AL-Go-Actions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AL-Go-Helper.ps1
1650 lines (1518 loc) · 69 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
}
$ErrorActionPreference = "stop"
Set-StrictMode -Version 2.0
$ALGoFolder = ".AL-Go\"
$ALGoSettingsFile = ".AL-Go\settings.json"
$RepoSettingsFile = ".github\AL-Go-Settings.json"
$defaultCICDPushBranches = @( 'main', 'release/*', 'feature/*' )
$defaultCICDPullRequestBranches = @( 'main' )
$runningLocal = $local.IsPresent
$runAlPipelineOverrides = @(
"DockerPull"
"NewBcContainer"
"ImportTestToolkitToBcContainer"
"CompileAppInBcContainer"
"GetBcContainerAppInfo"
"PublishBcContainerApp"
"UnPublishBcContainerApp"
"InstallBcAppFromAppSource"
"SignBcContainerApp"
"ImportTestDataInBcContainer"
"RunTestsInBcContainer"
"GetBcContainerAppRuntimePackage"
"RemoveBcContainer"
)
# 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
$MicrosoftTelemetryConnectionString = "InstrumentationKey=84bd9223-67d4-4378-8590-9e4a46023be2;IngestionEndpoint=https://westeurope-1.in.applicationinsights.azure.com/"
function ConvertTo-HashTable {
[CmdletBinding()]
Param(
[parameter(ValueFromPipeline)]
[PSCustomObject] $object
)
$ht = @{}
if ($object) {
$object.PSObject.Properties | ForEach-Object { $ht[$_.Name] = $_.Value }
}
$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 MaskValueInLog {
Param(
[string] $value
)
if (!$runningLocal) {
Write-Host "::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
}
}
function DownloadAndImportBcContainerHelper {
Param(
[string] $BcContainerHelperVersion = "",
[string] $baseFolder = ""
)
$params = @{ "ExportTelemetryFunctions" = $true }
if ($baseFolder) {
$repoSettingsPath = Join-Path $baseFolder $repoSettingsFile
if (-not (Test-Path $repoSettingsPath -PathType Leaf)) {
$repoSettingsPath = Join-Path $baseFolder "..\$repoSettingsFile"
if (-not (Test-Path $repoSettingsPath -PathType Leaf)) {
$repoSettingsPath = Join-Path $baseFolder "..\..\$repoSettingsFile"
}
}
if (Test-Path $repoSettingsPath) {
if (-not $BcContainerHelperVersion) {
$repoSettings = Get-Content $repoSettingsPath -Encoding UTF8 | ConvertFrom-Json | ConvertTo-HashTable
$ap = "$ENV:GITHUB_ACTION_PATH".Split('\')
if ($ap -and $ap.Count -gt 4) {
$branch = $ap[$ap.Count - 2]
$owner = $ap[$ap.Count - 4]
if ($owner -eq "freddydk") {
$bcContainerHelperVersion = "dev"
}
elseif ($owner -eq "businesscentralapps") {
$bcContainerHelperVersion = "preview"
}
elseif ($owner -eq "microsoft" -and $branch -eq "preview") {
$bcContainerHelperVersion = "preview"
}
}
if ($bcContainerHelperVersion -eq "" -and $repoSettings.ContainsKey("BcContainerHelperVersion")) {
$BcContainerHelperVersion = $repoSettings.BcContainerHelperVersion
}
}
$params += @{ "bcContainerHelperConfigFile" = $repoSettingsPath }
}
}
if (-not $BcContainerHelperVersion) {
$BcContainerHelperVersion = "latest"
}
if ($bcContainerHelperVersion -eq "none") {
$tempName = ""
$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 {
$tempName = Join-Path $env:TEMP ([Guid]::NewGuid().ToString())
$webclient = New-Object System.Net.WebClient
if ($BcContainerHelperVersion -eq "dev") {
Write-Host "Downloading BcContainerHelper developer version"
$webclient.DownloadFile("https://github.com/microsoft/navcontainerhelper/archive/dev.zip", "$tempName.zip")
}
else {
Write-Host "Downloading BcContainerHelper $BcContainerHelperVersion version"
try {
$webclient.DownloadFile("https://bccontainerhelper.azureedge.net/public/$($BcContainerHelperVersion).zip", "$tempName.zip")
}
catch {
$webclient.DownloadFile("https://bccontainerhelper.blob.core.windows.net/public/$($BcContainerHelperVersion).zip", "$tempName.zip")
}
}
Expand-7zipArchive -Path "$tempName.zip" -DestinationPath $tempName
Remove-Item -Path "$tempName.zip"
$BcContainerHelperPath = (Get-Item -Path (Join-Path $tempName "*\BcContainerHelper.ps1")).FullName
}
. $BcContainerHelperPath @params
$tempName
}
function CleanupAfterBcContainerHelper {
Param(
[string] $bcContainerHelperPath
)
if ($bcContainerHelperPath) {
try {
Write-Host "Removing BcContainerHelper"
Remove-Module BcContainerHelper
Remove-Item $bcContainerHelperPath -Recurse -Force
}
catch {}
}
}
function MergeCustomObjectIntoOrderedDictionary {
Param(
[System.Collections.Specialized.OrderedDictionary] $dst,
[PSCustomObject] $src
)
# Add missing properties in OrderedDictionary
$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)
}
}
}
@($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) {
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") {
$ht = [ordered]@{}
$srcElm.PSObject.Properties | Sort-Object -Property Name -Culture "iv-iv" | ForEach-Object { $ht[$_.Name] = $_.Value }
$dst."$prop" += @($ht)
}
else {
$dst."$prop" += $srcElm
}
}
}
else {
$dst."$prop" = $srcProp
}
}
}
}
}
function ReadSettings {
Param(
[string] $baseFolder,
[string] $repoName = "$env:GITHUB_REPOSITORY",
[string] $workflowName = "",
[string] $userName = ""
)
$repoName = $repoName.SubString("$repoName".LastIndexOf('/') + 1)
# Read Settings file
$settings = [ordered]@{
"type" = "PTE"
"country" = "us"
"artifact" = ""
"companyName" = ""
"repoVersion" = "1.0"
"repoName" = $repoName
"versioningStrategy" = 0
"runNumberOffset" = 0
"appBuild" = 0
"appRevision" = 0
"keyVaultName" = ""
"licenseFileUrlSecretName" = "LicenseFileUrl"
"insiderSasTokenSecretName" = "InsiderSasToken"
"ghTokenWorkflowSecretName" = "GhTokenWorkflow"
"adminCenterApiCredentialsSecretName" = "AdminCenterApiCredentials"
"applicationInsightsConnectionStringSecretName" = "ApplicationInsightsConnectionString"
"keyVaultCertificateUrlSecretName" = ""
"keyVaultCertificatePasswordSecretName" = ""
"keyVaultClientIdSecretName" = ""
"codeSignCertificateUrlSecretName" = "CodeSignCertificateUrl"
"codeSignCertificatePasswordSecretName" = "CodeSignCertificatePassword"
"storageContextSecretName" = "StorageContext"
"additionalCountries" = @()
"appDependencies" = @()
"appFolders" = @()
"testDependencies" = @()
"testFolders" = @()
"bcptTestFolders" = @()
"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
"customCodeCops" = @()
"failOn" = "error"
"rulesetFile" = ""
"doNotBuildTests" = $false
"doNotRunTests" = $false
"doNotRunBcptTests" = $false
"doNotPublishApps" = $false
"doNotSignApps" = $false
"appSourceCopMandatoryAffixes" = @()
"obsoleteTagMinAllowedMajorMinor" = ""
"memoryLimit" = ""
"templateUrl" = ""
"templateBranch" = ""
"appDependencyProbingPaths" = @()
"runs-on" = "self-hosted"
"githubRunner" = ""
"cacheImageName" = "my"
"cacheKeepDays" = 3
"alwaysBuildAllProjects" = $false
"MicrosoftTelemetryConnectionString" = $MicrosoftTelemetryConnectionString
"PartnerTelemetryConnectionString" = ""
"SendExtendedTelemetryToMicrosoft" = $false
"Environments" = @()
}
$gitHubFolder = ".github"
$repoSettingsPath = $RepoSettingsFile
if (-not (Test-Path (Join-Path $baseFolder $repoSettingsPath) -PathType Leaf)) {
$RepoSettingsPath = "..\$RepoSettingsPath"
$gitHubFolder = "..\$gitHubFolder"
if (-not (Test-Path (Join-Path $baseFolder $RepoSettingsPath) -PathType Leaf)) {
$RepoSettingsPath = "..\$RepoSettingsPath"
$gitHubFolder = "..\$gitHubFolder"
}
}
$workflowName = $workflowName.Split([System.IO.Path]::getInvalidFileNameChars()) -join ""
$RepoSettingsPath, $ALGoSettingsFile, (Join-Path $gitHubFolder "$workflowName.settings.json"), (Join-Path $ALGoFolder "$workflowName.settings.json"), (Join-Path $ALGoFolder "$userName.settings.json") | ForEach-Object {
$settingsFile = $_
$settingsPath = Join-Path $baseFolder $settingsFile
if (Test-Path $settingsPath) {
try {
Write-Host "Reading $settingsFile"
$settingsJson = Get-Content $settingsPath -Encoding UTF8 | ConvertFrom-Json
# check settingsJson.version and do modifications if needed
MergeCustomObjectIntoOrderedDictionary -dst $settings -src $settingsJson
if ($settingsJson.PSObject.Properties.Name -eq "ConditionalSettings") {
$settingsJson.ConditionalSettings | ForEach-Object {
$conditionalSetting = $_
if ($conditionalSetting.branches | Where-Object { $ENV:GITHUB_REF_NAME -like $_ }) {
Write-Host "Applying conditional settings for $ENV:GITHUB_REF_NAME"
MergeCustomObjectIntoOrderedDictionary -dst $settings -src $conditionalSetting.settings
}
}
}
}
catch {
throw "Settings file $settingsFile, is wrongly formatted. Error is $($_.Exception.Message)."
}
}
}
if ($settings.githubRunner -eq "") {
$settings.githubRunner = $settings."runs-on"
}
$settings
}
function ExcludeUnneededApps {
Param(
[string[]] $folders,
[string[]] $includeOnlyAppIds,
[hashtable] $appIdFolders
)
$folders | ForEach-Object {
$folder = $_
if ($includeOnlyAppIds.Contains(($appIdFolders.GetEnumerator() | Where-Object { $_.Value -eq $folder }).Key)) {
$folder
}
}
}
function AnalyzeRepo {
Param(
[hashTable] $settings,
$token,
[string] $baseFolder,
[string] $project,
[string] $insiderSasToken,
[switch] $doNotCheckArtifactSetting,
[switch] $doNotIssueWarnings,
[string[]] $includeOnlyAppIds,
[string] $server_url = $ENV:GITHUB_SERVER_URL,
[string] $repository = $ENV:GITHUB_REPOSITORY
)
if (!$runningLocal) {
Write-Host "::group::Analyzing repository"
}
$projectPath = Join-Path $baseFolder $project -Resolve
Set-Location $projectPath
# 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))) {
throw "For AppSource Apps with AppSourceCop enabled, you need to specify AppSourceCopMandatoryAffixes in $ALGoSettingsFile"
}
}
else {
throw "The type, specified in $ALGoSettingsFile, must be either 'Per Tenant Extension' or 'AppSource App'. It is '$($settings.type)'."
}
if (-not (@($settings.appFolders) + @($settings.testFolders) + @($settings.bcptTestFolders))) {
Get-ChildItem -Path $projectPath -Directory | Where-Object { Test-Path -Path (Join-Path $_.FullName "app.json") } | ForEach-Object {
$folder = $_
$appJson = Get-Content (Join-Path $folder.FullName "app.json") -Encoding UTF8 | ConvertFrom-Json
$isTestApp = $false
$isBcptTestApp = $false
if ($appJson.PSObject.Properties.Name -eq "dependencies") {
$appJson.dependencies | ForEach-Object {
if ($_.PSObject.Properties.Name -eq "AppId") {
$id = $_.AppId
}
else {
$id = $_.Id
}
if ($performanceToolkitApps.Contains($id)) {
$isBcptTestApp = $true
}
elseif ($testRunnerApps.Contains($id)) {
$isTestApp = $true
}
}
}
if ($isBcptTestApp) {
$settings.bcptTestFolders += @($_.Name)
}
elseif ($isTestApp) {
$settings.testFolders += @($_.Name)
}
else {
$settings.appFolders += @($_.Name)
}
}
}
Write-Host "Checking appFolders and testFolders"
$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
if (-not (Test-Path $folder -PathType Container)) {
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)" }
$settings.bcptTestFolders = @($settings.bcptTestFolders | Where-Object { $_ -ne $folderName })
$enumerate = $false
}
if ($enumerate) {
$expandFolders = @(Get-Item $appJsonFile -ErrorAction SilentlyContinue | ForEach-Object { Resolve-Path -Relative $_.Directory })
if ($appFolder) {
$settings.appFolders = @($settings.appFolders | Where-Object { $_ -ne $folderName }) + $expandFolders
}
elseif ($testFolder) {
$settings.testFolders = @($settings.testFolders | Where-Object { $_ -ne $folderName }) + $expandFolders
}
elseif ($bcptTestFolder) {
$settings.bcptTestFolders = @($settings.bcptTestFolders | Where-Object { $_ -ne $folderName }) + $expandFolders
}
$expandFolders | ForEach-Object {
$folderName = $_
$folder = Join-Path $projectPath $folderName
$appJsonFile = Join-Path $folder "app.json"
if ($dependencies.Contains($folderName)) {
throw "$descr $folderName, specified in $ALGoSettingsFile, is specified more than once."
}
$dependencies.Add($folderName, @())
try {
$appJson = Get-Content $appJsonFile -Encoding UTF8 | ConvertFrom-Json
if ($appIdFolders.Contains($appJson.Id)) {
throw "$descr $folderName contains a duplicate AppId ($($appIdFolders."$appJson.Id"))"
}
$appIdFolders.Add($appJson.Id, $folderName)
if ($appJson.PSObject.Properties.Name -eq 'Dependencies') {
$appJson.dependencies | ForEach-Object {
if ($_.PSObject.Properties.Name -eq "AppId") {
$id = $_.AppId
}
else {
$id = $_.Id
}
if ($id -eq $applicationAppId) {
if ([Version]$_.Version -gt [Version]$settings.applicationDependency) {
$settings.applicationDependency = $appDep
}
}
else {
$dependencies."$folderName" += @( [ordered]@{ "id" = $id; "version" = $_.version } )
}
}
}
if ($appJson.PSObject.Properties.Name -eq 'Application') {
$appDep = $appJson.application
if ([Version]$appDep -gt [Version]$settings.applicationDependency) {
$settings.applicationDependency = $appDep
}
}
}
catch {
throw "$descr $folderName, specified in $ALGoSettingsFile, contains a corrupt app.json file. Error is $($_.Exception.Message)."
}
}
}
}
}
Write-Host "Application Dependency $($settings.applicationDependency)"
if ($includeOnlyAppIds) {
$i = 0
while ($i -lt $includeOnlyAppIds.Count) {
$id = $includeOnlyAppIds[$i]
if ($appIdFolders.Contains($id)) {
$dependencies."$($appIdFolders."$id")" | ForEach-Object {
$includeOnlyAppIds += @($_.Id)
}
}
$i++
}
$settings.appFolders = @(ExcludeUnneededApps -folders $settings.appFolders -includeOnlyAppIds $includeOnlyAppIds -appIdFolders $appIdFolders)
$settings.testFolders = @(ExcludeUnneededApps -folders $settings.testFolders -includeOnlyAppIds $includeOnlyAppIds -appIdFolders $appIdFolders)
$settings.bcptTestFolders = @(ExcludeUnneededApps -folders $settings.bcptTestFolders -includeOnlyAppIds $includeOnlyAppIds -appIdFolders $appIdFolders)
}
if (!$doNotCheckArtifactSetting) {
$artifact = $settings.artifact
if ($artifact.Contains('{INSIDERSASTOKEN}')) {
if ($insiderSasToken) {
$artifact = $artifact.replace('{INSIDERSASTOKEN}', $insiderSasToken)
}
else {
throw "Artifact definition $artifact requires you to create a secret called InsiderSasToken, containing the Insider SAS Token from https://aka.ms/collaborate"
}
}
Write-Host "Checking artifact setting"
if ($artifact -eq "" -and $settings.updateDependencies) {
$artifact = Get-BCArtifactUrl -country $settings.country -select all | Where-Object { [Version]$_.Split("/")[4] -ge [Version]$settings.applicationDependency } | Select-Object -First 1
if (-not $artifact) {
if ($insiderSasToken) {
$artifact = Get-BCArtifactUrl -storageAccount bcinsider -country $settings.country -select all -sasToken $insiderSasToken | Where-Object { [Version]$_.Split("/")[4] -ge [Version]$settings.applicationDependency } | Select-Object -First 1
if (-not $artifact) {
throw "No artifacts found for application dependency $($settings.applicationDependency)."
}
}
else {
throw "No artifacts found for application dependency $($settings.applicationDependency). If you are targetting an insider version, you need to create a secret called InsiderSasToken, containing the Insider SAS Token from https://aka.ms/collaborate"
}
}
}
if ($artifact -like "https://*") {
$artifactUrl = $artifact
$storageAccount = ("$artifactUrl////".Split('/')[2]).Split('.')[0]
$artifactType = ("$artifactUrl////".Split('/')[3])
$version = ("$artifactUrl////".Split('/')[4])
$country = ("$artifactUrl////".Split('/')[5])
$sasToken = "$($artifactUrl)?".Split('?')[1]
}
else {
$segments = "$artifact/////".Split('/')
$storageAccount = $segments[0];
$artifactType = $segments[1]; if ($artifactType -eq "") { $artifactType = 'Sandbox' }
$version = $segments[2]
$country = $segments[3]; if ($country -eq "") { $country = $settings.country }
$select = $segments[4]; if ($select -eq "") { $select = "latest" }
$sasToken = $segments[5]
$artifactUrl = Get-BCArtifactUrl -storageAccount $storageAccount -type $artifactType -version $version -country $country -select $select -sasToken $sasToken | Select-Object -First 1
if (-not $artifactUrl) {
throw "No artifacts found for the artifact setting ($artifact) in $ALGoSettingsFile"
}
$version = $artifactUrl.Split('/')[4]
$storageAccount = $artifactUrl.Split('/')[2]
}
if ($settings.additionalCountries -or $country -ne $settings.country) {
if ($country -ne $settings.country -and !$doNotIssueWarnings) {
OutputWarning -message "artifact definition in $ALGoSettingsFile uses a different country ($country) than the country definition ($($settings.country))"
}
Write-Host "Checking Country and additionalCountries"
# AT is the latest published language - use this to determine available country codes (combined with mapping)
$ver = [Version]$version
Write-Host "https://$storageAccount/$artifactType/$version/$country"
$atArtifactUrl = Get-BCArtifactUrl -storageAccount $storageAccount -type $artifactType -country at -version "$($ver.Major).$($ver.Minor)" -select Latest -sasToken $sasToken
Write-Host "Latest AT artifacts $atArtifactUrl"
$latestATversion = $atArtifactUrl.Split('/')[4]
$countries = Get-BCArtifactUrl -storageAccount $storageAccount -type $artifactType -version $latestATversion -sasToken $sasToken -select All | ForEach-Object {
$countryArtifactUrl = $_.Split('?')[0] # remove sas token
$countryArtifactUrl.Split('/')[5] # get country
}
Write-Host "Countries with artifacts $($countries -join ',')"
$allowedCountries = $bcContainerHelperConfig.mapCountryCode.PSObject.Properties.Name + $countries | Select-Object -Unique
Write-Host "Allowed Country codes $($allowedCountries -join ',')"
if ($allowedCountries -notcontains $settings.country) {
throw "Country ($($settings.country)), specified in $ALGoSettingsFile is not a valid country code."
}
$illegalCountries = $settings.additionalCountries | Where-Object { $allowedCountries -notcontains $_ }
if ($illegalCountries) {
throw "additionalCountries contains one or more invalid country codes ($($illegalCountries -join ",")) in $ALGoSettingsFile."
}
$artifactUrl = $artifactUrl.Replace($artifactUrl.Split('/')[4], $atArtifactUrl.Split('/')[4])
}
else {
Write-Host "Downloading artifacts from $($artifactUrl.Split('?')[0])"
$folders = Download-Artifacts -artifactUrl $artifactUrl -includePlatform -ErrorAction SilentlyContinue
if (-not ($folders)) {
throw "Unable to download artifacts from $($artifactUrl.Split('?')[0]), please check $ALGoSettingsFile."
}
}
$settings.artifact = $artifactUrl
if ([Version]$settings.applicationDependency -gt [Version]$version) {
throw "Application dependency is set to $($settings.applicationDependency), which isn't compatible with the artifact version $version"
}
}
# unpack all dependencies and update app- and test dependencies from dependency apps
$settings.appDependencies + $settings.testDependencies | ForEach-Object {
$dep = $_
if ($dep -is [string]) {
# TODO: handle pre-settings - documentation pending
}
}
Write-Host "Updating app- and test Dependencies"
$dependencies.Keys | ForEach-Object {
$folderName = $_
$appFolder = $settings.appFolders.Contains($folderName)
if ($appFolder) { $prop = "appDependencies" } else { $prop = "testDependencies" }
$dependencies."$_" | ForEach-Object {
$id = $_.Id
$version = $_.version
$exists = $settings."$prop" | Where-Object { $_ -is [System.Collections.Specialized.OrderedDictionary] -and $_.id -eq $id }
if ($exists) {
if ([Version]$version -gt [Version]$exists.Version) {
$exists.Version = $version
}
}
else {
$settings."$prop" += @( [ordered]@{ "id" = $id; "version" = $_.version } )
}
}
}
Write-Host "Analyzing Test App Dependencies"
if ($settings.testFolders) { $settings.installTestRunner = $true }
if ($settings.bcptTestFolders) { $settings.installPerformanceToolkit = $true }
$settings.appDependencies + $settings.testDependencies | ForEach-Object {
$dep = $_
if ($dep.GetType().Name -eq "OrderedDictionary") {
if ($testRunnerApps.Contains($dep.id)) { $settings.installTestRunner = $true }
if ($testFrameworkApps.Contains($dep.id)) { $settings.installTestFramework = $true }
if ($testLibrariesApps.Contains($dep.id)) { $settings.installTestLibraries = $true }
if ($performanceToolkitApps.Contains($dep.id)) { $settings.installPerformanceToolkit = $true }
}
}
if (!$runningLocal) {
Write-Host "::endgroup::"
}
Write-Host "Checking appDependencyProbingPaths"
if ($settings.appDependencyProbingPaths) {
$settings.appDependencyProbingPaths = @($settings.appDependencyProbingPaths | ForEach-Object {
if ($_.GetType().Name -eq "PSCustomObject") {
$_
}
else {
New-Object -Type PSObject -Property $_
}
})
$settings.appDependencyProbingPaths | ForEach-Object {
$dependency = $_
if (-not ($dependency.PsObject.Properties.name -eq "repo")) {
throw "AppDependencyProbingPaths needs to contain a repo property, pointing to the repository on which you have a dependency"
}
if ($dependency.Repo -eq ".") {
$dependency.Repo = "$server_url/$repository"
}
elseif ($dependency.Repo -notlike "https://*") {
$dependency.Repo = "$server_url/$($dependency.Repo)"
}
if (-not ($dependency.PsObject.Properties.name -eq "Version")) {
$dependency | Add-Member -Name "Version" -MemberType NoteProperty -Value "latest"
}
if (-not ($dependency.PsObject.Properties.name -eq "Projects")) {
$dependency | Add-Member -Name "Projects" -MemberType NoteProperty -Value "*"
}
elseif ([String]::IsNullOrEmpty($dependency.Projects)) {
$dependency.Projects = '*'
}
if (-not ($dependency.PsObject.Properties.name -eq "release_status")) {
$dependency | Add-Member -Name "release_status" -MemberType NoteProperty -Value "release"
}
if (-not ($dependency.PsObject.Properties.name -eq "branch")) {
$dependency | Add-Member -Name "branch" -MemberType NoteProperty -Value "main"
}
Write-Host "Dependency to projects '$($dependency.Projects)' in $($dependency.Repo)@$($dependency.branch), version $($dependency.version), release status $($dependency.release_status)"
if (-not ($dependency.PsObject.Properties.name -eq "AuthTokenSecret")) {
if ($token) {
Write-Host "Using token as AuthTokenSecret"
}
else {
Write-Host "No token available, will attempt to invoke gh auth status --show-token to get access to repository"
}
$dependency | Add-Member -Name "AuthTokenSecret" -MemberType NoteProperty -Value $token
}
if (-not ($dependency.PsObject.Properties.name -eq "alwaysIncludeApps")) {
$dependency | Add-Member -Name "alwaysIncludeApps" -MemberType NoteProperty -Value @()
}
elseif ($dependency.alwaysIncludeApps -is [string]) {
$dependency.alwaysIncludeApps = $dependency.alwaysIncludeApps.Split(' ')
}
if ($dependency.alwaysIncludeApps) {
Write-Host "Always including apps: $($dependency.alwaysIncludeApps -join ", ")"
}
if ($dependency.release_status -eq "include") {
if ($dependency.Repo -ne "$server_url/$repository") {
OutputWarning "Dependencies with release_status 'include' must be to other projects in the same repository."
}
else {
$dependency.Projects.Split(',') | ForEach-Object {
if ($_ -eq '*') {
OutputWarning "Dependencies to the same repository cannot specify all projects (*)"
}
else {
$depProject = $_
Write-Host "Identified dependency to project $depProject in the same repository"
$dependencyIds = @( @($settings.appDependencies + $settings.testDependencies) | ForEach-Object { $_.id })
$depProjectPath = Join-Path $baseFolder $depProject
$depSettings = ReadSettings -baseFolder $depProjectPath -workflowName "CI/CD"
$depSettings = AnalyzeRepo -settings $depSettings -token $token -baseFolder $baseFolder -project $depProject -includeOnlyAppIds @($dependencyIds + $includeOnlyAppIds + $dependency.alwaysIncludeApps) -doNotIssueWarnings -doNotCheckArtifactSetting -server_url $server_url -repository $repository
Set-Location $projectPath
"appFolders", "testFolders" | ForEach-Object {
$propertyName = $_
Write-Host "Adding folders from $depProject to $_"
$found = $true
$depSettings."$propertyName" | ForEach-Object {
$folder = (Resolve-Path -Path (Join-Path $depProjectPath $_) -Relative).ToLowerInvariant()
if (!$settings."$propertyName".Contains($folder)) {
$settings."$propertyName" += @($folder)
$found = $true
Write-Host "- $folder"
}
}
if (!$found) { Write-Host "- No folders added" }
}
}
}
}
}
}
}
if (!$settings.doNotRunBcptTests -and -not $settings.bcptTestFolders) {
if (!$doNotIssueWarnings) { OutputWarning -message "No performance test apps found in bcptTestFolders in $ALGoSettingsFile" }
$settings.doNotRunBcptTests = $true
}
if (!$settings.doNotRunTests -and -not $settings.testFolders) {
if (!$doNotIssueWarnings) { OutputWarning -message "No test apps found in testFolders in $ALGoSettingsFile" }
$settings.doNotRunTests = $true
}
if (-not $settings.appFolders) {
if (!$doNotIssueWarnings) { OutputWarning -message "No apps found in appFolders in $ALGoSettingsFile" }
}
$settings
}
function Get-ProjectFolders {
Param(
[string] $baseFolder,
[string] $project,
[switch] $includeALGoFolder,
[string[]] $includeOnlyAppIds,
[string] $server_url = $ENV:GITHUB_SERVER_URL,
[string] $repository = $ENV:GITHUB_REPOSITORY,
$token
)
Write-Host "Analyzing project $project"
if ($includeOnlyAppIds) {
$systemAppId, $baseAppId, $applicationAppId | ForEach-Object {
if (!$includeOnlyAppIds.Contains($_)) { $includeOnlyAppIds += @($_) }
}
}
$projectFolders = @()
$projectPath = Join-Path $baseFolder $project
$settings = ReadSettings -baseFolder $projectPath -workflowName "CI/CD"
$settings = AnalyzeRepo -settings $settings -token $token -baseFolder $baseFolder -project $project -includeOnlyAppIds $includeOnlyAppIds -doNotIssueWarnings -doNotCheckArtifactSetting -server_url $server_url -repository $repository
$AlGoFolderArr = @()
if ($includeALGoFolder) { $AlGoFolderArr = @(".AL-Go") }
Set-Location $baseFolder
@($settings.appFolders + $settings.testFolders + $settings.bcptTestFolders + $AlGoFolderArr) | ForEach-Object {
$fullPath = Join-Path $projectPath $_ -Resolve
$relativePath = Resolve-Path -Path $fullPath -Relative
$folder = $relativePath.Substring(2).Replace('\', '/').ToLowerInvariant()
if ($includeOnlyAppIds) {
$appJsonFile = Join-Path $fullPath 'app.json'
if (Test-Path $appJsonFile) {
$appJson = Get-Content -Path $appJsonFile -Encoding UTF8 | ConvertFrom-Json
if ($includeOnlyAppIds.Contains($appJson.Id) -and !$projectFolders.contains($folder)) {
$projectFolders += @($folder)
}
}
}
else {
$projectFolders += @($folder)
}
}
Write-Host "Project $project folders:"
$projectFolders | ForEach-Object { Write-Host "- $_" }
$projectFolders
}
function installModules {
Param(
[String[]] $modules
)
$modules | ForEach-Object {
if (-not (Get-InstalledModule -Name $_ -ErrorAction SilentlyContinue)) {
Write-Host "Installing module $_"
Install-Module $_ -Force | Out-Null
}
}
$modules | ForEach-Object {
Write-Host "Importing module $_"
Import-Module $_ -DisableNameChecking -WarningAction SilentlyContinue | Out-Null
}
}
function CloneIntoNewFolder {
Param(
[string] $actor,
[string] $token,
[string] $branch
)
$baseFolder = Join-Path $env:TEMP ([Guid]::NewGuid().ToString())
New-Item $baseFolder -ItemType Directory | Out-Null
Set-Location $baseFolder
$serverUri = [Uri]::new($env:GITHUB_SERVER_URL)
$serverUrl = "$($serverUri.Scheme)://$($actor):$($token)@$($serverUri.Host)/$($env:GITHUB_REPOSITORY)"
# Environment variables for hub commands
$env:GITHUB_USER = $actor
$env:GITHUB_TOKEN = $token
# Configure git username and email