functions/Match-Vars.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
<#
    .PARAMETER simpleMode
    for better performance. do not perform variable substitution based on self and root
    should still work for simpler scenarios

#>

function get-entry(
    [Parameter(mandatory=$true,Position=1)] $key,
    [Parameter(mandatory=$true,ValueFromPipeline=$true,Position=2)] $map,
    $excludeProperties = @("project"),
    [switch][bool] $simpleMode = $false) 
{
    $root = $map
    $parent = $null
    $entry = $null
    $splits=$key.split(".")
    for($i = 0; $i -lt $splits.length; $i++) {
        $split = $splits[$i]
        $parent = $entry
        if ($i -eq $splits.length-1) {
            $key = $split
            if ($map[$key] -ne $null) { 
               $entry = $map[$key] 
               $vars = @()
           }
           else {     
            foreach($kvp in $map.GetEnumerator()) {
                $pattern = $kvp.key
                $vars = match-varpattern $key "$pattern"
                if ($vars -ne $null) {
                        $entry = $kvp.value   
                        break
                }
            }
           }

           if ($entry -ne $null) {
             #TODO: should we use a deep clone
             $entry2 = $entry.Clone()
             if ($entry2 -is [Hashtable]) {
                $entry2._vars = $vars
             }             
             $entry2 = replace-properties $entry2 -vars $vars -exclude $excludeProperties     
             if (!$simpleMode) {
                 # replace properties based on self values
                 $entry2 = replace-properties $entry2 -vars $map -exclude $excludeProperties  
                 # replace properties based on root values
                 $entry2 = replace-properties $entry2 -vars $root -exclude $excludeProperties  
             }
             return $entry2
           }

           return $entry
        }
        else {
            $entry = $map.$split
        }
        if ($entry -eq $null) {
            break
        }
        if ($entry -ne $null -and $entry.group -ne $null) {
            $isGroup = $true
            break
        }
        $map = $entry
    }    

   
}

function replace-properties($obj, $vars = @{}, [switch][bool]$strict, $exclude = @()) {
    $exclude = @($exclude)
    if ($vars -eq $null) { throw "vars == NULL"}
    if ($obj -is [string]) {
        $replaced = replace-vars -text $obj -vars $vars
        return $replaced
    }
    elseif ($obj -is [System.Collections.IDictionary]) {
        $keys = $obj.keys.Clone()
        $keys = $keys | sort
        foreach($key in $keys) {
            if ($key -notin $exclude) {
                if ($obj[$key] -in $exclude) {
                    continue
                }
                $self = $obj
                try {
                    $obj[$key] = replace-properties $obj[$key] $vars -exclude ($exclude + @($obj))
                }
                finally {
                    $self = $null
                }
                
            }
        }
        return $obj
    }
    elseif ($obj -is [Array]) {
        $obj = $obj.Clone()
         for($i = 0; $i -lt $obj.length; $i++) {
            if ($obj[$i] -in $exclude) {
                continue
            }
            try {
                $obj[$i] = replace-properties $obj[$i] $vars -exclude ($exclude + @($obj))
            }
            finally {
            }
        }
    }    
    elseif ($strict) {
        throw "unsupported object"
       
    }

    return $obj
}

#TODO: support multiple matches per line
function _replace-varline ([Parameter(Mandatory=$true)]$text, $vars = @{}) {
    $r = $text
    if ($vars -eq $null) { throw "vars == NULL"}

    do {
        #each replace may insert a new variable reference in the string, so we need to iterate again
        $replaced = $false
        foreach($kvp in $vars.GetEnumerator()) {
            $name = $kvp.key
            $val = $kvp.value

            if ($r -match "\{$name\}") {
                $r = $r -replace "\{$name\}",$val
                $replaced = $true
                break
            }
            # support also same placeholder as in template match
            elseif ($r -match "__$($name)__") {
                $r = $r -replace "__$($name)__",$val
                $replaced = $true
                break
            }
            elseif ($r -match "_$($name)_") {
                $r = $r -replace "_$($name)_",$val
                $replaced = $true
                break
            }
        }    
    } while ($replaced)

    return $r    
}

#TODO: support multiple matches per line
function _replace-varauto([Parameter(Mandatory=$true)]$__text)  {
    
    do {
    #each replace may insert a new variable reference in the string, so we need to iterate again
    $__replaced = $false
    $__matches = [System.Text.RegularExpressions.Regex]::Matches($__text, "\{(\?{0,1}[a-zA-Z0-9_.:]+?)\}")
    foreach($__match in $__matches) {
        if ($__match.Success) {
            $__name = $__Match.Groups[1].Value
            $__orgname = $__name
            $__defaultifnull = $false
            if ($__name.startswith("?")) {
                $__name= $__name.substring(1)
                $__defaultifnull = $true
            }
            $__varpath = $__name 
            $__splits = $__name.split(".")
            $__splitstart = 1
            if (!($__varpath -match ":")) {
                    $__varpath = "variable:" + $__splits[0]                 
            }
            $__val = $null
            # this is a fragile thing. the module itself may define local vars that collide with map vars
            if (test-path "$__varpath") {
                $__val = (get-item $__varpath).Value
                for($__i = $__splitstart; $__i -lt $__splits.length; $__i++) {
                    $__s = $__splits[$__i] 
                    $__val = $__val.$__s
                }  
            }
            elseif (test-path "variable:self") {
                $__selftmp = (get-item "variable:self").Value
                $__val = $__selftmp
                foreach($__s in $__splits) {
                    $__val = $__val.$__s
                }            
            }
            if ($__val -ne $null) {
                    $__text = $__text -replace "\{$([System.Text.RegularExpressions.Regex]::Escape($__orgname))\}",$__val
                    $__replaced = $true
            } 
            elseif ($__defaultifnull) {
                $__text = $__text -replace "\{$([System.Text.RegularExpressions.Regex]::Escape($__orgname))\}",""
                $__replaced = $true                
            }
        }
    }
    }
    while ($__replaced)
    return $__text
}

function convert-vars([Parameter(Mandatory=$true)]$text, $vars = @{}, [switch][bool]$noauto = $false) {
    $text = @($text) | % { _replace-varline $_ $vars }

    $originalself = $self

    # is this necessary if we're doing replace-properties twice?
    if ($originalself -eq $null) {
        $self = $vars
    }
    if (!$noauto) {
        $text = @($text) | % { _replace-varauto $_ }
    }

    
    $m = [System.Text.RegularExpressions.Regex]::Matches($text, "\{(\?{0,1}[a-zA-Z0-9_.:]+?)\}")
    if ($m.count -gt 0) {
        write-warning "missing variable '$($m[0].Groups[1].Value)'"
    }
    return $text
}

function get-vardef ($text) {
    $result = $null
    $m = [System.Text.RegularExpressions.Regex]::Matches($text, "__([a-zA-Z]+)__");
    if ($m -ne $null) {
        $result = $m | % {
            $_.Groups[1].Value
        }
        return $result
    }

    $m = [System.Text.RegularExpressions.Regex]::Matches($text, "_([a-zA-Z]+)_");
    if ($m -ne $null) {
        $result = $m | % {
            $_.Groups[1].Value
        }
        return $result
    }

    return $null
}

function match-varpattern ($text, $pattern) {
    $result = $null
    $vars = @(get-vardef $pattern)
    if ($vars -eq $null) { return $null }
    $regex = $pattern -replace "__[a-zA-Z]+__","([a-zA-Z0-9]*)"    
    $regex = $regex -replace "_[a-zA-Z]+_","([a-zA-Z0-9]*)"    
    $m = [System.Text.RegularExpressions.Regex]::Matches($text, "^$regex`$");
    
    if ($m -ne $null) {
        $result = $m | % {
            for($i = 1; $i -lt $_.Groups.Count; $i++) {
                $val = $_.Groups[$i].Value
                $name = $vars[$i-1]
                return @{ $name = $val }
            }
        }
    }

    return $result
}

new-alias Replace-Vars Convert-Vars -force