forked from jakkulabs/PowervRA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.psake.ps1
409 lines (303 loc) · 13.6 KB
/
build.psake.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
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
# --- Dot source build.settings.ps1
. $PSScriptRoot\build.settings.ps1
# --- Add any parameters from build.ps1
properties {
$CurrentVersion = [version](Get-Metadata -Path $env:BHPSModuleManifest)
if ($Increment) {
$StepVersion = [version](Step-Version $CurrentVersion -By $Increment)
}
}
# --- Define the build tasks
Task Default -depends Test
Task Test -depends Init, Analyze, TestHelp
Task Build -depends Test, UpdateModuleManifest, UpdateDocumentation, IncrementVersion, CommitChanges, CreateArtifact
Task Release -depends CreateArtifact, CreateGitHubRelease, PublishToPSGallery
Task Init {
Write-Output "Build System Details:"
foreach ($Item in (Get-Item -Path ENV:BH*)){
Write-Output "$($Item.Name): $($Item.Value)"
}
Write-Output "ScriptAnalyzerSeverityLevel: $($ScriptAnalysisFailBuildOnSeverityLevel)"
Write-Output "Current Module Version: $($CurrentVersion)"
Write-Output "Increment: $($Increment)"
}
##############
# Task: Test #
##############
Task Analyze {
$Results = Invoke-ScriptAnalyzer -Path $ENV:BHModulePath -Recurse -Settings $ScriptAnalyzerSettingsPath -Verbose:$VerbosePreference
$Results | Select-Object RuleName, Severity, ScriptName, Line, Message | Format-List
switch ($ScriptAnalysisFailBuildOnSeverityLevel) {
'None' {
return
}
'Error' {
Assert -conditionToCheck (
($Results | Where-Object Severity -eq 'Error').Count -eq 0
) -failureMessage 'One or more ScriptAnalyzer errors were found. Build cannot continue!'
}
'Warning' {
Assert -conditionToCheck (
($Results | Where-Object {
$_.Severity -eq 'Warning' -or $_.Severity -eq 'Error'
}).Count -eq 0) -failureMessage 'One or more ScriptAnalyzer warnings were found. Build cannot continue!'
}
default {
Assert -conditionToCheck ($analysisResult.Count -eq 0) -failureMessage 'One or more ScriptAnalyzer issues were found. Build cannot continue!'
}
}
}
Task TestHelp {
# --- Run Tests. Currently limited to help tests
$Timestamp = Get-date -uformat "%Y%m%d-%H%M%S"
$TestFile = "TestResults_PS$PSVersion`_$TimeStamp.xml"
$Parameters = @{
Script = "$ENV:BHProjectPath\tests\Test000-Module.Tests.ps1"
Tag = 'Help'
PassThru = $true
OutputFormat = 'NUnitXml'
OutputFile = "$ENV:BHProjectPath\$TestFile"
}
$TestResults = Invoke-Pester @Parameters
If ($ENV:BHBuildSystem -eq 'AppVeyor') {
"Uploading $ENV:BHProjectPath\$TestFile to AppVeyor"
"JobID: $env:APPVEYOR_JOB_ID"
(New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path "$ENV:BHProjectPath\$TestFile"))
}
Remove-Item "$ENV:BHProjectPath\$TestFile" -Force -ErrorAction SilentlyContinue
if ($TestResults.FailedCount -gt 0) {
Write-Error "Failed '$($TestResults.FailedCount)' tests, build failed"
}
}
###############
# Task: Build #
###############
Task UpdateModuleManifest {
$PublicFunctions = Get-ChildItem -Path "$($ENV:BHModulePath)\Functions\Public" -Filter "*.ps1" -Recurse | Sort-Object
$ExportFunctions = @()
foreach ($FunctionFile in $PublicFunctions) {
$AST = [System.Management.Automation.Language.Parser]::ParseFile($FunctionFile.FullName, [ref]$null, [ref]$null)
$Functions = $AST.FindAll({
# --- Only export functions that contain a "-" and do not start with "int"
$args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] -and `
$args[0].Name -match "-" -and `
!$args[0].Name.StartsWith("int")
},$true)
if ($Functions.Name) {
$ExportFunctions += $Functions.Name
}
}
Set-ModuleFunctions -Name $ENV:BHPSModuleManifest -FunctionsToExport $ExportFunctions -Verbose:$VerbosePreference
}
Task UpdateDocumentation {
if ($ENV:BHBranchName -eq "master") {
Write-Output "This task cannot be executed on the master branch. Skpping task"
}
Write-Output "Updating Markdown help"
$ModuleInfo = Import-Module $ENV:BHPSModuleManifest -Global -Force -PassThru
$FunctionsPath = "$DocsDirectory\functions"
Remove-Item -Path $FunctionsPath -Recurse -Force -ErrorAction SilentlyContinue
New-Item $FunctionsPath -ItemType Directory | Out-Null
$PlatyPSParameters = @{
Module = $ModuleName
OutputFolder = $FunctionsPath
NoMetadata = $true
}
New-MarkdownHelp @PlatyPSParameters -ErrorAction SilentlyContinue -Verbose:$VerbosePreference | Out-Null
# --- Ensure that index.md is present and up to date
Write-Output "Updating index.md"
Copy-Item -Path "$($PSScriptRoot)\README.md" -Destination "$($DocsDirectory)\index.md" -Force -Verbose:$VerbosePreference | Out-Null
# --- Update mkdocs.yml with new functions
Write-Output "Updating mkdocs.yml"
$Mkdocs = "$($PSScriptRoot)\mkdocs.yml"
$Functions = $ModuleInfo.ExportedCommands.Keys | ForEach-Object {" - $($_) : functions/$($_).md"}
$Template = @"
---
site_name: $($ModuleName)
repo_url: $($RepositoryUrl)
site_author: $($ModuleAuthor)
edit_uri: edit/master/docs/
theme: readthedocs
copyright: "PowervRA is licenced under the <a href='$($RepositoryUrl)/raw/master/LICENSE'>MIT license"
pages:
- 'Home' : 'index.md'
- 'Change log' : 'CHANGELOG.md'
- 'Build' : 'build.md'
- 'Functions':
$($Functions -join "`r`n")
"@
$Template | Set-Content -Path $Mkdocs -Force
}
Task IncrementVersion {
if ($ENV:BHBranchName -eq "master") {
Write-Output "This task cannot be executed on the master branch. Skpping task"
}
if (!$StepVersion) {
Write-Output "StepVersion not specified. Skipping task"
}
if ([version]$StepVersion -gt [version]$CurrentVersion) {
# --- Update module manifest version
Update-Metadata -Path $env:BHPSModuleManifest -PropertyName ModuleVersion -Value $StepVersion
Write-Output "Module version updated to $($StepVersion)"
# --- Update appveyor build version
$AppveyorYMLPath = "$($PSScriptRoot)\appveyor.yml"
$AppveyorVersion = "$($StepVersion).{build}"
$NewAppveyorYML = Get-Content -Path $AppveyorYMLPath | ForEach-Object { $_ -replace '^version: .+$', "version: $($AppveyorVersion)";}
$NewAppveyorYML | Set-Content -Path $AppveyorYMLPath -Force
Write-Output "Appveyor build version set to $($AppveyorVersion)"
# --- Update change log
$ReleaseNotes = "$ENV:BHProjectPath\RELEASE.md"
$ChangeLog = "$DocsDirectory\CHANGELOG.md"
$Header = "# Version $($StepVersion)`r"
$Header, (Get-Content -Path $ReleaseNotes -Raw), "`r", (Get-Content $ChangeLog -Raw) | Set-Content $ChangeLog
}
}
Task CommitChanges {
if ($ENV:BHBuildSystem -eq "Unknown"){
Write-Output "Could not detect build system. Skipping task"
return
}
if ($ENV:APPVEYOR_REPO_PROVIDER -notlike 'github') {
Write-Output "Repo provider '$ENV:APPVEYOR_REPO_PROVIDER'. Skipping task"
return
}
if ($ENV:BHBranchName -eq "master") {
Write-Output "This task cannot be executed on the master branch. Skpping task"
}
If ($ENV:BHBuildSystem -eq 'AppVeyor') {
Write-Output "git config --global credential.helper store"
cmd /c "git config --global credential.helper store 2>&1"
Add-Content "$ENV:USERPROFILE\.git-credentials" "https://$($ENV:gh_token):[email protected]`n"
Write-Output "git config --global user.email"
cmd /c "git config --global user.email ""$($ENV:BHProjectName)-$($ENV:BHBranchName)-$($ENV:BHBuildSystem)@jakkulabs.com"" 2>&1"
Write-Output "git config --global user.name"
cmd /c "git config --global user.name ""AppVeyor"" 2>&1"
Write-Output "git config --global core.autocrlf true"
cmd /c "git config --global core.autocrlf true 2>&1"
}
Write-Output "git checkout $ENV:BHBranchName"
cmd /c "git checkout $ENV:BHBranchName 2>&1"
Write-Output "git pull recent commits from $ENV:BHBranchName"
cmd /c "git pull 2>&1"
Write-Output "git add -A"
cmd /c "git add -A 2>&1"
Write-Output "git commit -m"
cmd /c "git commit -m ""AppVeyor post-build commit [ci skip]"" 2>&1"
Write-Output "git status"
cmd /c "git status 2>&1"
Write-Output "git push origin $ENV:BHBranchName"
cmd /c "git push origin $ENV:BHBranchName 2>&1"
}
#################
# Task: Release #
#################
Task CreateArtifact {
# --- Create release directory
Write-Output "Creating Release Directory:"
$ReleaseDirectory = New-Item -Path "$($ENV:BHProjectPath)\Release\$($ModuleName)" -ItemType Directory -Force
Write-Output " - $($ReleaseDirectory.FullName)"
# --- Copy accross the updated psd1 file
Write-Verbose "Copying Module Manifest"
$ModuleManifestSource = Get-Item -Path $ENV:BHPSModuleManifest
Copy-Item -Path $ModuleManifestSource.FullName -Destination "$($ReleaseDirectory.FullName)\$($ModuleName).psd1" -Force
# --- Create an empty psm1 file
Write-Output "Creating base PSM1 file"
$PSM1 = New-Item -Path "$($ReleaseDirectory.FullName)\$($ModuleName).psm1" -ItemType File -Force
# --- Set psm1 content
$PSM1Header = @"
<#
_____ _____
| __ \ | __ \ /\
| |__) |____ _____ _ ____ _| |__) | / \
| ___/ _ \ \ /\ / / _ \ '__\ \ / / _ / / /\ \
| | | (_) \ V V / __/ | \ V /| | \ \ / ____ \
|_| \___/ \_/\_/ \___|_| \_/ |_| \_\/_/ \_\
#>
# --- Clean up vRAConnection variable on module remove
`$ExecutionContext.SessionState.Module.OnRemove = {
Remove-Variable -Name vRAConnection -Force -ErrorAction SilentlyContinue
}
"@
Set-Content -Path $PSM1.FullName -Value $PSM1Header -Encoding UTF8
# --- Process Functions
$Functions = Get-ChildItem -Path .\PowervRA\Functions -File -Recurse
Write-Output "Processing function:"
foreach ($Function in $Functions) {
Write-Output " - $($Function.BaseName)"
$Content = Get-Content -Path $Function.FullName -Raw
$Definition = @"
<#
- Function: $($Function.BaseName)
#>
$($Content)
`n
"@
$Body += $Definition
#Add-Content -Path $PSM1.FullName -Value $Definition -Encoding UTF8
}
Add-Content -Path $PSM1.FullName -Value $Body -Encoding UTF8
$ModuleManifestVersion = Get-Metadata -Path $ENV:BHPSModuleManifest -PropertyName "ModuleVersion"
$ArtifactDestination = "$($ENV:BHProjectPath)\$($ENV:BHProjectName).v$($ModuleManifestVersion).zip"
if ((Test-Path -Path $ArtifactDestination)) {
Remove-Item -Path $ArtifactDestination -Force | Out-Null
}
Write-Output "Compressing module: $($ArtifactDestination)"
Compress-Archive -Path $ReleaseDirectory.FullName -DestinationPath $ArtifactDestination -Force -Confirm:$false -Verbose:$VerbosePreference | Out-Null
if ($ENV:BHBuildSystem -eq "AppVeyor") {
Write-Output "Pushing asset to AppVeyor: $($ArtifactDestination)"
Push-AppveyorArtifact $ArtifactDestination
}
}
Task CreateGitHubRelease {
if ($ENV:BHBuildSystem -eq "Unknown"){
Write-Output "Could not detect build system. Skipping task"
return
}
if ($ENV:APPVEYOR_REPO_PROVIDER -notlike 'github') {
Write-Output "Repo provider '$ENV:APPVEYOR_REPO_PROVIDER'. Skipping task"
return
}
if ($ENV:BHBranchName -ne "master") {
Write-Output "Not in master branch. Skipping task"
return
}
Set-GitHubSessionInformation -UserName $OrgName -APIKey $ENV:gh_token -Verbose:$VerbosePreference | Out-Null
$ModuleManifestVersion = Get-Metadata -Path $ENV:BHPSModuleManifest -PropertyName "ModuleVersion"
try {
$GitHubRelease = Get-GitHubRelease -Repository $RepositoryName -Tag v$ModuleManifestVersion
}
catch {}
if ($GitHubRelease) {
Write-Output "A release with tag v$ModuleManifestVersion already exists. Skipping task"
return
}
$AssetPath = "$($ENV:BHProjectPath)\$($ENV:BHProjectName).v$($ModuleManifestVersion).zip"
$Asset = @{
"Path" = $AssetPath
"Content-Type" = "application/zip"
}
$GitHubReleaseManagerParameters = @{
Repository = $RepositoryName
Name = $ModuleName
Description = (Get-Content -Path "$ENV:BHProjectPath\RELEASE.md" -Raw)
Target = $ENV:BHBranchName
Tag = "v$($ModuleManifestVersion)"
Asset = $Asset
}
Write-Output "Creating GitHub release with the following parameters:"
Write-Output $GitHubReleaseManagerParameters
New-GitHubRelease @GitHubReleaseManagerParameters -Verbose:$VerbosePreference -Confirm:$false | Out-Null
}
Task PublishToPSGallery {
if ($ENV:BHBranchName -ne "master") {
Write-Output "Not in master branch. Skipping task"
return
}
$ModuleManifestVersion = Get-Metadata -Path $ENV:BHPSModuleManifest -PropertyName "ModuleVersion"
$PSGalleryModule = Find-Module -Name $ModuleName -RequiredVersion $ModuleManifestVersion -ErrorAction SilentlyContinue
if ($PSGalleryModule) {
Write-Output "Version $ModuleManifestVersion already exists in the PowerShell Gallery. Skipping task"
return
}
Publish-Module -Path "$($ENV:BHProjectPath)\Release\$($ModuleName)" -NuGetApiKey $ENV:psg_token -Confirm:$false -Verbose:$VerbosePreference | Out-Null
}