Repository navigation
Expand file tree
/
Copy pathInstallerBridge.psm1
More file actions
298 lines (258 loc) · 10.6 KB
/
Copy pathInstallerBridge.psm1
File metadata and controls
298 lines (258 loc) · 10.6 KB
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
# Apply default function parameters
if ($DumplingsDefaultParameterValues) { $PSDefaultParameterValues = $DumplingsDefaultParameterValues }
# Force stop on error
$ErrorActionPreference = 'Stop'
function Get-InstallerBridgePowerShell {
<#
.SYNOPSIS
Resolve the PowerShell host used to invoke external installer parser modules
#>
[OutputType([System.IO.FileInfo])]
param ()
$Candidates = @(
(Join-Path $PSHOME 'pwsh.exe'),
(Join-Path $PSHOME 'pwsh')
)
foreach ($Candidate in $Candidates) {
if (-not [string]::IsNullOrWhiteSpace($Candidate) -and (Test-Path -Path $Candidate)) {
return Get-Item -Path $Candidate -Force
}
}
if ($Command = Get-Command -Name 'pwsh' -ErrorAction 'SilentlyContinue') {
return Get-Item -Path $Command.Source -Force
}
throw 'The external installer parser bridge requires pwsh to be available'
}
function Resolve-InstallerBridgeModulePath {
<#
.SYNOPSIS
Resolve the path to a separately licensed installer parser module
.PARAMETER Name
The parser module directory name under Modules
#>
[OutputType([System.IO.DirectoryInfo])]
param (
[Parameter(Mandatory, HelpMessage = 'The parser module directory name under Modules')]
[ValidateSet('InstallerParsers')]
[string]$Name
)
$ModulePath = Join-Path $PSScriptRoot "..\..\..\$Name"
if (-not (Test-Path -Path $ModulePath)) {
throw "The separate installer parser module '$Name' could not be found at $ModulePath"
}
return Get-Item -Path $ModulePath -Force
}
function Resolve-InstallerBridgeCliPath {
<#
.SYNOPSIS
Resolve the CLI entrypoint for a separately licensed installer parser module
.PARAMETER Name
The parser module directory name under Modules
#>
[OutputType([System.IO.FileInfo])]
param (
[Parameter(Mandatory, HelpMessage = 'The parser module directory name under Modules')]
[ValidateSet('InstallerParsers')]
[string]$Name
)
$CliPath = Join-Path (Resolve-InstallerBridgeModulePath -Name $Name).FullName 'Cli.ps1'
if (-not (Test-Path -Path $CliPath)) {
throw "The installer parser CLI for '$Name' could not be found at $CliPath"
}
return Get-Item -Path $CliPath -Force
}
function ConvertTo-InstallerBridgeObject {
<#
.SYNOPSIS
Restore normal JSON objects while preserving member names that PowerShell cannot represent on PSCustomObject
.PARAMETER InputObject
A value produced by ConvertFrom-Json -AsHashtable, including nested dictionaries and arrays
#>
param (
[Parameter(ValueFromPipeline, Mandatory, HelpMessage = 'A losslessly deserialized installer parser value')]
[AllowNull()]
[object]$InputObject
)
process {
if ($null -eq $InputObject) { return $null }
if ($InputObject -is [System.Collections.IDictionary]) {
$Converted = [ordered]@{}
$MemberNames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase)
$RequiresDictionary = $false
foreach ($Entry in $InputObject.GetEnumerator()) {
$MemberName = [string]$Entry.Key
# PSCustomObject rejects an empty member name and folds names that differ
# only by case. Keep such JSON objects as dictionaries to avoid data loss.
if ([string]::IsNullOrEmpty($MemberName) -or -not $MemberNames.Add($MemberName)) {
$RequiresDictionary = $true
}
$ConvertedValue = ConvertTo-InstallerBridgeObject -InputObject $Entry.Value
if ($MemberName -eq 'UnresolvedFields') {
# JSON arrays lose their element type. Restore unresolved metadata
# field names without flattening structured diagnostic evidence.
$ConvertedValue = [string[]]@($ConvertedValue)
} elseif ($MemberName -eq 'Diagnostics') {
$ConvertedValue = [object[]]@($ConvertedValue)
}
$Converted[$MemberName] = $ConvertedValue
}
if ($RequiresDictionary) {
# Unary-comma return preserves IDictionary as one value. In PowerShell
# 7.6, Write-Output -NoEnumerate can wrap OrderedDictionary in a List.
return , $Converted
} else {
[pscustomobject]$Converted
}
return
}
if ($InputObject -is [System.Collections.IEnumerable] -and $InputObject -isnot [string]) {
$Converted = [System.Collections.Generic.List[object]]::new()
foreach ($Item in $InputObject) {
$Converted.Add((ConvertTo-InstallerBridgeObject -InputObject $Item))
}
return , $Converted.ToArray()
}
return $InputObject
}
}
function ConvertFrom-InstallerBridgeJson {
<#
.SYNOPSIS
Deserialize installer parser JSON without rejecting unnamed registry values
.PARAMETER Json
JSON emitted by the separately licensed installer parser CLI
#>
[OutputType([pscustomobject], [System.Collections.IDictionary], [object[]])]
param (
[Parameter(ValueFromPipeline, Mandatory, HelpMessage = 'JSON emitted by an installer parser CLI')]
[string]$Json
)
process {
# Registry default values legitimately use an empty value name. PowerShell's
# normal JSON mode rejects those members, while -AsHashtable retains them.
$Value = $Json | ConvertFrom-Json -AsHashtable -Depth 100
ConvertTo-InstallerBridgeObject -InputObject $Value
}
}
function Invoke-InstallerBridgeCommand {
<#
.SYNOPSIS
Invoke a separately licensed installer parser module through an external PowerShell process
.PARAMETER ModuleName
The parser module directory name under Modules
.PARAMETER Action
The CLI action to invoke
.PARAMETER Argument
The CLI arguments to forward
.PARAMETER TimeoutSeconds
Maximum runtime before the parser process and its descendants are terminated
#>
param (
[Parameter(Mandatory, HelpMessage = 'The parser module directory name under Modules')]
[ValidateSet('InstallerParsers')]
[string]$ModuleName,
[Parameter(Mandatory, HelpMessage = 'The CLI action to invoke')]
[string]$Action,
[Parameter(HelpMessage = 'The CLI arguments to forward')]
[hashtable]$Argument = @{},
[Parameter(HelpMessage = 'Maximum parser runtime in seconds')]
[ValidateRange(1, 3600)]
[int]$TimeoutSeconds = 300
)
$PowerShellPath = (Get-InstallerBridgePowerShell).FullName
$CliPath = (Resolve-InstallerBridgeCliPath -Name $ModuleName).FullName
$InteractiveCollisionPrompt = $Argument.ContainsKey('CollisionAction') -and $Argument.CollisionAction -eq 'Prompt'
$BridgeResultPath = $null
$StartInfo = [System.Diagnostics.ProcessStartInfo]::new()
$StartInfo.FileName = $PowerShellPath
$StartInfo.UseShellExecute = $false
# Prompt-mode extraction inherits the parent console just like native file
# cmdlets. The parser writes its machine-readable result to a temporary file
# so host prompts cannot corrupt the JSON transport stream.
$StartInfo.RedirectStandardOutput = -not $InteractiveCollisionPrompt
$StartInfo.RedirectStandardError = $true
if ($StartInfo.RedirectStandardOutput) {
$StartInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
}
$StartInfo.StandardErrorEncoding = [System.Text.Encoding]::UTF8
foreach ($Value in @('-NoLogo', '-NoProfile', '-File', $CliPath, '-Action', $Action)) {
$null = $StartInfo.ArgumentList.Add($Value)
}
foreach ($Entry in $Argument.GetEnumerator()) {
if ($null -eq $Entry.Value) { continue }
if ($Entry.Value -is [string] -and [string]::IsNullOrWhiteSpace($Entry.Value)) { continue }
# Forward true switches by name and omit false switches. Native PowerShell
# cannot bind the strings "True" and "False" to switch parameters.
if ($Entry.Value -is [bool] -or $Entry.Value -is [System.Management.Automation.SwitchParameter]) {
if ([bool]$Entry.Value) { $null = $StartInfo.ArgumentList.Add("-$($Entry.Key)") }
continue
}
$null = $StartInfo.ArgumentList.Add("-$($Entry.Key)")
$null = $StartInfo.ArgumentList.Add([string]$Entry.Value)
}
if ($InteractiveCollisionPrompt) {
$BridgeResultPath = Join-Path ([IO.Path]::GetTempPath()) "Dumplings-InstallerBridge-$([guid]::NewGuid().ToString('N')).json"
$null = $StartInfo.ArgumentList.Add('-ResultPath')
$null = $StartInfo.ArgumentList.Add($BridgeResultPath)
}
$Process = [System.Diagnostics.Process]::new()
$Process.StartInfo = $StartInfo
try {
$null = $Process.Start()
# Drain both redirected streams concurrently so a verbose parser cannot
# deadlock while its sibling pipe is waiting to be read.
$StandardOutputTask = if ($StartInfo.RedirectStandardOutput) { $Process.StandardOutput.ReadToEndAsync() } else { $null }
$StandardErrorTask = $Process.StandardError.ReadToEndAsync()
if (-not $Process.WaitForExit($TimeoutSeconds * 1000)) {
try { $Process.Kill($true) } catch { }
throw "The installer parser CLI '$Action' exceeded the $TimeoutSeconds-second timeout"
}
$Process.WaitForExit()
$StandardError = $StandardErrorTask.GetAwaiter().GetResult()
if ($Process.ExitCode -ne 0) {
$Message = if ([string]::IsNullOrWhiteSpace($StandardError)) {
"The installer parser CLI '$Action' failed with exit code $($Process.ExitCode)"
} else {
"The installer parser CLI '$Action' failed with exit code $($Process.ExitCode): $StandardError"
}
throw $Message.Trim()
}
$StandardOutput = if ($InteractiveCollisionPrompt) {
if (-not (Test-Path -LiteralPath $BridgeResultPath -PathType Leaf)) {
throw "The installer parser CLI '$Action' did not produce its interactive result"
}
[IO.File]::ReadAllText($BridgeResultPath, [Text.Encoding]::UTF8)
} else {
$StandardOutputTask.GetAwaiter().GetResult()
}
if ([string]::IsNullOrWhiteSpace($StandardOutput)) { return $null }
return $StandardOutput | ConvertFrom-InstallerBridgeJson
} finally {
try { if (-not $Process.HasExited) { $Process.Kill($true) } } catch { }
$Process.Dispose()
if ($BridgeResultPath) {
try { [IO.File]::Delete($BridgeResultPath) } catch { }
}
}
}
function Convert-InstallerBridgePathsToFileInfo {
<#
.SYNOPSIS
Convert JSON path results from the installer bridge to FileInfo objects
.PARAMETER Path
The file paths returned by the external parser module
#>
[OutputType([System.IO.FileInfo[]])]
param (
[Parameter(HelpMessage = 'The file paths returned by the external parser module')]
[AllowNull()]
[object[]]$Path
)
$Result = [System.Collections.Generic.List[System.IO.FileInfo]]::new()
foreach ($Item in @($Path)) {
if ($null -eq $Item) { continue }
$Result.Add((Get-Item -Path ([string]$Item) -Force))
}
return $Result.ToArray()
}
Export-ModuleMember -Function Invoke-InstallerBridgeCommand, Convert-InstallerBridgePathsToFileInfo