forked from claudiospizzi/DSCPullServerWeb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.psake.ps1
389 lines (304 loc) · 13.1 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
<#
.SYNOPSIS
PSake build script for PowerShell modules.
.DESCRIPTION
This PSake build script supports building PowerShell manifest modules which
contain PowerShell script functions and optionally binary C# libraries.
The build script contains the following tasks:
- Init
Create folders, which are used by the build system: tst/ and bin/.
- Clean
Clean the content of build paths to ensure no side effects.
- Compile
If required, compile the Visual Studio Solutions. Ensure that the build
system copies the result into the target Module folder.
- Stage
Copy all module files to the build directory excluding the Functions and
Helpers, these files get merged in the .psm1 file.
- Merge
Copy the content of all .ps1 files within the Functions and Helpers
folders to the .psm1 file. This ensures a faster loading time for the
module, but still a nice development experience with one function per
file.
- Pester
Invoke all Pester tests within the module and ensure that all tests pass.
- ScriptAnalyzer
Invoke all Script Analyzer rules against the PowerShell script files and
ensure, that they do not break any rule.
- Gallery
This task will publish the module to a PowerShell Gallery. The task is not
part of the default tasks, it needs to be called manually if needed during
a deployment.
- GitHub
This task will publish the module to the GitHub Releases. The task is not
part of the default tasks, it needs to be called manually if needed during
a deployment.
The tasks are grouped to the following task groups:
- Default
Tasks: Build, Test
- Build
Tasks: Init, Clean, Compile, Stage, Merge
- Test
Tasks: Pester, ScriptAnalyzer
.NOTES
Author : Claudio Spizzi
License : MIT License
.LINK
https://github.com/claudiospizzi
#>
## Configuration and Default task
# Default build configuration
Properties {
$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath 'Modules'
$ModuleNames = @()
$SourceEnabled = $false
}
# Load project configuration
. $PSScriptRoot\build.settings.ps1
# Default task
Task Default -depends Build, Test
## Build tasks
# Overall build task
Task Build -depends Init, Clean, Compile, Stage, Merge
# Create release and test folders
Task Init -requiredVariables ReleasePath, PesterPath, ScriptAnalyzerPath {
if (!(Test-Path -Path $ReleasePath))
{
New-Item -Path $ReleasePath -ItemType Directory -Verbose:$VerbosePreference > $null
}
if (!(Test-Path -Path $PesterPath))
{
New-Item -Path $PesterPath -ItemType Directory -Verbose:$VerbosePreference > $null
}
if (!(Test-Path -Path $ScriptAnalyzerPath))
{
New-Item -Path $ScriptAnalyzerPath -ItemType Directory -Verbose:$VerbosePreference > $null
}
}
# Remove any items in the release and test folders
Task Clean -depends Init -requiredVariables ReleasePath, PesterPath, ScriptAnalyzerPath {
Get-ChildItem -Path $ReleasePath | Remove-Item -Recurse -Force -Verbose:$VerbosePreference
Get-ChildItem -Path $PesterPath | Remove-Item -Recurse -Force -Verbose:$VerbosePreference
Get-ChildItem -Path $ScriptAnalyzerPath | Remove-Item -Recurse -Force -Verbose:$VerbosePreference
}
# Compile C# solutions
Task Compile -depends Clean -requiredVariables SourceEnabled, SourcePath, SourcePublish, SourceNames {
#$msBuildPath = 'C:\Windows\Microsoft.NET\Framework\v4.0.30319'
$msBuildPath = 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin'
if (!$SourceEnabled)
{
return
}
if ($Env:Path -notlike "*$msBuildPath*")
{
$Env:Path = "$msBuildPath;$Env:Path"
}
foreach ($sourceName in $SourceNames)
{
nuget restore "Sources"
if ([String]::IsNullOrEmpty($SourcePublish))
{
$msBuildLog = (MSBuild.exe "$SourcePath\$sourceName.sln" /target:Build /p:Configuration=Release /verbosity:m)
}
else
{
$msBuildLog = (MSBuild.exe "$SourcePath\$sourceName.sln" /target:Build /p:Configuration=Release /p:DeployOnBuild=true /p:PublishProfile=$SourcePublish /verbosity:m)
}
$msBuildLog | ForEach-Object { Write-Verbose $_ }
}
}
# Copy all required module files to the release folder
Task Stage -depends Compile -requiredVariables ReleasePath, ModulePath, ModuleNames {
foreach ($moduleName in $ModuleNames)
{
foreach ($item in (Get-ChildItem -Path "$ModulePath\$moduleName" -Exclude 'Functions', 'Helpers'))
{
Copy-Item -Path $item.FullName -Destination "$ReleasePath\$moduleName\$($item.Name)" -Recurse -Verbose:$VerbosePreference
}
}
}
# Merge the module by copying all helper and cmdlet functions to the psm1 file
Task Merge -depends Stage -requiredVariables ReleasePath, ModulePath, ModuleNames {
foreach ($moduleName in $ModuleNames)
{
try
{
$moduleContent = New-Object -TypeName 'System.Collections.Generic.List[System.String]'
# Load code for all function files
foreach ($function in (Get-ChildItem -Path "$ModulePath\$moduleName\Functions" -Filter '*.ps1' -Recurse -File -ErrorAction 'SilentlyContinue'))
{
$moduleContent.Add((Get-Content -Path $function.FullName -Raw))
}
# Load code for all helpers files
foreach ($function in (Get-ChildItem -Path "$ModulePath\$moduleName\Helpers" -Filter '*.ps1' -Recurse -File -ErrorAction 'SilentlyContinue'))
{
$moduleContent.Add((Get-Content -Path $function.FullName -Raw))
}
# Load code of the module file itself
$moduleContent.Add((Get-Content -Path "$ModulePath\$moduleName\$moduleName.psm1" | Select-Object -Skip 15) -join "`r`n")
# Concatenate whole code into the module file
$moduleContent | Set-Content -Path "$ReleasePath\$moduleName\$moduleName.psm1" -Encoding UTF8 -Verbose:$VerbosePreference
# Compress
Compress-Archive -Path "$ReleasePath\$moduleName" -DestinationPath "$ReleasePath\$moduleName.zip" -Verbose:$VerbosePreference
# Publish AppVeyor artifacts
if ($env:APPVEYOR)
{
Push-AppveyorArtifact -Path "$ReleasePath\$moduleName.zip" -DeploymentName $moduleName -Verbose:$VerbosePreference
}
}
catch
{
Assert -conditionToCheck $false -failureMessage "Build failed: $_"
}
}
}
## Test tasks
# Overall test task
Task Test -depends Build, Pester, ScriptAnalyzer
# Invoke Pester tests and return result as NUnit XML file
Task Pester -requiredVariables ReleasePath, ModuleNames, PesterPath, PesterFile {
if (!(Get-Module -Name 'Pester' -ListAvailable))
{
Write-Warning "Pester module is not installed. Skipping $($psake.context.currentTaskName) task."
return
}
Import-Module -Name 'Pester'
foreach ($moduleName in $ModuleNames)
{
$modulePesterFile = Join-Path -Path $PesterPath -ChildPath "$moduleName-$PesterFile"
powershell.exe -NoLogo -NoProfile -NonInteractive -Command "Set-Location -Path '$ReleasePath\$moduleName'; Invoke-Pester -OutputFile '$modulePesterFile' -OutputFormat 'NUnitXml'"
$testResults = [Xml] (Get-Content -Path $modulePesterFile)
Assert -conditionToCheck ($testResults.'test-results'.failures -eq 0) -failureMessage "One or more Pester tests failed, build cannot continue."
# Publish AppVeyor test results
if ($env:APPVEYOR)
{
$webClient = New-Object -TypeName 'System.Net.WebClient'
$webClient.UploadFile("https://ci.appveyor.com/api/testresults/nunit/$env:APPVEYOR_JOB_ID", $modulePesterFile)
}
}
}
# Invoke Script Analyzer tests and stop if any test fails
Task ScriptAnalyzer -requiredVariables ReleasePath, ModulePath, ModuleNames, ScriptAnalyzerPath, ScriptAnalyzerFile, ScriptAnalyzerRules {
if (!(Get-Module -Name 'PSScriptAnalyzer' -ListAvailable))
{
Write-Warning "PSScriptAnalyzer module is not installed. Skipping $($psake.context.currentTaskName) task."
return
}
Import-Module -Name 'PSScriptAnalyzer'
foreach ($moduleName in $ModuleNames)
{
$moduleScriptAnalyzerFile = Join-Path -Path $ScriptAnalyzerPath -ChildPath "$moduleName-$ScriptAnalyzerFile"
$analyzeResults = Invoke-ScriptAnalyzer -Path "$ModulePath\$moduleName" -IncludeRule $ScriptAnalyzerRules -Recurse
$analyzeResults | ConvertTo-Json | Out-File -FilePath $moduleScriptAnalyzerFile -Encoding UTF8
Show-ScriptAnalyzerResult -ModuleName $moduleName -Rule $ScriptAnalyzerRules -Result $analyzeResults
Assert -conditionToCheck ($analyzeResults.Count -eq 0) -failureMessage "One or more Script Analyzer tests failed, build cannot continue."
}
}
## Deploy tasks
# Overall deploy task
Task Deploy -depends Test, Gallery, GitHub
# Deploy to the public PowerShell Gallery
Task Gallery -requiredVariables ReleasePath, ModuleNames, GalleryEnabled, GalleryName, GallerySource, GalleryPublish, GalleryKey {
if (!$GalleryEnabled)
{
return
}
# Register the target PowerShell Gallery, if it does not exist
if ($null -eq (Get-PSRepository -Name $GalleryName -ErrorAction SilentlyContinue))
{
Register-PSRepository -Name $GalleryName -SourceLocation $GallerySource -PublishLocation $GalleryPublish
}
foreach ($moduleName in $ModuleNames)
{
$moduleVersion = (Import-PowerShellDataFile -Path "$ReleasePath\$moduleName\$moduleName.psd1").ModuleVersion
$releaseNotes = Get-ReleaseNote -Version $moduleVersion
Publish-Module -Path "$ReleasePath\$moduleName" -Repository $GalleryName -NuGetApiKey $GalleryKey -ReleaseNotes $releaseNotes
}
}
# Deploy a release to the GitHub repository
Task GitHub -requiredVariables ReleasePath, ModuleNames, GitHubEnabled, GitHubRepoName, GitHubKey {
if (!$GitHubEnabled)
{
return
}
foreach ($moduleName in $ModuleNames)
{
$moduleVersion = (Import-PowerShellDataFile -Path "$ReleasePath\$moduleName\$moduleName.psd1").ModuleVersion
$releaseNotes = Get-ReleaseNote -Version $moduleVersion
# Create GitHub release
$releaseParams = @{
Method = 'Post'
Uri = "https://api.github.com/repos/claudiospizzi/$GitHubRepoName/releases"
Headers = @{
'Accept' = 'application/vnd.github.v3+json'
'Authorization' = "token $GitHubKey"
}
Body = @{
tag_name = $moduleVersion
target_commitish = 'master'
name = "$moduleName v$moduleVersion"
body = ($releaseNotes -join "`n")
draft = $false
prerelease = $false
} | ConvertTo-Json
}
$release = Invoke-RestMethod @releaseParams -ErrorAction Stop
# Upload artifact to GitHub
$artifactParams = @{
Method = 'Post'
Uri = "https://uploads.github.com/repos/claudiospizzi/$GitHubRepoName/releases/$($release.id)/assets?name=$moduleName-$moduleVersion.zip"
Headers = @{
'Accept' = 'application/vnd.github.v3+json'
'Authorization' = "token $GitHubKey"
'Content-Type' = 'application/zip'
}
InFile = "$ReleasePath\$ModuleName.zip"
}
$artifact = Invoke-RestMethod @artifactParams -ErrorAction Stop
}
}
## Helper functions
# Show the Script Analyzer results on the host
function Show-ScriptAnalyzerResult($ModuleName, $Rule, $Result)
{
$colorMap = @{
Error = 'Red'
Warning = 'Yellow'
Information = 'Blue'
}
Write-Host "Module $ModuleName" -ForegroundColor Magenta
foreach ($currentRule in $Rule)
{
Write-Host " Rule $($currentRule.RuleName)" -ForegroundColor Magenta
foreach ($record in $Result.Where({$_.RuleName -eq $currentRule.RuleName}))
{
Write-Host " [-] $($record.Severity): $($record.Message)" -ForegroundColor $colorMap[[String]$record.Severity]
Write-Host " at $($record.ScriptPath): line $($record.Line)" -ForegroundColor $colorMap[[String]$record.Severity]
}
}
Write-Host "Script Analyzer completed"
Write-Host "Rules: $($Rule.Count) Failed: $($analyzeResults.Count)"
}
# Extract the Release Notes from the CHANGELOG.md file
function Get-ReleaseNote($Version)
{
$changelogFile = Join-Path -Path $PSScriptRoot -ChildPath 'CHANGELOG.md'
$releaseNotes = @()
$isCurrentVersion = $false
foreach ($line in (Get-Content -Path $changelogFile))
{
if ($line -eq "## $Version")
{
$isCurrentVersion = $true
}
elseif ($line -like '## *')
{
$isCurrentVersion = $false
}
if ($isCurrentVersion -and $line -like '- *')
{
$releaseNotes += $line
}
}
Write-Output $releaseNotes
}