internal/configurationschemata/metajson.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
Register-PSFConfigSchema -Name MetaJson -Schema {
    param (
        [string]
        $Resource,
        
        [System.Collections.Hashtable]
        $Settings
    )
    
    Write-PSFMessage -String 'Configuration.Schema.MetaJson.ProcessResource' -StringValues $Resource -ModuleName PSFramework
    
    #region Converting parameters
    $Peek = $Settings["Peek"]
    $ExcludeFilter = $Settings["ExcludeFilter"]
    $IncludeFilter = $Settings["IncludeFilter"]
    $AllowDelete = $Settings["AllowDelete"]
    $script:EnableException = $Settings["EnableException"]
    $script:cmdlet = $Settings["Cmdlet"]
    Set-Location -Path $Settings["Path"]
    $PassThru = $Settings["PassThru"]
    #endregion Converting parameters
    
    #region Utility Function
    function Read-V1Node
    {
        [CmdletBinding()]
        param (
            $NodeData,
            
            [string]
            $Path,
            
            [Hashtable]
            $Result,
            
            [string]
            $Type,
            
            [Hashtable]
            $Settings
        )
        
        Write-PSFMessage -String 'Configuration.Schema.MetaJson.ProcessFile' -StringValues $Path -ModuleName PSFramework
        
        $basePath = switch ($Type) {
            'file' { Split-Path -Path $Path }
            'weblink' { $Path -replace '/[^/]+?$' }
            default { $null }
        }
        
        if ($NodeData.ModuleName) { $moduleName = "{0}." -f $NodeData.ModuleName }
        else { $moduleName = "" }
        
        #region Import Resources
        foreach ($property in $NodeData.Static.PSObject.Properties)
        {
            $Result["$($moduleName)$($property.Name)"] = $property.Value
        }
        foreach ($property in $NodeData.Object.PSObject.Properties)
        {
            $Result["$($moduleName)$($property.Name)"] = $property.Value | ConvertFrom-PSFClixml
        }
        foreach ($property in $NodeData.Dynamic.PSObject.Properties)
        {
            $Result["$($moduleName)$(Resolve-V1String -String $property.Name)"] = Resolve-V1String -String $property.Value
        }
        foreach ($property in $NodeData.Tree.PSObject.Properties) {
            Resolve-V1Tree -Property $property -Result $Result -BaseElement @()
        }
        foreach ($property in $NodeData.DynamicTree.PSObject.Properties) {
            Resolve-V1Tree -Property $property -Result $Result -BaseElement @() -Dynamic $true
        }
        #endregion Import Resources
        
        #region Import included / linked configuration files
        :includes foreach ($include in $NodeData.Include)
        {
            $resolvedInclude = Resolve-V1String -String $include
            $uri = [uri]$resolvedInclude
            
            # Skip relative paths if we do not have a base path to place it relative to
            if (-not $uri.IsAbsoluteUri -and -not $basePath) { continue }
            #region Calculate the new include path
            if ($uri.IsAbsoluteUri) { $includePath = $resolvedInclude }
            else {
                $includePath = switch ($Type) {
                    'file'
                    {
                        $joinedPath = Join-Path -Path $basePath -ChildPath ($resolvedInclude -replace '^\.\\', '\')
                        try { Resolve-PSFPath -Path $joinedPath -Provider FileSystem -SingleItem }
                        catch { Stop-PSFFunction -String 'Configuration.Schema.MetaJson.ResolveFile' -StringValues $joinedPath -EnableException $script:EnableException -ModuleName PSFramework -ErrorRecord $_ -Continue -ContinueLabel includes -Cmdlet $script:cmdlet }
                    }
                    'weblink'
                    {
                        $newPath = $basePath
                        $relParts = $resolvedInclude -split "/"
                        foreach ($part in $relParts) {
                            if ($part -eq '..') { $newPath = $newPath -replace '/[^/]+$' }
                            else { $newPath = $newPath, $part -join '/' }
                        }
                        $newPath
                    }
                }
            }
            #endregion Calculate the new include path
            
            $newSettings = $Settings | ConvertTo-PSFHashtable -Include ExcludeFilter, IncludeFilter
            try { $configData = Import-PSFConfig -Path $includePath -Peek @newSettings -Schema MetaJson -EnableException -ErrorAction Stop }
            catch { Stop-PSFFunction -String 'Configuration.Schema.MetaJson.ExecuteInclude.Error' -StringValues $includePath -EnableException $script:EnableException -ModuleName PSFramework -ErrorRecord $_ -Continue -ContinueLabel includes -Cmdlet $script:cmdlet }
            foreach ($configDatum in $configData) {
                $Result[$configDatum.FullName] = $configDatum.Value
            }
        }
        #endregion Import included / linked configuration files
        
        $Result
    }
    
    function Resolve-V1String
    {
    <#
        .SYNOPSIS
            Resolves a string by inserting placeholders for environment variables.
         
        .DESCRIPTION
            Resolves a string by inserting placeholders for environment variables.
         
        .PARAMETER String
            The string to resolve.
         
        .EXAMPLE
            PS C:\> Resolve-V1String -String '.\%COMPUTERNAME%\config.json'
         
            Resolves the specified string, inserting the local computername for %COMPUTERNAME%.
    #>

        [CmdletBinding()]
        param (
            $String
        )
        if ($String -isnot [string]) { return $String }
        
        $scriptblock = {
            param (
                $Match
            )
            
            $script:envData[$Match.Value]
        }
        
        [regex]::Replace($String, $script:envDataNamesRGX, $scriptblock)
    }
    
    function Resolve-V1Tree {
        [CmdletBinding()]
        param (
            $Property,
            
            [Hashtable]
            $Result,
            
            [bool]
            $Dynamic,
            
            [AllowEmptyCollection()]
            [string[]]
            $BaseElement
        )
        
        if ($Property.TypeNameOfValue -notin 'System.Management.Automation.PSCustomObject', 'System.Collections.Hashtable') {
            $name = (@($BaseElement) + @($Property.Name)) -join "."
            if ($Dynamic) { $Result[(Resolve-V1String -String $name)] = Resolve-V1String -String $Property.Value }
            else { $Result[$name] = $Property.Value }
            return
        }
        
        $value = $Property.Value
        if ($value -is [System.Collections.Hashtable]) { $value = [pscustomobject]$value }
        
        if ($value.'!Condition') {
            $conditionSet = $null
            if ($value.'!ConditionSet') {
                $module, $name = $value.'!ConditionSet' -split ' ', 2
                $conditionSet = Get-PSFFilterConditionSet -Module $module -Name $name | Select-Object -First 1
            }
            else {
                $conditionSet = Get-PSFFilterConditionSet -Module PSFramework -Name Environment
            }
            if (-not $conditionSet) { throw "Unable to resolve Condition Set: $($value.'!ConditionSet')" }
            $filter = New-PSFFilter -Expression $value.'!Condition' -ConditionSet $conditionSet
            if (-not $filter.Evaluate()) { return }
        }
        
        foreach ($propertyObject in $value.PSObject.Properties) {
            if ($propertyObject.Name -eq '!Condition') { continue }
            if ($propertyObject.Name -eq '!ConditionSet') { continue }
            
            if ($value.'!Condition') { Resolve-V1Tree -Property $propertyObject -Result $Result -Dynamic $Dynamic -BaseElement $BaseElement }
            else { Resolve-V1Tree -Property $propertyObject -Result $Result -Dynamic $Dynamic -BaseElement (@($BaseElement) + @($Property.Name)) }
        }
    }
    #endregion Utility Function
    
    #region Utility Computation
    $script:envData = @{ }
    foreach ($envItem in (Get-ChildItem env:\))
    {
        $script:envData["%$($envItem.Name)%"] = $envItem.Value
    }
    $script:envDataNamesRGX = $script:envData.Keys -join '|'
    #endregion Utility Computation
    
    #region Accessing Content
    try {
        $null = Resolve-PSFPath -Path $Resource -Provider FileSystem -SingleItem
        $resourceType = 'File'
    }
    catch {
        if ($Resource -match '^https{0,1}://') { $resourceType = 'weblink' }
        else { $resourceType = 'Json' }
    }
    switch ($resourceType) {
        #region Weblink
        'weblink'
        {
            try { $importData = Invoke-WebRequest -Uri $Resource -UseBasicParsing -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop }
            catch {
                Stop-PSFFunction -String 'Configuration.Schema.MetaJson.WebError' -StringValues $Resource -ModuleName PSFramework -FunctionName 'Schema: MetaJson' -EnableException $EnableException -ErrorRecord $_ -Cmdlet $script:cmdlet
                return
            }
            $resolvedPath = $Resource
        }
        #endregion Weblink
        #region File
        'file'
        {
            try { $resolvedPath = Resolve-PSFPath -Path $Resource -Provider FileSystem -SingleItem }
            catch {
                Stop-PSFFunction -String 'Configuration.Schema.MetaJson.ResolveFile' -StringValues $Resource -ModuleName PSFramework -FunctionName 'Schema: MetaJson' -EnableException $EnableException -ErrorRecord $_ -Cmdlet $script:cmdlet
                return
            }
            
            switch -regex ($resolvedPath) {
                '\.psd1$'
                {
                    try { $importData = [pscustomobject](Import-PSFPowerShellDataFile -Path $resolvedPath -ErrorAction Stop) }
                    catch {
                        Stop-PSFFunction -String 'Configuration.Schema.MetaJson.InvalidPsd1' -StringValues $Resource -ModuleName PSFramework -FunctionName 'Schema: MetaJson' -EnableException $EnableException -ErrorRecord $_ -Cmdlet $script:cmdlet
                        return
                    }
                    if ($importData.Static -is [hashtable]) { $importData.Static = [pscustomobject]$importData.Static }
                    if ($importData.Object -is [hashtable]) { $importData.Object = [pscustomobject]$importData.Object }
                    if ($importData.Dynamic -is [hashtable]) { $importData.Dynamic = [pscustomobject]$importData.Dynamic }
                    if ($importData.Tree -is [hashtable]) { $importData.Tree = [pscustomobject]$importData.Tree }
                    if ($importData.DynamicTree -is [hashtable]) { $importData.DynamicTree = [pscustomobject]$importData.DynamicTree }
                }
                default
                {
                    try { $importData = Get-Content -Path $resolvedPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop }
                    catch {
                        Stop-PSFFunction -String 'Configuration.Schema.MetaJson.InvalidJson' -StringValues $Resource -ModuleName PSFramework -FunctionName 'Schema: MetaJson' -EnableException $EnableException -ErrorRecord $_ -Cmdlet $script:cmdlet
                        return
                    }
                }
            }
        }
        #endregion File
        #region Straight Json
        default
        {
            try {
                $importData = $Resource | ConvertFrom-Json -ErrorAction Stop
                $resolvedPath = ''
            }
            catch {
                Stop-PSFFunction -String 'Configuration.Schema.MetaJson.InvalidJson' -StringValues $Resource -ModuleName PSFramework -FunctionName 'Schema: MetaJson' -EnableException $EnableException -ErrorRecord $_ -Cmdlet $script:cmdlet
                return
            }
        }
        #endregion Straight Json
    }
    #endregion Accessing Content
    
    switch ($importData.Version)
    {
        1
        {
            $configurationHash = Read-V1Node -NodeData $importData -Path $resolvedPath -Type $resourceType -Result @{ } -Settings $Settings
            $configurationItems = $configurationHash.Keys | ForEach-Object {
                [pscustomobject]@{
                    FullName = $_
                    Value = $configurationHash[$_]
                }
            }
            
            foreach ($configItem in $configurationItems)
            {
                if ($ExcludeFilter | Where-Object { $configItem.FullName -like $_ }) { continue }
                if ($IncludeFilter -and -not ($IncludeFilter | Where-Object { $configItem.FullName -like $_ })) { continue }
                if ($Peek)
                {
                    $configItem
                    continue
                }
                
                Set-PSFConfig -FullName $configItem.FullName -Value $configItem.Value -AllowDelete:$AllowDelete -PassThru:$PassThru
            }
        }
        default
        {
            Stop-PSFFunction -String 'Configuration.Schema.MetaJson.UnknownVersion' -StringValues $Resource, $importData.Version -ModuleName PSFramework -FunctionName 'Schema: MetaJson' -EnableException $EnableException -Cmdlet $script:cmdlet
            return
        }
    }
}