scripts/Invoke-Task.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
function Invoke-Task {
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)]
        [hashtable]$task,

        [Parameter(Mandatory = $false)]
        [hashtable]$config = (Coalesce (Peek-Config), @{})
    )
    process {
        $caption = "Invoke task: $($task.name)"

        try {
            $caption | f-log-info

            if (-not (Invoke-Expression $task.when)) {
                "`t`tBypassed because of: [$($task.when)] = $(Invoke-Expression $task.when)" | f-log-info
                return;
            }

            Push-Location (Build-Path "$($task.work_dir)" $config)

            foreach ($step in $task.steps) {
                (Peek-Context).caught = $false
                $step | Invoke-Step -work_dir $task.work_dir
            }
        } catch {
            if (-not (Peek-Context).caught) {
                # if it was not thrown in execution context, it should be logged
                $_ | f-log-err
            }
            if ($task.on_error -eq 'throw') {
                throw $_
            }
        }
        finally {
            Pop-Location
            if ($config.attributes.pwshake_log_to_json) {
                (Peek-Context).json_sb.ToString() | f-json | Add-Content -Path "$($config.attributes.pwshake_log_path).json" -Encoding UTF8
                (Peek-Context).json_sb.Clear() | Out-Null
            }
        }
    }
}