-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathALZ.build.ps1
More file actions
569 lines (476 loc) · 27.1 KB
/
ALZ.build.ps1
File metadata and controls
569 lines (476 loc) · 27.1 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
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<#
.SYNOPSIS
An Invoke-Build Build file.
.DESCRIPTION
Build steps can include:
- ValidateRequirements
- ImportModuleManifest
- Clean
- Analyze
- FormattingCheck
- Test
- DevCC
- CreateHelpStart
- Build
- IntegrationTest
- Archive
.EXAMPLE
Invoke-Build
This will perform the default build Add-BuildTasks: see below for the default Add-BuildTask execution
.EXAMPLE
Invoke-Build -Add-BuildTask Analyze,Test
This will perform only the Analyze and Test Add-BuildTasks.
.NOTES
This build file by Catesta will pull in configurations from the "<module>.Settings.ps1" file as well, where users can more easily customize the build process if required.
https://github.com/nightroman/Invoke-Build
https://github.com/nightroman/Invoke-Build/wiki/Build-Scripts-Guidelines
If using VSCode you can use the generated tasks.json to execute the various tasks in this build file.
Ctrl + P | then type task (add space) - you will then be presented with a list of available tasks to run
The 'InstallDependencies' Add-BuildTask isn't present here.
Module dependencies are installed at a previous step in the pipeline.
If your manifest has module dependencies include all required modules in your CI/CD bootstrap file:
AWS - install_modules.ps1
Azure - actions_bootstrap.ps1
GitHub Actions - actions_bootstrap.ps1
AppVeyor - actions_bootstrap.ps1
#>
#Include: Settings
$ModuleName = (Split-Path -Path $BuildFile -Leaf).Split('.')[0]
. "./$ModuleName.Settings.ps1"
function Test-ManifestBool ($Path) {
Get-ChildItem $Path | Test-ModuleManifest -ErrorAction SilentlyContinue | Out-Null; $?
}
#Default Build
$str = @()
$str = 'Clean', 'ValidateRequirements', 'ImportModuleManifest'
$str += 'FormattingCheck'
$str += 'Analyze', 'Test'
$str += 'Build', 'Archive'
$str += "Install"
Add-BuildTask -Name . -Jobs $str
#Local testing build process
Add-BuildTask TestLocal Clean, ImportModuleManifest, Analyze, Test
#Local help file creation process
Add-BuildTask HelpLocal Clean, ImportModuleManifest, CreateHelpStart
#Full build sans integration tests
Add-BuildTask BuildNoIntegration -Jobs $str2
#Build and Install Only
Add-BuildTask BuildAndInstallOnly Clean, ImportModuleManifest, Build, Archive, Install
# Pre-build variables to be used by other portions of the script
Enter-Build {
$script:ModuleName = (Split-Path -Path $BuildFile -Leaf).Split('.')[0]
# Identify other required paths
$script:ModuleSourcePath = Join-Path -Path $BuildRoot -ChildPath $script:ModuleName
$script:ModuleFiles = Join-Path -Path $script:ModuleSourcePath -ChildPath '*'
$script:ModuleManifestFile = Join-Path -Path $script:ModuleSourcePath -ChildPath "$($script:ModuleName).psd1"
$manifestInfo = Import-PowerShellDataFile -Path $script:ModuleManifestFile
$script:ModuleVersion = $manifestInfo.ModuleVersion
$script:ModuleDescription = $manifestInfo.Description
$script:FunctionsToExport = $manifestInfo.FunctionsToExport
$script:TestsPath = Join-Path -Path $BuildRoot -ChildPath 'Tests'
$script:UnitTestsPath = Join-Path -Path $script:TestsPath -ChildPath 'Unit'
$script:IntegrationTestsPath = Join-Path -Path $script:TestsPath -ChildPath 'Integration'
$script:ArtifactsPath = Join-Path -Path $BuildRoot -ChildPath 'Artifacts'
$script:ArchivePath = Join-Path -Path $BuildRoot -ChildPath 'Archive'
$script:BuildModuleRootFile = Join-Path -Path $script:ModuleSourcePath -ChildPath "$($script:ModuleName).psm1"
# Ensure our builds fail until if below a minimum defined code test coverage threshold
$script:coverageThreshold = 5
[version]$script:MinPesterVersion = '5.2.2'
[version]$script:MaxPesterVersion = '5.99.99'
$script:testOutputFormat = 'NUnitXML'
} #Enter-Build
# Define headers as separator, task path, synopsis, and location, e.g. for Ctrl+Click in VSCode.
# Also change the default color to Green. If you need task start times, use `$Task.Started`.
Set-BuildHeader {
param($Path)
# separator line
Write-Build DarkMagenta ('=' * 79)
# default header + synopsis
Write-Build DarkGray "Task $Path : $(Get-BuildSynopsis $Task)"
# task location in a script
Write-Build DarkGray "At $($Task.InvocationInfo.ScriptName):$($Task.InvocationInfo.ScriptLineNumber)"
Write-Build Yellow "Manifest File: $script:ModuleManifestFile"
Write-Build Yellow "Manifest Version: $($manifestInfo.ModuleVersion)"
} #Set-BuildHeader
# Define footers similar to default but change the color to DarkGray.
Set-BuildFooter {
param($Path)
Write-Build DarkGray "Done $Path, $($Task.Elapsed)"
# # separator line
# Write-Build Gray ('=' * 79)
} #Set-BuildFooter
#Synopsis: Validate system requirements are met
Add-BuildTask ValidateRequirements {
# this setting comes from the *.Settings.ps1
Write-Build White " Verifying at least PowerShell $script:requiredPSVersion..."
Assert-Build ($PSVersionTable.PSVersion -ge $script:requiredPSVersion) "At least Powershell $script:requiredPSVersion is required for this build to function properly"
Write-Build Green ' ...Verification Complete!'
} #ValidateRequirements
# Synopsis: Import the current module manifest file for processing
Add-BuildTask TestModuleManifest -Before ImportModuleManifest {
Write-Build White ' Running module manifest tests...'
Assert-Build (Test-Path $script:ModuleManifestFile) 'Unable to locate the module manifest file.'
Test-ModuleManifest -Path $script:ModuleManifestFile
Assert-Build (Test-ManifestBool -Path $script:ModuleManifestFile) 'Module Manifest test did not pass verification.'
Write-Build Green ' ...Module Manifest Verification Complete!'
} #f5b33218-bde4-4028-b2a1-9c206f089503
# Synopsis: Load the module project
Add-BuildTask ImportModuleManifest {
Write-Build White ' Attempting to load the project module.'
try {
Import-Module $script:ModuleManifestFile -Force -PassThru -ErrorAction Stop
} catch {
Write-Build Red $_
throw "Unable to load the project module"
}
Write-Build Green " ...$script:ModuleName imported successfully"
}
#Synopsis: Clean and reset Artifacts/Archive Directory
Add-BuildTask Clean {
Write-Build White ' Clean up our Artifacts/Archive directory...'
$null = Remove-Item $script:ArtifactsPath -Force -Recurse -ErrorAction 0
$null = New-Item $script:ArtifactsPath -ItemType:Directory
$null = Remove-Item $script:ArchivePath -Force -Recurse -ErrorAction 0
$null = New-Item $script:ArchivePath -ItemType:Directory
Write-Build Green ' ...Clean Complete!'
} #Clean
#Synopsis: Invokes PSScriptAnalyzer against the Module source path
Add-BuildTask Analyze {
$scriptAnalyzerParams = @{
Path = $script:ModuleSourcePath
Setting = 'PSScriptAnalyzerSettings.psd1'
Recurse = $true
Verbose = $false
}
Write-Build White ' Performing Module ScriptAnalyzer checks...'
$scriptAnalyzerResults = Invoke-ScriptAnalyzer @scriptAnalyzerParams
if ($scriptAnalyzerResults) {
$scriptAnalyzerResults | Format-Table
throw ' One or more PSScriptAnalyzer errors/warnings where found.'
} else {
Write-Build Green ' ...Module Analyze Complete!'
}
} #Analyze
#Synopsis: Invokes Script Analyzer against the Tests path if it exists
Add-BuildTask AnalyzeTests -After Analyze {
if (Test-Path -Path $script:TestsPath) {
$scriptAnalyzerParams = @{
Path = $script:TestsPath
Setting = 'PSScriptAnalyzerSettings.psd1'
ExcludeRule = 'PSUseDeclaredVarsMoreThanAssignments'
Recurse = $true
Verbose = $false
}
Write-Build White ' Performing Test ScriptAnalyzer checks...'
$scriptAnalyzerResults = Invoke-ScriptAnalyzer @scriptAnalyzerParams
if ($scriptAnalyzerResults) {
$scriptAnalyzerResults | Format-Table
throw ' One or more PSScriptAnalyzer errors/warnings where found.'
} else {
Write-Build Green ' ...Test Analyze Complete!'
}
}
} #AnalyzeTests
#Synopsis: Analyze scripts to verify if they adhere to desired coding format (Stroustrup / OTBS / Allman)
Add-BuildTask FormattingCheck {
$scriptAnalyzerParams = @{
Setting = 'CodeFormattingOTBS'
ExcludeRule = 'PSUseConsistentWhitespace'
Recurse = $true
Verbose = $false
}
Write-Build White " Performing script formatting checks... $($script:ModuleSourcePath)"
$publicPath = Join-Path $script:ModuleSourcePath 'Public'
$privatePath = Join-Path $script:ModuleSourcePath 'Private'
$scriptAnalyzerResults = Invoke-ScriptAnalyzer -Path "$publicPath" @scriptAnalyzerParams
$scriptAnalyzerResults += Invoke-ScriptAnalyzer -Path "$privatePath" @scriptAnalyzerParams
if ($scriptAnalyzerResults) {
$scriptAnalyzerResults | Format-Table
throw ' PSScriptAnalyzer code formatting check did not adhere to {0} standards' -f $scriptAnalyzerParams.Setting
} else {
Write-Build Green ' ...Formatting Analyze Complete!'
}
} #FormattingCheck
#Synopsis: Invokes all Pester Unit Tests in the Tests\Unit folder (if it exists)
Add-BuildTask Test {
Write-Build White " Importing desired Pester version. Min: $script:MinPesterVersion Max: $script:MaxPesterVersion"
$pesterAvailable = Get-Module -Name Pester -ListAvailable -ErrorAction 'Stop'
if ($pesterAvailable -and ($pesterAvailable.Version -ge $script:MinPesterVersion -and $pesterAvailable.Version -le $script:MaxPesterVersion)) {
Write-Build Gray ' Pester already loaded and within desired version range. Skipping import.'
} else {
Write-Build Gray ' Pester not loaded or not within desired version range. Importing desired version.'
Remove-Module -Name Pester -Force -ErrorAction SilentlyContinue # there are instances where some containers have Pester already in the session
Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop'
}
$codeCovPath = "$script:ArtifactsPath\ccReport\"
$testOutPutPath = "$script:ArtifactsPath\testOutput\"
if (-not(Test-Path $codeCovPath)) {
New-Item -Path $codeCovPath -ItemType Directory | Out-Null
}
if (-not(Test-Path $testOutPutPath)) {
New-Item -Path $testOutPutPath -ItemType Directory | Out-Null
}
if (Test-Path -Path $script:UnitTestsPath) {
$pesterConfiguration = New-PesterConfiguration
$pesterConfiguration.run.Path = $script:UnitTestsPath
$pesterConfiguration.Run.PassThru = $true
$pesterConfiguration.Run.Exit = $false
$pesterConfiguration.CodeCoverage.Enabled = $true
$pesterConfiguration.CodeCoverage.Path = "..\..\..\$ModuleName\*\*.ps1"
$pesterConfiguration.CodeCoverage.CoveragePercentTarget = $script:coverageThreshold
$pesterConfiguration.CodeCoverage.OutputPath = "$codeCovPath\CodeCoverage.xml"
$pesterConfiguration.CodeCoverage.OutputFormat = 'JaCoCo'
$pesterConfiguration.TestResult.Enabled = $true
$pesterConfiguration.TestResult.OutputPath = "$testOutPutPath\PesterTests.xml"
$pesterConfiguration.TestResult.OutputFormat = $script:testOutputFormat
$pesterConfiguration.Output.Verbosity = 'Detailed'
Write-Build White ' Performing Pester Unit Tests...'
# Publish Test Results
$testResults = Invoke-Pester -Configuration $pesterConfiguration
# This will output a nice json for each failed test (if running in CodeBuild)
if ($env:CODEBUILD_BUILD_ARN) {
$testResults.TestResult | ForEach-Object {
if ($_.Result -ne 'Passed') {
ConvertTo-Json -InputObject $_ -Compress
}
}
}
$numberFails = $testResults.FailedCount
Assert-Build($numberFails -eq 0) ('Failed "{0}" unit tests.' -f $numberFails)
Write-Build Gray (' ...CODE COVERAGE - CommandsExecutedCount: {0}' -f $testResults.CodeCoverage.CommandsExecutedCount)
Write-Build Gray (' ...CODE COVERAGE - CommandsAnalyzedCount: {0}' -f $testResults.CodeCoverage.CommandsAnalyzedCount)
if ($testResults.CodeCoverage.NumberOfCommandsExecuted -ne 0) {
$coveragePercent = '{0:N2}' -f ($testResults.CodeCoverage.CommandsExecutedCount / $testResults.CodeCoverage.CommandsAnalyzedCount * 100)
<#
if ($testResults.CodeCoverage.NumberOfCommandsMissed -gt 0) {
'Failed to analyze "{0}" commands' -f $testResults.CodeCoverage.NumberOfCommandsMissed
}
Write-Host "PowerShell Commands not tested:`n$(ConvertTo-Json -InputObject $testResults.CodeCoverage.MissedCommands)"
#>
if ([Int]$coveragePercent -lt $coverageThreshold) {
throw ('Failed to meet code coverage threshold of {0}% with only {1}% coverage' -f $coverageThreshold, $coveragePercent)
} else {
Write-Build Cyan " $('Covered {0}% of {1} analyzed commands in {2} files.' -f $coveragePercent,$testResults.CodeCoverage.CommandsAnalyzedCount,$testResults.CodeCoverage.FilesAnalyzedCount)"
Write-Build Green ' ...Pester Unit Tests Complete!'
}
} else {
# account for new module build condition
Write-Build Yellow ' Code coverage check skipped. No commands to execute...'
}
}
} #Test
#Synopsis: Used primarily during active development to generate xml file to graphically display code coverage in VSCode using Coverage Gutters
Add-BuildTask DevCC {
Write-Build White ' Generating code coverage report at root...'
Write-Build White " Importing desired Pester version. Min: $script:MinPesterVersion Max: $script:MaxPesterVersion"
$pesterAvailable = Get-Module -Name Pester -ListAvailable -ErrorAction 'Stop'
if ($pesterAvailable -and ($pesterAvailable.Version -ge $script:MinPesterVersion -and $pesterAvailable.Version -le $script:MaxPesterVersion)) {
Write-Build Gray ' Pester already loaded and within desired version range. Skipping import.'
} else {
Write-Build Gray ' Pester not loaded or not within desired version range. Importing desired version.'
Remove-Module -Name Pester -Force -ErrorAction SilentlyContinue # there are instances where some containers have Pester already in the session
Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop'
}
$pesterConfiguration = New-PesterConfiguration
$pesterConfiguration.run.Path = $script:UnitTestsPath
$pesterConfiguration.CodeCoverage.Enabled = $true
$pesterConfiguration.CodeCoverage.Path = "$PSScriptRoot\$ModuleName\*\*.ps1"
$pesterConfiguration.CodeCoverage.CoveragePercentTarget = $script:coverageThreshold
$pesterConfiguration.CodeCoverage.OutputPath = '..\..\..\cov.xml'
$pesterConfiguration.CodeCoverage.OutputFormat = 'CoverageGutters'
Invoke-Pester -Configuration $pesterConfiguration
Write-Build Green ' ...Code Coverage report generated!'
} #DevCC
# Synopsis: Build help for module
Add-BuildTask CreateHelpStart {
Write-Build White ' Performing all help related actions.'
Write-Build Gray ' Importing platyPS v0.12.0 ...'
Import-Module platyPS -RequiredVersion 0.12.0 -ErrorAction Stop
Write-Build Gray ' ...platyPS imported successfully.'
} #CreateHelpStart
# Synopsis: Build markdown help files for module and fail if help information is missing
Add-BuildTask CreateMarkdownHelp -After CreateHelpStart {
$ModulePage = "$script:ArtifactsPath\docs\$($ModuleName).md"
$markdownParams = @{
Module = $ModuleName
OutputFolder = "$script:ArtifactsPath\docs\"
Force = $true
WithModulePage = $true
Locale = 'en-US'
FwLink = "NA"
HelpVersion = $script:ModuleVersion
}
Write-Build Gray ' Generating markdown files...'
$null = New-MarkdownHelp @markdownParams
Write-Build Gray ' ...Markdown generation completed.'
Write-Build Gray ' Replacing markdown elements...'
# Replace multi-line EXAMPLES
$OutputDir = "$script:ArtifactsPath\docs\"
$OutputDir | Get-ChildItem -File | ForEach-Object {
# fix formatting in multiline examples
$content = Get-Content $_.FullName -Raw
$newContent = $content -replace '(## EXAMPLE [^`]+?```\r\n[^`\r\n]+?\r\n)(```\r\n\r\n)([^#]+?\r\n)(\r\n)([^#]+)(#)', '$1$3$2$4$5$6'
if ($newContent -ne $content) {
Set-Content -Path $_.FullName -Value $newContent -Force
}
}
# Replace each missing element we need for a proper generic module page .md file
$ModulePageFileContent = Get-Content -Raw $ModulePage
$ModulePageFileContent = $ModulePageFileContent -replace '{{Manually Enter Description Here}}', $script:ModuleDescription
$script:FunctionsToExport | ForEach-Object {
Write-Build DarkGray " Updating definition for the following function: $($_)"
$TextToReplace = "{{Manually Enter $($_) Description Here}}"
$ReplacementText = (Get-Help -Detailed $_).Synopsis
$ModulePageFileContent = $ModulePageFileContent -replace $TextToReplace, $ReplacementText
}
$ModulePageFileContent | Out-File $ModulePage -Force -Encoding:utf8
Write-Build Gray ' ...Markdown replacements complete.'
Write-Build Gray ' Verifying GUID...'
$MissingGUID = Select-String -Path "$script:ArtifactsPath\docs\*.md" -Pattern "(00000000-0000-0000-0000-000000000000)"
if ($MissingGUID.Count -gt 0) {
Write-Build Yellow ' The documentation that got generated resulted in a generic GUID. Check the GUID entry of your module manifest.'
throw 'Missing GUID. Please review and rebuild.'
}
Write-Build Gray ' Checking for missing documentation in md files...'
$MissingDocumentation = Select-String -Path "$script:ArtifactsPath\docs\*.md" -Pattern "({{.*}})"
if ($MissingDocumentation.Count -gt 0) {
Write-Build Yellow ' The documentation that got generated resulted in missing sections which should be filled out.'
Write-Build Yellow ' Please review the following sections in your comment based help, fill out missing information and rerun this build:'
Write-Build Yellow ' (Note: This can happen if the .EXTERNALHELP CBH is defined for a function before running this build.)'
Write-Build Yellow " Path of files with issues: $script:ArtifactsPath\docs\"
$MissingDocumentation | Select-Object FileName, LineNumber, Line | Format-Table -AutoSize
throw 'Missing documentation. Please review and rebuild.'
}
Write-Build Gray ' Checking for missing SYNOPSIS in md files...'
$fSynopsisOutput = @()
$synopsisEval = Select-String -Path "$script:ArtifactsPath\docs\*.md" -Pattern "^## SYNOPSIS$" -Context 0, 1
$synopsisEval | ForEach-Object {
$chAC = $_.Context.DisplayPostContext.ToCharArray()
if ($null -eq $chAC) {
$fSynopsisOutput += $_.FileName
}
}
if ($fSynopsisOutput) {
Write-Build Yellow " The following files are missing SYNOPSIS:"
$fSynopsisOutput
throw 'SYNOPSIS information missing. Please review.'
}
Write-Build Gray ' ...Markdown generation complete.'
} #CreateMarkdownHelp
# Synopsis: Build the external xml help file from markdown help files with PlatyPS
Add-BuildTask CreateExternalHelp -After CreateMarkdownHelp {
Write-Build Gray ' Creating external xml help file...'
$null = New-ExternalHelp "$script:ArtifactsPath\docs" -OutputPath "$script:ArtifactsPath\en-US\" -Force
Write-Build Gray ' ...External xml help file created!'
} #CreateExternalHelp
Add-BuildTask CreateHelpComplete -After CreateExternalHelp {
Write-Build Green ' ...CreateHelp Complete!'
} #CreateHelpStart
# Synopsis: Copies module assets to Artifacts folder
Add-BuildTask AssetCopy -Before Build {
Write-Build Gray ' Copying assets to Artifacts...'
Copy-Item -Path "$script:ModuleSourcePath\*" -Destination $script:ArtifactsPath -Exclude *.psd1, *.psm1 -Recurse -ErrorAction Stop
Write-Build Gray ' ...Assets copy complete.'
} #AssetCopy
# Synopsis: Builds the Module to the Artifacts folder
Add-BuildTask Build {
Write-Build White ' Performing Module Build'
Write-Build Gray ' Copying manifest file to Artifacts...'
Copy-Item -Path $script:ModuleManifestFile -Destination $script:ArtifactsPath -Recurse -ErrorAction Stop
Copy-Item -Path $script:BuildModuleRootFile -Destination $script:ArtifactsPath -Recurse -ErrorAction Stop
#Copy-Item -Path $script:ModuleSourcePath\bin -Destination $script:ArtifactsPath -Recurse -ErrorAction Stop
Write-Build Gray ' ...manifest copy complete.'
Write-Build Gray ' Merging Public and Private functions to one module file...'
#$private = "$script:ModuleSourcePath\Private"
# $scriptContent = [System.Text.StringBuilder]::new()
#$powerShellScripts = Get-ChildItem -Path $script:ModuleSourcePath -Filter '*.ps1' -Recurse
# $powerShellScripts = Get-ChildItem -Path $script:ArtifactsPath -Recurse | Where-Object { $_.Name -match '^*.ps1$' }
# foreach ($script in $powerShellScripts) {
# $null = $scriptContent.Append((Get-Content -Path $script.FullName -Raw))
# $null = $scriptContent.AppendLine('')
# $null = $scriptContent.AppendLine('')
# }
# $scriptContent.ToString() | Out-File -FilePath $script:BuildModuleRootFile -Encoding utf8 -Force
Write-Build Gray ' ...Module creation complete.'
Write-Build Gray ' Cleaning up leftover artifacts...'
#cleanup artifacts that are no longer required
# if (Test-Path "$script:ArtifactsPath\Public") {
# Remove-Item "$script:ArtifactsPath\Public" -Recurse -Force -ErrorAction Stop
# }
# if (Test-Path "$script:ArtifactsPath\Private") {
# Remove-Item "$script:ArtifactsPath\Private" -Recurse -Force -ErrorAction Stop
# }
if (Test-Path "$script:ArtifactsPath\Imports.ps1") {
Remove-Item "$script:ArtifactsPath\Imports.ps1" -Force -ErrorAction SilentlyContinue
}
if (Test-Path "$script:ArtifactsPath\docs") {
#here we update the parent level docs. If you would prefer not to update them, comment out this section.
Write-Build Gray ' Overwriting docs output...'
if (-not (Test-Path '..\docs\')) {
New-Item -Path '..\docs\' -ItemType Directory -Force | Out-Null
}
Move-Item "$script:ArtifactsPath\docs\*.md" -Destination '..\docs\' -Force
Remove-Item "$script:ArtifactsPath\docs" -Recurse -Force -ErrorAction Stop
Write-Build Gray ' ...Docs output completed.'
}
Write-Build Green ' ...Build Complete!'
} #Build
#Synopsis: Invokes all Pester Integration Tests in the Tests\Integration folder (if it exists)
Add-BuildTask IntegrationTest {
if (Test-Path -Path $script:IntegrationTestsPath) {
Write-Build White " Importing desired Pester version. Min: $script:MinPesterVersion Max: $script:MaxPesterVersion"
$pesterAvailable = Get-Module -Name Pester -ListAvailable -ErrorAction 'Stop'
if ($pesterAvailable -and ($pesterAvailable.Version -ge $script:MinPesterVersion -and $pesterAvailable.Version -le $script:MaxPesterVersion)) {
Write-Build Gray ' Pester already loaded and within desired version range. Skipping import.'
} else {
Write-Build Gray ' Pester not loaded or not within desired version range. Importing desired version.'
Remove-Module -Name Pester -Force -ErrorAction SilentlyContinue # there are instances where some containers have Pester already in the session
Import-Module -Name Pester -MinimumVersion $script:MinPesterVersion -MaximumVersion $script:MaxPesterVersion -ErrorAction 'Stop'
}
Write-Build White " Performing Pester Integration Tests in $($invokePesterParams.path)"
$pesterConfiguration = New-PesterConfiguration
$pesterConfiguration.run.Path = $script:IntegrationTestsPath
$pesterConfiguration.Run.PassThru = $true
$pesterConfiguration.Run.Exit = $false
$pesterConfiguration.CodeCoverage.Enabled = $false
$pesterConfiguration.TestResult.Enabled = $false
$pesterConfiguration.Output.Verbosity = 'Detailed'
$testResults = Invoke-Pester -Configuration $pesterConfiguration
# This will output a nice json for each failed test (if running in CodeBuild)
if ($env:CODEBUILD_BUILD_ARN) {
$testResults.TestResult | ForEach-Object {
if ($_.Result -ne 'Passed') {
ConvertTo-Json -InputObject $_ -Compress
}
}
}
$numberFails = $testResults.FailedCount
Assert-Build($numberFails -eq 0) ('Failed "{0}" unit tests.' -f $numberFails)
Write-Build Green ' ...Pester Integration Tests Complete!'
}
} #IntegrationTest
#Synopsis: Creates an archive of the built Module
Add-BuildTask Archive {
Write-Build White ' Performing Archive...'
$archivePath = Join-Path -Path $BuildRoot -ChildPath 'Archive'
if (Test-Path -Path $archivePath) {
$null = Remove-Item -Path $archivePath -Recurse -Force
}
$null = New-Item -Path $archivePath -ItemType Directory -Force
$zipFileName = '{0}_{1}_{2}.{3}.zip' -f $script:ModuleName, $script:ModuleVersion, ([DateTime]::UtcNow.ToString("yyyyMMdd")), ([DateTime]::UtcNow.ToString("hhmmss"))
$zipFile = Join-Path -Path $archivePath -ChildPath $zipFileName
if ($PSEdition -eq 'Desktop') {
Add-Type -AssemblyName 'System.IO.Compression.FileSystem'
}
[System.IO.Compression.ZipFile]::CreateFromDirectory($script:ArtifactsPath, $zipFile)
Write-Build Green ' ...Archive Complete!'
} #Archive
#Synopsis: Installs the module into the current session.
Add-BuildTask Install {
Write-Build White ' Installing Module...'
$module = Join-Path $script:ArtifactsPath "$($script:ModuleName).psd1"
Write-Build Gray ' Removing Previously installed instance of this module, if found.'
Remove-Module $ModuleName -Force -ErrorAction SilentlyContinue
Import-Module $module -Force
Write-Build Green ' ...Installation Complete!'
}