Repository navigation
Expand file tree
/
Copy pathBuild-PSBuildModule.ps1
More file actions
298 lines (266 loc) · 12.4 KB
/
Copy pathBuild-PSBuildModule.ps1
File metadata and controls
298 lines (266 loc) · 12.4 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
# spell-checker:ignore modulename
function Build-PSBuildModule {
<#
.SYNOPSIS
Builds a PowerShell module based on source directory
.DESCRIPTION
Builds a PowerShell module based on source directory and optionally
concatenates public/private functions from separate files into
monolithic .PSM1 file.
.PARAMETER Path
The source module path.
.PARAMETER DestinationPath
Destination path to write "built" module to.
.PARAMETER ModuleName
The name of the module.
.PARAMETER Compile
Switch to indicate if separate function files should be concatenated
into monolithic .PSM1 file.
.PARAMETER CompileHeader
String that will be at the top of your PSM1 file.
.PARAMETER CompileFooter
String that will be added to the bottom of your PSM1 file.
.PARAMETER CompileScriptHeader
String that will be added to your PSM1 file before each script file.
.PARAMETER CompileScriptFooter
String that will be added to your PSM1 file after each script file.
.PARAMETER ReadMePath
Path to project README. If present, this will become the
"about_<ModuleName>.help.txt" file in the build module.
.PARAMETER CompileDirectories
List of directories containing .ps1 files that will also be compiled
into the PSM1.
.PARAMETER CopyDirectories
List of directories that will copying "as-is" into the build module.
.PARAMETER Exclude
Array of files (regular expressions) to exclude from copying into built
module.
.PARAMETER Culture
UI Culture. This is used to determine what culture directory to store
"about_<ModuleName>.help.txt" in.
.EXAMPLE
$buildParams = @{
Path = ./MyModule
DestinationPath = ./Output/MoModule/0.1.0
ModuleName = MyModule
Exclude = @()
Compile = $false
Culture = (Get-UICulture).Name
}
Build-PSBuildModule @buildParams
Build module from source directory './MyModule' and save to
'/Output/MoModule/0.1.0'
#>
[CmdletBinding()]
param(
[parameter(Mandatory)]
[string]$Path,
[parameter(Mandatory)]
[string]$DestinationPath,
[parameter(Mandatory)]
[string]$ModuleName,
[switch]$Compile,
[string]$CompileHeader,
[string]$CompileFooter,
[string]$CompileScriptHeader,
[string]$CompileScriptFooter,
[string]$ReadMePath,
# Defaulted rather than left empty. Get-ChildItem -Path @() binds nothing and
# falls back to the current location, so -Compile with no directories recursed
# the caller's working directory into the built module and still reported
# success. This is the value build.properties.ps1 supplies, so a direct call now
# behaves like the task path. See psake/PowerShellBuild#206.
[string[]]$CompileDirectories = @('Enum', 'Classes', 'Private', 'Public'),
[string[]]$CopyDirectories = @(),
[string[]]$Exclude = @(),
[string]$Culture = (Get-UICulture).Name
)
if (-not (Test-Path -LiteralPath $DestinationPath)) {
$newItemSplat = @{
Path = $DestinationPath
ItemType = 'Directory'
Verbose = $VerbosePreference
}
New-Item @newItemSplat > $null
}
# Copy "non-processed files"
$getChildItemSplat = @{
Path = $Path
Include = '*.psm1', '*.psd1', '*.ps1xml'
Depth = 1
}
Get-ChildItem @getChildItemSplat |
Copy-Item -Destination $DestinationPath -Force
foreach ($dir in $CopyDirectories) {
$copyPath = [IO.Path]::Combine($Path, $dir)
Copy-Item -Path $copyPath -Destination $DestinationPath -Recurse -Force
}
# Copy README as about_<modulename>.help.txt
if (-not [string]::IsNullOrEmpty($ReadMePath)) {
$culturePath = [IO.Path]::Combine($DestinationPath, $Culture)
$aboutModulePath = [IO.Path]::Combine(
$culturePath,
"about_$($ModuleName).help.txt"
)
# The guard belongs to New-Item alone. With the copy inside it, an existing
# culture directory meant no about help file was written at all -- and
# CopyDirectories runs above, so naming the culture directory there was enough
# to suppress it silently. That is psake/PowerShellBuild#207. The Force below was
# already here and unreachable; this restores the overwrite it was written for.
if (-not (Test-Path -LiteralPath $culturePath -PathType Container)) {
New-Item -Path $culturePath -ItemType Directory -Force > $null
}
$copyItemSplat = @{
LiteralPath = $ReadMePath
Destination = $aboutModulePath
Force = $true
}
Copy-Item @copyItemSplat
}
# Copy source files to destination and optionally combine *.ps1 files
# into the PSM1
if ($Compile.IsPresent) {
$rootModule = [IO.Path]::Combine($DestinationPath, "$ModuleName.psm1")
# Grab the contents of the copied over PSM1
# This will be appended to the end of the finished PSM1
$psm1Contents = Get-Content -Path $rootModule -Raw
# Because that content is appended last, an Export-ModuleMember call inside it runs
# after the concatenated functions, and the module's effective export set is the
# intersection of that call and FunctionsToExport in the manifest. Compiling copies no
# function directories to the output, so the scaffold loader that almost every module
# template generates discovers nothing and exports nothing, while the manifest still
# names every public function and the build still succeeds. Warned about rather than
# rewritten: what the consumer's root module should do instead depends on the module.
# See psake/PowerShellBuild#201.
#
# Found by parsing rather than by matching text, so that the command named in a
# comment or quoted in a here-string -- including a comment explaining why the loader
# deliberately does not call it -- is not reported as a call. A line-anchored regex
# gets the single-line # comment right and still fires inside a <# #> block or a
# here-string, because it cannot see that the line it anchored on is not code.
$rootModuleAst = [System.Management.Automation.Language.Parser]::ParseInput(
$psm1Contents, [ref] $null, [ref] $null
)
$exportModuleMemberCall = $rootModuleAst.FindAll(
{
param($node)
$node -is [System.Management.Automation.Language.CommandAst] -and
$node.GetCommandName() -eq 'Export-ModuleMember'
},
$true
)
if ($exportModuleMemberCall) {
$sourceRootModule = [IO.Path]::Combine($Path, "$ModuleName.psm1")
Write-Warning (
$LocalizedData.ExportModuleMemberInSourceRootModule -f $sourceRootModule
)
}
'' | Out-File -FilePath $rootModule -Encoding 'utf8'
if ($CompileHeader) {
$CompileHeader | Add-Content -Path $rootModule -Encoding 'utf8'
}
$resolvedCompileDirectories = $CompileDirectories | ForEach-Object {
[IO.Path]::Combine($Path, $_)
}
# An empty compile list leaves -Path null, and Get-ChildItem treats null or empty as
# "not supplied" and falls back to the current location -- so this would recurse the
# working directory and concatenate every .ps1 under it into the root module, while
# the build reported success. PowerShell/PowerShell#17793 is Won't Fix, with the
# working group's advice being to validate in the caller, so the guard belongs here.
#
# The parameter default covers an omitted argument. This covers an explicit empty
# array, which is what both task files forward when a consumer sets
# $PSBPreference.Build.CompileDirectories = @(). See psake/PowerShellBuild#206.
$allScripts = @()
if ($resolvedCompileDirectories) {
$getChildItemSplat = @{
Path = $resolvedCompileDirectories
Filter = '*.ps1'
File = $true
Recurse = $true
ErrorAction = 'SilentlyContinue'
}
$allScripts = Get-ChildItem @getChildItemSplat
}
# Compiling to an empty set produces a root module holding only its header, the
# appended source .psm1, and its footer -- a plausible artifact with every function
# missing. Warned about rather than treated as an error: wrapping an already-complete
# .psm1 in a header and footer is a coherent thing to ask for.
if (-not $allScripts) {
Write-Warning ($LocalizedData.NoScriptsToCompile -f ($CompileDirectories -join ', '))
}
$allScripts = $allScripts | Remove-ExcludedItem -Exclude $Exclude
$addContentSplat = @{
Path = $rootModule
Encoding = 'utf8'
}
$allScripts | ForEach-Object {
# Read through the full path. This used to read through a path resolved relative to
# the current location, which is not something every current location can express.
# On Windows PowerShell 5.1 a source file on another drive resolves to a path like
# .\C:\src\Public\Get-Widget.ps1, and a source outside the current PSDrive's root to
# a ..\ path that cannot climb past that root. Neither can be read back, so
# Get-Content silently returned nothing for every file and the compiled .psm1 came
# out holding its headers and footers and none of the functions -- while the build
# reported success. It is reachable whenever the build runs from a different drive
# than the module source, which is how the Windows PowerShell 5.1 CI job is laid out.
$sourceFilePath = $_.FullName
Write-Verbose ($LocalizedData.AddingFileToPsm1 -f $sourceFilePath)
if ($CompileScriptHeader) {
Write-Output $CompileScriptHeader
}
# -LiteralPath, not -Path: the value is a FullName, and -Path reads [ ] * ? as
# wildcards. A source file named Get-Widget[1].ps1, or any checkout under a
# directory like repo[main], would then match nothing and be dropped from the
# compiled module in silence -- the same failure this full-path read exists to
# prevent, reached a different way.
Get-Content -LiteralPath $sourceFilePath
if ($CompileScriptFooter) {
Write-Output $CompileScriptFooter
}
} | Add-Content @addContentSplat
$psm1Contents | Add-Content @addContentSplat
if ($CompileFooter) {
$CompileFooter | Add-Content @addContentSplat
}
} else {
# Copy everything over, then remove stuff that should have been excluded
# It's just easier this way
$copyParams = @{
Path = [IO.Path]::Combine($Path, '*')
Destination = $DestinationPath
Recurse = $true
Force = $true
Verbose = $VerbosePreference
}
Copy-Item @copyParams
$allItems = Get-ChildItem -Path $DestinationPath -Recurse
$toRemove = foreach ($item in $allItems) {
foreach ($regex in $Exclude) {
if ($item -match $regex) {
$item
}
}
}
$toRemove | Remove-Item -Recurse -Force -ErrorAction 'Ignore'
}
# Export public functions in manifest if there are any public functions
$getChildItemSplat = @{
Recurse = $true
ErrorAction = 'SilentlyContinue'
Path = "$Path/Public/*.ps1"
}
$publicFunctions = Get-ChildItem @getChildItemSplat
if ($publicFunctions) {
$outputManifest = [IO.Path]::Combine(
$DestinationPath,
"$ModuleName.psd1"
)
$updateMetadataSplat = @{
Path = $OutputManifest
PropertyName = 'FunctionsToExport'
Value = $publicFunctions.BaseName
}
Update-Metadata @updateMetadataSplat
}
}