-
Notifications
You must be signed in to change notification settings - Fork 0
/
Install-Dependency.ps1
357 lines (313 loc) · 14.1 KB
/
Install-Dependency.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
<#
.SYNOPSIS
Installs script or module dependencies based on '#requires -Module' statements or module manifests.
.EXAMPLE
Install-Dependency.ps1 -Path .\Script.ps1
Installs script dependencies defined by '#requires -Module' statements. Module is installed for current user only.
.EXAMPLE
Install-Dependency.ps1 -Path .\Module.psd1
Installs module dependencies defined by module manifest (manifest is specified directly). Module is installed for current user only.
.EXAMPLE
Install-Dependency.ps1 -Path .\Module
Installs module dependencies defined by module manifest (manifest is located by parent's name). Module is installed for current user only.
.EXAMPLE
Install-Dependency.ps1 -Path .\ScriptModule.psm1, .\Script.ps1, .\Module -Scope AllUsers
Installs dependencies of all given items. Modules are installed globally for all users.
.EXAMPLE
Install-Dependency.ps1 -Path .\ScriptModule.psm1 -Scope CurrentUser -Repository PSGallery, UntrustedRepository
Installs script module dependencies. Dependencies could be installed from given repositories even if repositories are not trusted. Module is installed for current user only.
.EXAMPLE
Install-Dependency.ps1 -Path .\Script.psm1 -LimitMajorVersion
Installs script dependencies. If no maximum allowed version is specified, the script automatically adds maximum version constraint to prevent installing modules with breaking changes.
.EXAMPLE
Install-Dependency.ps1 -Path .\Module.psd1 -InformationAction Continue
Installs module dependencies and displays information about installed modules.
.EXAMPLE
Install-Dependency.ps1 -Path ".\Module.psd1|.\Script.ps1" -AdditionalPathDelimiter "|"
Installs module dependencies of both Module.psd1 and Script.ps1. Paths must be delimited by a character defined in 'AdditionalPathDelimiter'.
#>
[CmdletBinding()]
param(
# Paths to items whose dependencies should be installed
[Parameter(Mandatory = $true)]
[string[]] $Path,
# Installation scope of installed modules (allowed values are 'CurrentUser' and 'AllUsers')
[ValidateSet("AllUsers", "CurrentUser")]
[ValidateScript( {
$CurrentUser = [System.Security.Principal.WindowsPrincipal]::new([System.Security.Principal.WindowsIdentity]::GetCurrent())
if ($PSItem -eq "AllUsers" -and -not $CurrentUser.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "Modules can be installed globally only if the script is executed as administrator."
}
return $true
}
)]
[string] $Scope = "CurrentUser",
# Repositories from which modules could be installed (defaults to all trusted repositories)
[string[]] $Repository = (Get-PSRepository | ? -Property "InstallationPolicy" -EQ -Value "Trusted" | select -ExpandProperty "Name"),
# Optional delimiter that is applied on each item of 'Path' to get all paths (useful in CI/CD systems that are not able to provide multiple values using array syntax)
[string] $AdditionalPathDelimiter,
# Limit major version in order to avoid breaking changes in installed modules
[switch] $LimitMajorVersion
)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
Set-StrictMode -Version 2
$script:InstalledModules = Get-Module -ListAvailable
$script:RequiresModuleStatementRegex = [regex]::new("^\s*#requires\s+-modules?\s+(.*)$", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
function Test-Line {
<#
.SYNOPSIS
Tests whether given line represents '#requires -Module' statement.
#>
param(
# Line to test
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[string] $Line
)
return $script:RequiresModuleStatementRegex.IsMatch($Line)
}
function ConvertTo-ModuleDefinition {
<#
.SYNOPSIS
Converts hashtable with module reference (as used in '#requires -Module' statement or in module manifest)
to a hashtable with module definition which can be used as parameter for Install-Module cmdlet.
#>
param(
# Module reference to convert
[Parameter(Mandatory = $true)]
[hashtable] $ModuleReference
)
$ModuleDefinition = @{
Name = $ModuleReference.ModuleName
}
if ($ModuleReference.ContainsKey("ModuleVersion")) {
$ModuleDefinition.Add("MinimumVersion", $ModuleReference.ModuleVersion -as [version])
}
if ($ModuleReference.ContainsKey("MaximumVersion")) {
$ModuleDefinition.Add("MaximumVersion", $ModuleReference.MaximumVersion -as [version])
}
elseif ($script:LimitMajorVersion -and $ModuleDefinition.ContainsKey("MinimumVersion")) {
$MajorVersion = $ModuleDefinition.MinimumVersion.Major
$MaxInt = [int]::MaxValue
$HighestAllowedVersion = [version]::new($MajorVersion, $MaxInt, $MaxInt, $MaxInt)
$ModuleDefinition.Add("MaximumVersion", $HighestAllowedVersion)
}
if ($ModuleReference.ContainsKey("RequiredVersion")) {
$ModuleDefinition.Add("RequiredVersion", $ModuleReference.RequiredVersion -as [version])
}
return $ModuleDefinition
}
function Get-ModuleDefinition {
<#
.SYNOPSIS
Extracts module definition from '#requires -Module' statement.
The definition can be used as parameter for Install-Module cmdlet.
#>
[System.Diagnostics.CodeAnalysis.SuppressMessage("PSAvoidUsingInvokeExpression", "",
Justification = "Although potential security problem, we need to parse hashtable literal to get the module reference.")]
param(
# Line to extract module definition from
[Parameter(Mandatory = $true)]
[string] $Line
)
$StatementValue = $script:RequiresModuleStatementRegex.Match($Line).Groups[1].Value
$StatementValue = $StatementValue.Split(",")
$ModuleDefinitions = $StatementValue | % {
$SerializedReference = $PSItem.Trim().Trim("'").Trim("""")
if (-not $SerializedReference.StartsWith("@{")) {
# Module is referenced only by its name. Provide complete reference structure.
$SerializedReference = "@{ ModuleName = '$SerializedReference' }"
}
$DeserializedReference = Invoke-Expression -Command $SerializedReference
return ConvertTo-ModuleDefinition -ModuleReference $DeserializedReference
}
return $ModuleDefinitions
}
function Test-ModuleCompliance {
<#
.SYNOPSIS
Tests whether the given module complies name and version requirements.
#>
param(
# Module to test
[Parameter(Mandatory = $true)]
[PSModuleInfo] $Module,
# Requirements to test the module against
[Parameter(Mandatory = $true)]
[hashtable] $Requirement
)
if ($Module.Name -ne $Requirement.Name) {
return $false
}
$ModuleVersion = $Module.Version
if ($Requirement.ContainsKey("RequiredVersion") -and $ModuleVersion -ne $Requirement.RequiredVersion) {
return $false
}
if ($Requirement.ContainsKey("MaximumVersion") -and $ModuleVersion -gt $Requirement.MaximumVersion) {
return $false
}
if ($Requirement.ContainsKey("MinimumVersion") -and $ModuleVersion -lt $Requirement.MinimumVersion) {
return $false
}
return $true
}
function Format-VersionConstraint {
<#
.SYNOPSIS
Returns version constraint defined in module definition in printable format.
#>
param(
# Module definition to format
[Parameter(Mandatory = $true)]
[hashtable] $ModuleDefinition
)
if ($ModuleDefinition.ContainsKey("RequiredVersion")) {
return "[$($ModuleDefinition.RequiredVersion)]"
}
elseif ($ModuleDefinition.ContainsKey("MinimumVersion") -and -not $ModuleDefinition.ContainsKey("MaximumVersion")) {
return "[$($ModuleDefinition.MinimumVersion), )"
}
elseif ($ModuleDefinition.ContainsKey("MinimumVersion") -and $ModuleDefinition.ContainsKey("MaximumVersion")) {
return "[$($ModuleDefinition.MinimumVersion), $($ModuleDefinition.MaximumVersion)]"
}
elseif (-not $ModuleDefinition.ContainsKey("MinimumVersion") -and $ModuleDefinition.ContainsKey("MaximumVersion")) {
return "(, $($ModuleDefinition.MaximumVersion)]"
}
return "[0.0.0, )"
}
function Install-Dependency {
<#
.SYNOPSIS
Installs module dependency defined by given module definition.
#>
param(
# Module to install
[Parameter(Mandatory = $true)]
[hashtable] $ModuleDefinition
)
$ModuleName = $ModuleDefinition.Name
$VersionConstraint = Format-VersionConstraint -ModuleDefinition $ModuleDefinition
$SatisfyingModules = @($script:InstalledModules | ? { Test-ModuleCompliance -Module $PSItem -Requirement $ModuleDefinition })
if ($SatisfyingModules.Length -gt 0) {
$SkipMessage = "Module '$ModuleName' is already installed and its version constraints '$VersionConstraint' are satisfied by following modules:"
Write-Information -MessageData $SkipMessage
$SatisfyingModules | % { Write-Information -MessageData "$($PSItem.Name), $($PSItem.Version)" }
continue
}
Write-Information "Installing module '$ModuleName, $VersionConstraint'."
Install-Module @ModuleDefinition -Scope $script:Scope -Repository $script:Repository -AllowClobber -Force
# Since previously installed module could installed other dependencies that might be required later,
# refresh the list of already installed modules.
$script:InstalledModules = Get-Module -ListAvailable
}
function Install-ScriptFileDependency {
<#
.SYNOPSIS
Installs script file module dependencies defined by '#requires -Module' statements.
#>
param(
# Path to script
[Parameter(Mandatory = $true)]
[ValidateScript( { if (Test-Path -Path $PSItem -PathType Leaf) { return $true } else { throw "File '$PSItem' cannot be found. Specify valid path." } })]
[string] $FilePath
)
$Lines = Get-Content -Path $FilePath
$RequiredModules = $Lines | % {
if (Test-Line -Line $PSItem) {
return Get-ModuleDefinition -Line $PSItem
}
}
foreach ($ModuleDefinition in $RequiredModules) {
Install-Dependency -ModuleDefinition $ModuleDefinition
}
}
function Install-ManifestFileDependency {
<#
.SYNOPSIS
Installs module dependencies defined by module manifest.
#>
[System.Diagnostics.CodeAnalysis.SuppressMessage("PSAvoidUsingInvokeExpression", "",
Justification = "Although potential security problem, we need to parse module manifest.")]
param(
[Parameter(Mandatory = $true)]
[ValidateScript( { if (Test-Path -Path $PSItem -PathType Leaf) { return $true } else { throw "File '$PSItem' cannot be found. Specify valid path." } })]
[string] $FilePath
)
# Resolve to absolute path. Later in the function, when searching for nested modules, 'Split-Path -Parent' would return null for 'Something.psd1'
# and then 'Join-Path' would fail because it would try to join null with path to nested module which is prohibited.
$FilePath = (Resolve-Path -Path $FilePath).Path
[hashtable] $Manifest = Invoke-Expression -Command (Get-Content -Path $FilePath -Raw)
if ($Manifest.ContainsKey("RequiredModules")) {
$RequiredModules = $Manifest.RequiredModules
foreach ($Module in $RequiredModules) {
# Module is referenced only by its name. Provide complete reference structure.
if ($Module -is [string]) {
$Module = @{ ModuleName = $Module }
}
$ModuleDefinition = ConvertTo-ModuleDefinition -ModuleReference $Module
Install-Dependency -ModuleDefinition $ModuleDefinition
}
}
# Install also dependencies of all nested modules.
if ($Manifest.ContainsKey("NestedModules")) {
$NestedModules = $Manifest.NestedModules
$BasePath = Split-Path -Path $FilePath -Parent
foreach ($NestedModule in $NestedModules) {
$NestedModulePath = Join-Path -Path $BasePath -ChildPath $NestedModule
if (Test-Path -Path $NestedModulePath -PathType Container) {
$ManifestName = "$(Split-Path -Path $NestedModulePath -Leaf).psd1"
$NestedModuleManifestPath = Join-Path -Path $NestedModulePath -ChildPath $ManifestName
if (Test-Path -Path $NestedModuleManifestPath -PathType Leaf) {
Install-ManifestFileDependency -FilePath $NestedModuleManifestPath
}
}
}
}
}
function Select-DependencyInstaller {
<#
.SYNOPSIS
Selects proper dependency installer based on the type of given item.
#>
param(
# Path to item whose dependencies should be installed
[Parameter(Mandatory = $true)]
[string] $Path
)
if (Test-Path -Path $Path -PathType Leaf) {
$Extension = [System.IO.Path]::GetExtension($Path)
switch -Regex ($Extension) {
"\.psm?1" {
Install-ScriptFileDependency -FilePath $Path
}
"\.psd1" {
Install-ManifestFileDependency -FilePath $Path
}
default {
Write-Warning -Message "Could not proceed with the file '$Path' due to the unknown extension '$Extension'."
}
}
}
elseif (Test-Path -Path $Path -PathType Container) {
$ModuleManifestName = "$(Split-Path -Path $Path -Leaf).psd1"
$ModuleManifestPath = Join-Path -Path $Path -ChildPath $ModuleManifestName
if (Test-Path -Path $ModuleManifestPath -PathType Leaf) {
Select-DependencyInstaller -Path $ModuleManifestPath
}
else {
Write-Warning -Message "Could not locate module manifest '$ModuleManifestName' in the directory '$Path'."
}
}
else {
Write-Warning -Message "No item available on path '$Path'."
}
}
# Multiple paths might be concatenated into a single string. Perform additional split.
if (-not [string]::IsNullOrEmpty($AdditionalPathDelimiter)) {
$Path = $Path | % {
return $PSItem -split $AdditionalPathDelimiter, 0, "SimpleMatch"
}
}
foreach ($CurrentPath in $Path) {
Select-DependencyInstaller -Path $CurrentPath -ErrorAction Continue
}