forked from PlagueHO/LoopbackAdapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpsakefile.ps1
More file actions
561 lines (476 loc) · 18.7 KB
/
Copy pathpsakefile.ps1
File metadata and controls
561 lines (476 loc) · 18.7 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
# PSake makes variables declared here available in other scriptblocks
# Init some things
Properties {
# Prepare the folder variables
$ProjectRoot = $ENV:BHProjectPath
if (-not $ProjectRoot)
{
$ProjectRoot = $PSScriptRoot
}
$ModuleName = 'LoopbackAdapter'
$Timestamp = Get-Date -uformat "%Y%m%d-%H%M%S"
$PSVersion = $PSVersionTable.PSVersion.Major
$separator = '----------------------------------------------------------------------'
}
Task Default -Depends Test, Build
Task Init {
Set-Location -Path $ProjectRoot
# Install any dependencies required for the Init stage
Invoke-PSDepend `
-Path $PSScriptRoot `
-Force `
-Import `
-Install `
-Tags 'Init'
Set-BuildEnvironment -Force
$separator
'Build System Details:'
Get-Item -Path ENV:BH*
"`n"
$separator
'Other Environment Variables:'
Get-ChildItem -Path ENV:
"`n"
$separator
'PowerShell Details:'
$PSVersionTable
"`n"
}
Task PrepareTest -Depends Init {
# Install any dependencies required for testing
Invoke-PSDepend `
-Path $PSScriptRoot `
-Force `
-Import `
-Install `
-Tags 'Test'
}
Task Test -Depends UnitTest, IntegrationTest
Task UnitTest -Depends Init, PrepareTest {
$separator
# Execute tests
$testScriptsPath = Join-Path -Path $ProjectRoot -ChildPath 'test\Unit'
$testResultsFile = Join-Path -Path $testScriptsPath -ChildPath 'TestResults.unit.xml'
$codeCoverageFile = Join-Path -Path $testScriptsPath -ChildPath 'CodeCoverage.xml'
$codeCoverageSource = Get-ChildItem -Path (Join-Path -Path $ProjectRoot -ChildPath 'src\lib\*.ps1') -Recurse
$testResults = Invoke-Pester `
-Script $testScriptsPath `
-OutputFormat NUnitXml `
-OutputFile $testResultsFile `
-PassThru `
-ExcludeTag Incomplete `
-CodeCoverage $codeCoverageSource `
-CodeCoverageOutputFile $codeCoverageFile `
-CodeCoverageOutputFileFormat JaCoCo
# Prepare and uploade code coverage
if ($testResults.CodeCoverage)
{
# Only bother generating code coverage in AppVeyor
if ($ENV:BHBuildSystem -eq 'AppVeyor')
{
'Preparing CodeCoverage'
Import-Module `
-Name (Join-Path -Path $ProjectRoot -ChildPath '.codecovio\CodeCovio.psm1')
$jsonPath = Export-CodeCovIoJson `
-CodeCoverage $testResults.CodeCoverage `
-RepoRoot $ProjectRoot
'Uploading CodeCoverage to CodeCov.io'
try
{
Invoke-UploadCoveCoveIoReport -Path $jsonPath
}
catch
{
# CodeCov currently reports an error when uploading
# This is not fatal and can be ignored
Write-Warning -Message $_
}
}
}
else
{
Write-Warning -Message 'Could not create CodeCov.io report because pester results object did not contain a CodeCoverage object'
}
# Upload tests
if ($ENV:BHBuildSystem -eq 'AppVeyor')
{
'Publishing test results to AppVeyor'
(New-Object 'System.Net.WebClient').UploadFile(
"https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)",
(Resolve-Path $testResultsFile))
"Publishing test results to AppVeyor as Artifact"
Push-AppveyorArtifact $testResultsFile
if ($testResults.FailedCount -gt 0)
{
throw "$($testResults.FailedCount) unit tests failed."
}
}
else
{
if ($testResults.FailedCount -gt 0)
{
Write-Error -Exception "$($testResults.FailedCount) unit tests failed."
}
}
"`n"
}
Task IntegrationTest -Depends Init, PrepareTest {
$separator
# Execute tests
$testScriptsPath = Join-Path -Path $ProjectRoot -ChildPath 'test\Integration'
$testResultsFile = Join-Path -Path $testScriptsPath -ChildPath 'TestResults.integration.xml'
$testResults = Invoke-Pester `
-Script $testScriptsPath `
-OutputFormat NUnitXml `
-OutputFile $testResultsFile `
-PassThru `
-ExcludeTag Incomplete
# Upload tests
if ($ENV:BHBuildSystem -eq 'AppVeyor')
{
'Publishing test results to AppVeyor'
(New-Object 'System.Net.WebClient').UploadFile(
"https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)",
(Resolve-Path $testResultsFile))
"Publishing test results to AppVeyor as Artifact"
Push-AppveyorArtifact $testResultsFile
if ($testResults.FailedCount -gt 0)
{
throw "$($testResults.FailedCount) integration tests failed."
}
}
else
{
if ($testResults.FailedCount -gt 0)
{
Write-Error -Exception "$($testResults.FailedCount) integration tests failed."
}
}
"`n"
}
Task Build -Depends Init {
$separator
# Install any dependencies required for the Build stage
Invoke-PSDepend `
-Path $PSScriptRoot `
-Force `
-Import `
-Install `
-Tags 'Build'
# Generate the next version by adding the build system build number to the manifest version
$manifestPath = Join-Path -Path $ProjectRoot -ChildPath "src/$ModuleName.psd1"
$newVersion = Get-VersionNumber `
-ManifestPath $manifestPath `
-Build $ENV:BHBuildNumber
if ($ENV:BHBuildSystem -eq 'AppVeyor')
{
# Update AppVeyor build version number
Update-AppveyorBuild -Version $newVersion
}
# Determine the folder names for staging the module
$StagingFolder = Join-Path -Path $ProjectRoot -ChildPath 'staging'
$ModuleFolder = Join-Path -Path $StagingFolder -ChildPath $ModuleName
# Determine the folder names for staging the module
$versionFolder = Join-Path -Path $ModuleFolder -ChildPath $newVersion
# Stage the module
$null = New-Item -Path $StagingFolder -Type directory -ErrorAction SilentlyContinue
$null = New-Item -Path $ModuleFolder -Type directory -ErrorAction SilentlyContinue
Remove-Item -Path $versionFolder -Recurse -Force -ErrorAction SilentlyContinue
$null = New-Item -Path $versionFolder -Type directory
# Populate Version Folder
$null = Copy-Item -Path (Join-Path -Path $ProjectRoot -ChildPath "src/$ModuleName.psm1") -Destination $versionFolder
$null = Copy-Item -Path (Join-Path -Path $ProjectRoot -ChildPath 'src/en-US') -Destination $versionFolder -Recurse
$null = Copy-Item -Path (Join-Path -Path $ProjectRoot -ChildPath 'LICENSE') -Destination $versionFolder
$null = Copy-Item -Path (Join-Path -Path $ProjectRoot -ChildPath 'README.md') -Destination $versionFolder
$null = Copy-Item -Path (Join-Path -Path $ProjectRoot -ChildPath 'CHANGELOG.md') -Destination $versionFolder
$null = Copy-Item -Path (Join-Path -Path $ProjectRoot -ChildPath 'RELEASENOTES.md') -Destination $versionFolder
# Load the Libs files into the PSM1
$libFiles = Get-ChildItem `
-Path (Join-Path -Path $ProjectRoot -ChildPath 'src/lib') `
-Include '*.ps1' `
-Recurse
# Assemble all the libs content into a single string
$libFilesStringBuilder = [System.Text.StringBuilder]::new()
foreach ($libFile in $libFiles)
{
$libContent = Get-Content -Path $libFile -Raw
$null = $libFilesStringBuilder.AppendLine($libContent)
}
<#
Load the PSM1 file into an array of lines and step through each line
adding it to a string builder if the line is not part of the ImportFunctions
Region. Then add the content of the $libFilesStringBuilder string builder
immediately following the end of the region.
#>
$modulePath = Join-Path -Path $versionFolder -ChildPath "$ModuleName.psm1"
$moduleContent = Get-Content -Path $modulePath
$moduleStringBuilder = [System.Text.StringBuilder]::new()
$importFunctionsRegionFound = $false
foreach ($moduleLine in $moduleContent)
{
if ($importFunctionsRegionFound)
{
if ($moduleLine -eq '#endregion')
{
$null = $moduleStringBuilder.AppendLine('#region Functions')
$null = $moduleStringBuilder.AppendLine($libFilesStringBuilder)
$null = $moduleStringBuilder.AppendLine('#endregion')
$importFunctionsRegionFound = $false
}
}
else
{
if ($moduleLine -eq '#region ImportFunctions')
{
$importFunctionsRegionFound = $true
}
else
{
$null = $moduleStringBuilder.AppendLine($moduleLine)
}
}
}
Set-Content -Path $modulePath -Value $moduleStringBuilder -Force
# Prepare external help
'Building external help file'
New-ExternalHelp `
-Path (Join-Path -Path $ProjectRoot -ChildPath 'docs\') `
-OutputPath $versionFolder `
-Force
# Create the module manifest in the staging folder
'Updating module manifest'
$stagedManifestPath = Join-Path -Path $versionFolder -ChildPath "$ModuleName.psd1"
$tempManifestPath = Join-Path -Path $ENV:Temp -ChildPath "$ModuleName.psd1"
Import-LocalizedData `
-BindingVariable 'stagedManifestContent' `
-FileName "$ModuleName.psd1" `
-BaseDirectory (Join-Path -Path $ProjectRoot -ChildPath 'src')
$stagedManifestContent.ModuleVersion = $newVersion
$stagedManifestContent.Copyright = "(c) $((Get-Date).Year) Daniel Scott-Raynsford. All rights reserved."
# Extract the PrivateData values and remove it because it can not be splatted
'LicenseUri','Tags','ProjectUri','IconUri','ReleaseNotes' | Foreach-Object -Process {
$privateDataValue = $stagedManifestContent.PrivateData.PSData.$_
if ($privateDataValue)
{
$null = $stagedManifestContent.Add($_, $privateDataValue)
}
}
$stagedManifestContent.ReleaseNotes = $stagedManifestContent.ReleaseNotes -replace "## What is New in $ModuleName Unreleased", "## What is New in $ModuleName $newVersion"
$stagedManifestContent.Remove('PrivateData')
# Create the module manifest file
New-ModuleManifest `
-Path $tempManifestPath `
@stagedManifestContent
# Make sure the manifest is encoded as UTF8
'Convert manifest to UTF8'
$temporaryManifestContent = Get-Content -Path $tempManifestPath -Raw
$utf8NoBomEncoding = New-Object -TypeName System.Text.UTF8Encoding -ArgumentList ($false)
[System.IO.File]::WriteAllLines($stagedManifestPath, $temporaryManifestContent, $utf8NoBomEncoding)
# Remove the temporary manifest
$null = Remove-Item -Path $tempManifestPath -Force
# Validate the module manifest
if (-not (Test-ModuleManifest -Path $stagedManifestPath))
{
throw "The generated module manifest '$stagedManifestPath' was invalid"
}
# Set the new version number in the staged CHANGELOG.md
'Updating CHANGELOG.MD'
$stagedChangeLogPath = Join-Path -Path $versionFolder -ChildPath 'CHANGELOG.md'
$stagedChangeLogContent = Get-Content -Path $stagedChangeLogPath -Raw
$stagedChangeLogContent = $stagedChangeLogContent -replace '# Unreleased', "# $newVersion"
Set-Content -Path $stagedChangeLogPath -Value $stagedChangeLogContent -NoNewLine -Force
# Set the new version number in the staged RELEASENOTES.md
'Updating RELEASENOTES.MD'
$stagedReleaseNotesPath = Join-Path -Path $versionFolder -ChildPath 'RELEASENOTES.md'
$stagedReleaseNotesContent = Get-Content -Path $stagedReleaseNotesPath -Raw
$stagedReleaseNotesContent = $stagedReleaseNotesContent -replace "## What is New in $ModuleName Unreleased", "## What is New in $ModuleName $newVersion"
Set-Content -Path $stagedReleaseNotesPath -Value $stagedReleaseNotesContent -NoNewLine -Force
# Create zip artifact
$zipFileFolder = Join-Path `
-Path $StagingFolder `
-ChildPath 'zip'
$null = New-Item -Path $zipFileFolder -Type directory -ErrorAction SilentlyContinue
$zipFilePath = Join-Path `
-Path $zipFileFolder `
-ChildPath "${ENV:BHProjectName}_$newVersion.zip"
if (Test-Path -Path $zipFilePath)
{
$null = Remove-Item -Path $zipFilePath
}
$null = Add-Type -assemblyname System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory($ModuleFolder, $zipFilePath)
# Update the Git Repo if this is the master branch build in Azure Pipelines
if ($ENV:BHBuildSystem -eq 'Azure Pipelines')
{
if ($ENV:BHBranchName -eq 'master')
{
# This is a push to master so update GitHub with release info
'Beginning update to master branch with deployed information'
$commitMessage = $ENV:BHCommitMessage.TrimEnd()
"Commit to master branch triggered with commit message: '$commitMessage'"
if ($commitMessage -match '^Azure DevOps Deploy updating Version Number to [0-9/.]*')
{
# This was a deploy commit so no need to do anything
'Skipping update to master branch with deployed information because this was triggered by Azure DevOps Updating the Version Number'
}
else
{
# Pull the master branch, update the readme.md and manifest
Set-Location -Path $ProjectRoot
Invoke-Git -GitParameters @('config', '--global', 'credential.helper', 'store')
# Configure Azure DevOps to be able to Push back to GitHub
Add-Content `
-Path "$ENV:USERPROFILE\.git-credentials" `
-Value "https://$($ENV:githubRepoToken):x-oauth-basic@github.com`n"
Invoke-Git -GitParameters @('config', '--global', 'user.email', 'plagueho@gmail.com')
Invoke-Git -GitParameters @('config', '--global', 'user.name', 'Daniel Scott-Raynsford')
'Display list of Git Remotes'
Invoke-Git -GitParameters @('remote', '-v')
Invoke-Git -GitParameters @('checkout', '-f', 'master')
# Replace the manifest with the one that was published
'Updating files changed during deployment'
Copy-Item `
-Path $stagedManifestPath `
-Destination (Join-Path -Path $ProjectRoot -ChildPath 'src') `
-Force
Copy-Item `
-Path $stagedChangeLogPath `
-Destination $ProjectRoot `
-Force
Copy-Item `
-Path $stagedReleaseNotesPath `
-Destination $ProjectRoot `
-Force
'Adding updated module files to commit'
Invoke-Git -GitParameters @('add', '.')
"Creating new commit for 'Azure DevOps Deploy updating Version Number to $NewVersion'"
Invoke-Git -GitParameters @('commit', '-m', "Azure DevOps Deploy updating Version Number to $NewVersion")
"Adding $newVersion tag to Master"
Invoke-Git -GitParameters @('tag', '-a', '-m', $newVersion, $newVersion)
# Update the master branch
'Pushing deployment changes to Master'
Invoke-Git -GitParameters @('status')
Invoke-Git -GitParameters @('push')
# Merge the changes to the Master branch into the Dev branch
'Pushing deployment changes to Dev'
Invoke-Git -GitParameters @('checkout', '-f', 'dev')
Invoke-Git -GitParameters @('merge', 'origin/master')
Invoke-Git -GitParameters @('push')
}
}
else
{
"Skipping update to master branch with deployed information because branch is: '$ENV:BHBranchName'"
}
}
else
{
"Skipping update to master branch with deployed information because build system is: '$ENV:BHBuildSystem'"
}
"`n"
}
Task Deploy {
$separator
# Determine the folder name for the Module
$ModuleFolder = Join-Path -Path $ProjectRoot -ChildPath $ModuleName
# Install any dependencies required for the Deploy stage
Invoke-PSDepend `
-Path $PSScriptRoot `
-Force `
-Import `
-Install `
-Tags 'Deploy'
# Copy the module to the PSModulePath
$PSModulePath = ($ENV:PSModulePath -split ';')[0]
$destinationPath = Join-Path -Path $PSModulePath -ChildPath $ModuleName
"Copying Module from $ModuleFolder to $destinationPath"
Copy-Item `
-Path $ModuleFolder `
-Destination $destinationPath `
-Container `
-Recurse `
-Force
$installedModule = Get-Module -Name $ModuleName -ListAvailable
$versionNumber = $installedModule.Version |
Sort-Object -Descending |
Select-Object -First 1
if (-not $versionNumber)
{
Throw "$ModuleName Module could not be found after copying to $PSModulePath"
}
# This is a deploy from the staging folder
"Publishing $ModuleName Module version '$versionNumber' to PowerShell Gallery"
$null = Get-PackageProvider `
-Name NuGet `
-ForceBootstrap
Publish-Module `
-Name $ModuleName `
-RequiredVersion $versionNumber `
-NuGetApiKey $ENV:PowerShellGalleryApiKey `
-Confirm:$false
}
<#
.SYNOPSIS
Generate a new version number.
#>
function Get-VersionNumber
{
[CmdLetBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$ManifestPath,
[Parameter(Mandatory = $true)]
[System.String]
$Build
)
# Get version number from the existing manifest
$manifestContent = Get-Content -Path $ManifestPath -Raw
$regex = '(?<=ModuleVersion\s+=\s+'')(?<ModuleVersion>.*)(?='')'
$matches = @([regex]::matches($manifestContent, $regex, 'IgnoreCase'))
$version = $null
if ($matches)
{
$version = $matches[0].Value
}
# Determine the new version number
$versionArray = $version -split '\.'
$newVersion = ''
foreach ($ver in (0..2))
{
$sem = $versionArray[$ver]
if ([System.String]::IsNullOrEmpty($sem))
{
$sem = '0'
}
$newVersion += "$sem."
}
$newVersion += $Build
return $newVersion
}
<#
.SYNOPSIS
Safely execute a Git command.
#>
function Invoke-Git
{
[CmdLetBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String[]]
$GitParameters
)
try
{
"Executing 'git $($GitParameters -join ' ')'"
exec { & git $GitParameters }
}
catch
{
Write-Warning -Message $_
}
}