-
Notifications
You must be signed in to change notification settings - Fork 25
/
tasks.ps1
753 lines (628 loc) · 22.5 KB
/
tasks.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
# suppress warnings that we need to use
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidOverwritingBuiltInCmdlets', ""
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingWriteHost', ""
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingInvokeExpression', ""
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingPositionalParameters', ""
)]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidGlobalVars', ""
)]
param()
$ErrorActionPreference = "Stop"
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseDeclaredVarsMoreThanAssignments', "Internal PS variable"
)]
$PSNativeCommandUseErrorActionPreference = $true
function _usage ($_fdp = 1) {
Write-Host "usage:"
Write-Host " list : list the tasks.json labels defined"
Write-Host " desc <task_label> : describe the task <task_label>"
Write-Host " desc <task_index> : describe the task <task_index>"
Write-Host " run <task_label> : run the task <task_label>"
Write-Host " run <task_index> : run the task <task_index>"
Write-Host " run-nodeps <task_label> : run the tasks without dependencies <task_label>"
if ($_fdp -eq 0) {
Write-Host -ForegroundColor Yellow ""
Write-Host -ForegroundColor Yellow "⚠️ :: WARNING :: ⚠️"
Write-Host -ForegroundColor Yellow "This script depends on tasks.json and settings.json"
Write-Host -ForegroundColor Yellow "These files need to be in the same directory as this script."
Write-Host -ForegroundColor Yellow ""
}
exit 0
}
# settings
$_overrideEnv = $true;
$_debug = $false;
$_gitlab_ci = $false
if ($Env:GITLAB_CI -eq $true) {
Write-Host "ℹ️ :: GITLAB_CI :: ℹ️"
# for gitlab-ci we need to set the docker host
$Env:DOCKER_HOST = "tcp://docker:2375"
$_gitlab_ci = $true
}
if ($env:TASKS_DEBUG -eq $true) {
$_debug = $true;
}
if ($env:TASKS_OVERRIDE_ENV -eq $false) {
$_overrideEnv = $false;
}
if ($env:TASKS_USE_PWSH_INSTEAD_BASH -eq $true) {
$_usePwshInsteadBash = $true;
} else {
$_usePwshInsteadBash = $false;
}
if (($null -eq $env:TASKS_CUSTOM_SETTINGS_JSON) -or ($env:TASKS_CUSTOM_SETTINGS_JSON -eq "settings.json")) {
$env:TASKS_CUSTOM_SETTINGS_JSON = "settings.json"
} else {
Write-Host "ℹ️ :: CUSTOM SETTINGS :: ℹ️"
Write-Host "Using custom settings file: $env:TASKS_CUSTOM_SETTINGS_JSON"
}
try {
$tasksFileContent = Get-Content $PSScriptRoot/tasks.json
$settingsFileContent = Get-Content $PSScriptRoot/$env:TASKS_CUSTOM_SETTINGS_JSON
$json = $tasksFileContent | ConvertFrom-Json
$settings = $settingsFileContent | ConvertFrom-Json
$inputs = $json.inputs
$inputValues = @{}
$cliInputs = [System.Collections.ArrayList]@()
$runDeps = $true;
} catch {
_usage 0
}
function settingsToGlobal () {
foreach ($set in $settings | Get-Member -MemberType Properties) {
if (-not (Test-Path "variable:Global:$($set.Name)")) {
New-Variable `
-Scope Global `
-Name "config:$($set.Name)" -Value $settings.($set.Name)
} else {
Set-Variable `
-Scope Global `
-Name "config:$($set.Name)" -Value $settings.($set.Name)
}
}
}
function write-error () {
Write-Host -ForegroundColor Red `
$args[0]
exit $args[1]
}
function getTasksLabels () {
$labels = [System.Collections.ArrayList]@()
for ($i = 0; $i -le $json.tasks.length; $i++) {
[void]$labels.Add($json.tasks[$i].label)
}
return $labels
}
function listTasksLabel () {
$_noIndex = $false
if ($null -ne $args[0]) {
if ($args[0] -eq "--no-index") {
$_noIndex = $true
}
}
for ($i = 0; $i -le $json.tasks.length; $i++) {
if ($null -ne $json.tasks[$i].label) {
if ($_noIndex -eq $false) {
Write-Host -NoNewline "$($i + 1).`t"
}
Write-Host $json.tasks[$i].label
}
}
}
function checkInput () {
$ret = [System.Collections.ArrayList]@()
foreach ($arg in $args[0]) {
if (-not $arg.Contains("`${input:")) {
[void]$ret.Add($arg)
} else {
$maches = ($arg |
Select-String `
-Pattern "(?<=\`${input:).*?(?=\s*})" `
-AllMatches
).Matches
foreach ($matchValue in $maches) {
$inputObj = $null
foreach ($inp in $inputs) {
if ($inp.id -eq $matchValue.Value) {
$inputObj = $inp
}
}
$fromUser = $null
if ($inputValues.ContainsKey($matchValue.Value)) {
$fromUser = $inputValues[$matchValue.Value]
} else {
$desc = $inputObj.description
$default = $inputObj.default
if ($cliInputs.Count -gt 0) {
$fromUser = $cliInputs[0]
$cliInputs.RemoveAt(0)
}
# cli input is nothing
if ($null -eq $fromUser) {
if ($inputObj.password -eq $true) {
$fromUser = Read-Host `
-AsSecureString `
-Prompt "$desc [***]"
# TODO: so much security wow
$fromUser = ConvertFrom-SecureString `
-SecureString $fromUser `
-AsPlainText
} else {
$fromUser = Read-Host `
-Prompt "$desc [$default]"
}
}
if ($fromUser -eq [String]::Empty) {
$fromUser = $default
}
$inputValues.Add($matchValue.Value, $fromUser)
}
$matchValue = $matchValue.Value
$arg = $arg.Replace("`${input:${matchValue}}", $fromUser)
}
[void]$ret.Add($arg)
}
}
return $ret
}
# TODO: refactor to be an generic prefix check
function checkTorizonInputs ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
if ($item.Contains("`${command:torizon_")) {
$maches = ($item |
Select-String `
-Pattern "(?<=\`${command:torizon_).*?(?=\s*})" `
-AllMatches
).Matches
foreach ($matchValue in $maches) {
$matchValue = $matchValue.Value
$item = $item.Replace(
"`${command:torizon_${matchValue}}",
"`${config:torizon_${matchValue}}"
)
}
}
[void]$ret.Add($item)
}
return $ret
}
function checkDockerInputs ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
if ($item.Contains("`${command:docker_")) {
$maches = ($item |
Select-String `
-Pattern "(?<=\`${command:docker_).*?(?=\s*})" `
-AllMatches
).Matches
foreach ($matchValue in $maches) {
$matchValue = $matchValue.Value
$item = $item.Replace(
"`${command:docker_${matchValue}}",
"`${config:docker_${matchValue}}"
)
}
}
[void]$ret.Add($item)
}
return $ret
}
function checkTCBInputs ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
if ($item.Contains("`${command:tcb")) {
# this is re-implementation from the TCB extension
if ($item.Contains("tcb.getNextPackageVersion")) {
$_ret = (
./.conf/torizonIO.ps1 `
package latest version ${global:config:tcb.packageName}
)
$_next = [System.Int32]::Parse($_ret) +1
if ($_debug) {
Write-Host -ForegroundColor Green `
"Next package version: $_next"
}
$item = $item.Replace(
"`${command:tcb.getNextPackageVersion}",
"$_next"
)
}
# this is re-implementation from the TCB extension
elseif ($item.Contains("tcb.outputTEZIFolder")) {
# load the tcbuild.yaml
$_tcbuild = Get-Content `
$(Join-Path $Global:workspaceFolder "tcbuild.yaml") -Raw `
| out-string
# check if the yaml module is installed
Write-Host "Importing powershell-yaml ..."
if (-not (Get-Module -ListAvailable -Name "powershell-yaml")) {
Write-Host -ForegroundColor Yellow "Installing powershell-yaml ..."
Install-Module -Name "powershell-yaml" -Confirm:$false -Force
}
$_yamlObj = ConvertFrom-Yaml $_tcbuild -AllDocuments -Ordered
write-host $($_yamlObj.GetType())
if (
($null -ne $_yamlObj) -and
($null -ne $_yamlObj.output) -and
($null -ne $_yamlObj.output."easy-installer") -and
($null -ne $_yamlObj.output."easy-installer".local)
) {
$item = $item.Replace(
"`${command:tcb.outputTEZIFolder}",
$_yamlObj.output."easy-installer".local
)
} else {
throw "Error reading tcbuild.yaml, check if there is an output.easy.installer.local"
}
}
$maches = ($item |
Select-String `
-Pattern "(?<=\`${command:tcb.).*?(?=\s*})" `
-AllMatches
).Matches
foreach ($matchValue in $maches) {
$matchValue = $matchValue.Value
$item = $item.Replace(
"`${command:tcb.${matchValue}}",
"`${config:tcb.${matchValue}}"
)
}
}
[void]$ret.Add($item)
}
return $ret
}
# check if the string contains special characters
function _containsSpecialChars ([String] $str) {
$ret = $false
if (
# do not match pipes like | >
$str -match "[^a-zA-Z0-9\.\-_|>]"
) {
$ret = $true
}
return $ret
}
function scapeArgs ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
# for now only scaping double quotes
foreach ($item in $list) {
if ($item.Contains("`"")) {
$item = $item.Replace("`"", "```"")
}
[void]$ret.Add($item)
}
return $ret
}
function checkConfig ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
# TODO: Add variable expand recursive
if ($item.Contains("config:")) {
$item = $item.Replace("config:", "global:config:")
$value = Invoke-Expression "echo `"$item`""
if ($null -ne $value -and $value.Contains("`${workspaceFolder")) {
$item = $value
}
}
[void]$ret.Add($item)
}
return $ret
}
function checkLongArgs ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
if ($item.Contains(" ")) {
$item = "'$item'"
}
[void]$ret.Add($item)
}
return $ret
}
##
# If the user is using bash as default shell, we need to scape the $ special
# characters, because powershell will try to expand the variables before it
# reach the bash shell
##
function bashVariables ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
if ($item.Contains("$")) {
# if $env
# if ${}
# if $global
# then we continue because these are meant to be expanded
if (
$item.Contains("`$global:") -or
$item.Contains("`$env:") -or
$item.Contains("`${")
) {
[void]$ret.Add($item)
continue
}
# ok, we can scape it
$item = $item.Replace("`$", "``$")
[void]$ret.Add($item)
} else {
[void]$ret.Add($item)
}
}
return $ret
}
function quotingSpecialChars ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
$_specialChar = _containsSpecialChars($item)
$_space = $item.Contains(" ")
if ($_specialChar -and -not $_space) {
$item = "'$item'"
}
[void]$ret.Add($item)
}
return $ret
}
function checkWorkspaceFolder ([System.Collections.ArrayList] $list) {
$ret = [System.Collections.ArrayList]@()
foreach ($item in $list) {
# TODO: Add variable expand recursive
if ($item.Contains("workspaceFolder")) {
$item = $item.Replace("workspaceFolder", "global:workspaceFolder")
$value = Invoke-Expression "echo $item"
if ($value.Contains("`${workspaceFolder")) {
$item = $value
}
}
[void]$ret.Add($item)
}
return $ret
}
function taskArgumentExecute ($label, [ScriptBlock]$fnExec, $message) {
if ($null -eq $label -or $label -eq [String]::Empty) {
write-error $message 10
} else {
$taskLabel = $label
if ($taskLabel -match "^\d+$") {
Invoke-Command -ScriptBlock $fnExec `
-ArgumentList $json.tasks[[int]::Parse($taskLabel) -1].label
} elseif ((getTasksLabels).Contains($taskLabel)) {
Invoke-Command -ScriptBlock $fnExec `
-ArgumentList $taskLabel
} else {
write-error "Undefined task <$taskLabel>" 10
}
}
}
function descTask () {
for ($i = 0; $i -le $json.tasks.length; $i++) {
if ($json.tasks[$i].label -eq $args[0]) {
$task = $json.tasks[$i]
$task | ConvertTo-Json
}
}
}
function _parseEnvs () {
$env = $args[0]
$task = $args[1]
$value = $task.options.env
| Select-Object -ExpandProperty $env
$expValue = checkWorkspaceFolder($value)
$expValue = checkTorizonInputs($expValue)
$expValue = checkDockerInputs($expValue)
$expValue = checkTCBInputs($expValue)
$expValue = checkInput($expValue)
$expValue = checkConfig($expValue)
$expValue = bashVariables($expValue)
$expValue = $expValue.ToString()
$_env = Invoke-Expression "echo `"$expValue`""
if ($_debug -eq $true) {
Write-Host -ForegroundColor Yellow `
"Env: $env=$expValue"
Write-Host -ForegroundColor Yellow `
"Parsed Env: $env=$_env"
}
return $_env
}
function _replaceDockerHost () {
$value = $args[0]
if ($value -match "DOCKER_HOST=") {
$value = $value.Replace("DOCKER_HOST=", "DOCKER_HOST=tcp://docker:2375")
}
return $value
}
function runTask () {
for ($i = 0; $i -le $json.tasks.length; $i++) {
if ($json.tasks[$i].label -eq $args[0]) {
$task = $json.tasks[$i]
$taskCmd = $task.command
$taskArgs = scapeArgs($task.args)
$taskArgs = checkWorkspaceFolder($taskArgs)
$taskArgs = checkTorizonInputs($taskArgs)
$taskArgs = checkDockerInputs($taskArgs)
$taskArgs = checkTCBInputs($taskArgs)
$taskArgs = checkInput($taskArgs)
$taskArgs = checkConfig($taskArgs)
$taskArgs = checkLongArgs($taskArgs)
$taskArgs = bashVariables($taskArgs)
$taskArgs = quotingSpecialChars($taskArgs)
$taskDepends = $task.dependsOn
$taskEnv = $task.options.env
$taskCwd = $task.options.cwd
$isBackground = ""
if ($task.isBackground -eq $true) {
$isBackground = " &"
}
# FIXME: if using powershell instead bash the background will start
# a new job, this is was not been well tested
# is gitlab ci
if ($_gitlab_ci -eq $true) {
$taskCmd = _replaceDockerHost($taskCmd)
}
# inject env
if ($null -ne $taskEnv) {
$envs = $taskEnv
| get-member -MemberType NoteProperty
| Select-Object -ExpandProperty Name
foreach ($env in $envs) {
if ($_overrideEnv) {
$_env = _parseEnvs $env $task
[System.Environment]::SetEnvironmentVariable(
$env, $_env
)
} else {
if (
$null -eq
[System.Environment]::GetEnvironmentVariable($env)
) {
$_env = _parseEnvs $env $task
[System.Environment]::SetEnvironmentVariable(
$env, $_env
)
}
}
}
}
# run dependencies
if ($runDeps -eq $true) {
for ($j = 0; $j -lt $taskDepends.Count; $j++) {
runTask $taskDepends[$j]
}
}
Write-Host -ForegroundColor Green `
"> Executing task: $($json.tasks[$i].label) <"
# we need to change dir if we are setting cwd
if ($null -ne $taskCwd) {
# store the current location
$_cwd = Get-Location
# we use invoke-expression because this way it expand the
# variables automatically
Invoke-Expression "Set-Location $taskCwd"
}
# parse the variables
$_cmd = Invoke-Expression "echo `"$taskCmd $taskArgs $isBackground`""
if ($env:TASKS_DEBUG -eq $true) {
Write-Host -ForegroundColor Yellow `
"Command: $taskCmd"
Write-Host -ForegroundColor Yellow `
"Args: $taskArgs"
Write-Host -ForegroundColor Yellow `
"Parsed Command: $_cmd"
}
# all to global
# we are spawning a new process, so we need to set all the envs
# as global, so the new process can see it
# this is useful when the user set bash variables
$_ALLENV = $(Get-ChildItem env:)
foreach ($_env in $_ALLENV) {
try {
# set it as a $Global:
Set-Variable `
-Scope Global `
-Name $_env.Name -Value $_env.Value
} catch {
# ignore
# some variables are not overwrite
}
}
# execute the task
if ($task.type -eq "shell") {
if ($_usePwshInsteadBash -eq $false) {
# use bash as default
# TODO: be explicit about bash as default on documentation
Invoke-Expression "bash -c `"$_cmd`""
} else {
Invoke-Expression "pwsh -nop -c `"$_cmd`""
}
} else {
Invoke-Expression $_cmd
}
$exitCode = $LASTEXITCODE
# go back to the origin location
if ($null -ne $taskCwd) {
# restore the current location
Set-Location $_cwd
}
# abort we had an error
if ($exitCode -ne 0) {
Write-Host -ForegroundColor Red `
"> TASK $($json.tasks[$i].label) exited with error code $($exitCode) <"
exit $exitCode
}
}
}
}
function getCliInputs () {
$argsS = $args[0]
# args[0] command / args[1] task name
for ($i = 2; $i -lt $argsS.Length; $i++) {
# inputs
[void]$cliInputs.Add($argsS[$i])
}
}
# main()
# set the relative workspaceFolder (following the pattern that VS Code expects)
if (
($null -eq $env:APOLLOX_WORKSPACE) -and
($env:APOLLOX_CONTAINER -ne 1) -and
(-not $env:GITHUB_WORKSPACE)
) {
$Global:workspaceFolder = Join-Path $PSScriptRoot ..
} elseif (
$env:GITHUB_WORKSPACE
) {
# If running in a github action, this ENV is set automatically,
# github actions sandboxes runners by re-writing their ABS path,
# so when we do a docker-in-docker build, the mount point for workdir is not found.
# This sets the ABS path from a file called abs-path
$Global:workspaceFolder = Join-Path $PSScriptRoot ..
$env:HOST_GITHUB_WORKSPACE = Get-Content -Path abs-path -ReadCount 1
} else {
$Global:workspaceFolder = $env:APOLLOX_WORKSPACE
}
settingsToGlobal
# edge case for config:docker_password
if ( $null -ne $env:DOCKER_PSSWD ) {
$Global:config:docker_password = $env:DOCKER_PSSWD
}
try {
switch ($args[0]) {
"list" {
listTasksLabel $args[1]
}
"desc" {
taskArgumentExecute `
$args[1] ${function:descTask} "Argument expected desc <task_label>"
}
"run" {
getCliInputs $args
taskArgumentExecute `
$args[1] ${function:runTask} "Argument expected run <task_label>"
}
"run-nodeps" {
$runDeps = $false;
getCliInputs $args
taskArgumentExecute `
$args[1] ${function:runTask} "Argument expected run <task_label>"
}
Default {
_usage
}
}
} catch {
Write-Host $_.Exception.Message -Foreground "Red"
Write-Host ""
$lines = $_.ScriptStackTrace.Split("`n")
foreach ($line in $lines) {
Write-Host "`t$line" -Foreground "DarkGray"
}
Write-Host ""
exit 500
}