forked from SCRT-HQ/PSGSuite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
psake.ps1
606 lines (555 loc) · 26.9 KB
/
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
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
# PSake makes variables declared here available in other scriptblocks
# Init some things
Properties {
# Find the build folder based on build system
$ProjectRoot = $ENV:BHProjectPath
if (-not $ProjectRoot) {
if ($pwd.Path -like "*ci*") {
Set-Location ..
}
$ProjectRoot = $pwd.Path
}
$moduleName = "PSGSuite"
$sut = $env:BHModulePath
$tests = "$projectRoot\Tests"
$Timestamp = Get-Date -Uformat "%Y%m%d-%H%M%S"
$PSVersion = $PSVersionTable.PSVersion.ToString()
$TestFile = "TestResults.xml"
$lines = '----------------------------------------------------------------------'
$outputDir = $env:BHBuildOutput
$outputModDir = Join-Path -Path $outputDir -ChildPath $env:BHProjectName
$manifest = Import-PowerShellDataFile -Path $env:BHPSModuleManifest
$outputModVerDir = Join-Path -Path $outputModDir -ChildPath $manifest.ModuleVersion
$pathSeperator = [IO.Path]::PathSeparator
$NuGetSearchStrings = @(
"Google.Apis*"
)
$Verbose = @{}
if ($ENV:BHCommitMessage -match "!verbose") {
$Verbose = @{Verbose = $True}
}
}
. ([System.IO.Path]::Combine($PSScriptRoot,"ci","AzurePipelinesHelpers.ps1"))
Set-BuildVariables
FormatTaskName (Get-PsakeTaskSectionFormatter)
#Task Default -Depends Init,Test,Build,Deploy
task default -depends Test
task Skip {
" Skipping psake for this job!"
}
task Init {
Set-Location $ProjectRoot
Write-BuildLog "Build System Details:"
Write-BuildLog "$((Get-ChildItem Env: | Where-Object {$_.Name -match "^(BUILD_|SYSTEM_|BH)"} | Sort-Object Name | Format-Table Name,Value -AutoSize | Out-String).Trim())"
if ($env:BHProjectName -cne $moduleName) {
$env:BHProjectName = $moduleName
}
'Configuration' | Foreach-Object {
Install-Module -Name $_ -Repository PSGallery -Scope CurrentUser -AllowClobber -SkipPublisherCheck -Confirm:$false -ErrorAction Stop -Force
Import-Module -Name $_ -Verbose:$false -ErrorAction Stop -Force
}
} -description 'Initialize build environment'
task Clean -depends Init {
$zipPath = [System.IO.Path]::Combine($PSScriptRoot,"$($env:BHProjectName).zip")
if (Test-Path $zipPath) {
Remove-Item $zipPath -Force
}
Remove-Module -Name $env:BHProjectName -Force -ErrorAction SilentlyContinue
if (Test-Path -Path $outputDir) {
if ("$env:NoNugetRestore" -eq 'True') {
Write-BuildLog "Skipping DLL clean due to `$env:NoNugetRestore = $env:NoNugetRestore"
Get-ChildItem -Path $outputDir -Recurse -File | Where-Object {$_.FullName -notlike "$outputModVerDir\lib*"} | Sort-Object {$_.FullName.Length} -Descending | ForEach-Object {
try {
Remove-Item $_.FullName -Force -Recurse
}
catch {
Write-Warning "Unable to delete: '$($_.FullName)'"
}
}
}
else {
Remove-Item $outputDir -Recurse -Force
}
}
if (-not (Test-Path $outputDir)) {
New-Item -Path $outputDir -ItemType Directory | Out-Null
}
" Cleaned previous output directory [$outputDir]"
} -description 'Cleans module output directory'
task Compile -depends Clean {
# Create module output directory
$functionsToExport = @()
$sutLib = [System.IO.Path]::Combine($sut,'lib')
$aliasesToExport = (. $sut\Aliases\PSGSuite.Aliases.ps1).Keys
if (-not (Test-Path $outputModVerDir)) {
$modDir = New-Item -Path $outputModDir -ItemType Directory -ErrorAction SilentlyContinue
New-Item -Path $outputModVerDir -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
}
# Append items to psm1
Write-BuildLog 'Creating psm1...'
$psm1 = Copy-Item -Path (Join-Path -Path $sut -ChildPath 'PSGSuite.psm1') -Destination (Join-Path -Path $outputModVerDir -ChildPath "$($ENV:BHProjectName).psm1") -PassThru
foreach ($scope in @('Private','Public')) {
Write-BuildLog "Copying contents from files in source folder to PSM1: $($scope)"
$gciPath = Join-Path $sut $scope
if (Test-Path $gciPath) {
Get-ChildItem -Path $gciPath -Filter "*.ps1" -Recurse -File | ForEach-Object {
Write-BuildLog "Working on: $scope$([System.IO.Path]::DirectorySeparatorChar)$($_.FullName.Replace("$gciPath$([System.IO.Path]::DirectorySeparatorChar)",'') -replace '\.ps1$')"
[System.IO.File]::AppendAllText($psm1,("$([System.IO.File]::ReadAllText($_.FullName))`n"))
if ($scope -eq 'Public') {
$functionsToExport += $_.BaseName
[System.IO.File]::AppendAllText($psm1,("Export-ModuleMember -Function '$($_.BaseName)'`n"))
}
}
}
}
Invoke-CommandWithLog {Remove-Module $env:BHProjectName -ErrorAction SilentlyContinue -Force -Verbose:$false}
if ("$env:NoNugetRestore" -ne 'True') {
New-Item -Path "$outputModVerDir\lib" -ItemType Directory -ErrorAction SilentlyContinue | Out-Null
Write-BuildLog "Installing NuGet dependencies..."
Install-NuGetDependencies -Destination $outputModVerDir -AddlSearchString $NuGetSearchStrings -Verbose
}
else {
Write-BuildLog "Skipping NuGet Restore due to `$env:NoNugetRestore = '$env:NoNugetRestore'"
}
$aliasHashContents = (Get-Content "$sut\Aliases\PSGSuite.Aliases.ps1" -Raw).Trim()
# Set remainder of PSM1 contents
@"
Import-GoogleSDK
if (`$global:PSGSuiteKey -and `$MyInvocation.BoundParameters['Debug']) {
`$prevDebugPref = `$DebugPreference
`$DebugPreference = "Continue"
Write-Debug "```$global:PSGSuiteKey is set to a `$(`$global:PSGSuiteKey.Count * 8)-bit key!"
`$DebugPreference = `$prevDebugPref
}
`$aliasHash = $aliasHashContents
foreach (`$key in `$aliasHash.Keys) {
try {
New-Alias -Name `$key -Value `$aliasHash[`$key] -Force
}
catch {
Write-Error "[ALIAS: `$(`$key)] `$(`$_.Exception.Message.ToString())"
}
}
Export-ModuleMember -Alias '*'
if (!(Test-Path (Join-Path "~" ".scrthq"))) {
New-Item -Path (Join-Path "~" ".scrthq") -ItemType Directory -Force | Out-Null
}
if (`$PSVersionTable.ContainsKey('PSEdition') -and `$PSVersionTable.PSEdition -eq 'Core' -and !`$Global:PSGSuiteKey -and !`$IsWindows) {
if (!(Test-Path (Join-Path (Join-Path "~" ".scrthq") "BlockCoreCLREncryptionWarning.txt"))) {
Write-Warning "CoreCLR does not support DPAPI encryption! Setting a basic AES key to prevent errors. Please create a unique key as soon as possible as this will only obfuscate secrets from plain text in the Configuration, the key is not secure as is. If you would like to prevent this message from displaying in the future, run the following command:`n`nBlock-CoreCLREncryptionWarning`n"
}
`$Global:PSGSuiteKey = [Byte[]]@(1..16)
`$ConfigScope = "User"
}
if (`$Global:PSGSuiteKey -is [System.Security.SecureString]) {
`$Method = "SecureString"
if (!`$ConfigScope) {
`$ConfigScope = "Machine"
}
}
elseif (`$Global:PSGSuiteKey -is [System.Byte[]]) {
`$Method = "AES Key"
if (!`$ConfigScope) {
`$ConfigScope = "Machine"
}
}
else {
`$Method = "DPAPI"
`$ConfigScope = "User"
}
Add-MetadataConverter -Converters @{
[SecureString] = {
`$encParams = @{}
if (`$Global:PSGSuiteKey -is [System.Byte[]]) {
`$encParams["Key"] = `$Global:PSGSuiteKey
}
elseif (`$Global:PSGSuiteKey -is [System.Security.SecureString]) {
`$encParams["SecureKey"] = `$Global:PSGSuiteKey
}
'ConvertTo-SecureString "{0}"' -f (ConvertFrom-SecureString `$_ @encParams)
}
"Secure" = {
param([string]`$String)
`$encParams = @{}
if (`$Global:PSGSuiteKey -is [System.Byte[]]) {
`$encParams["Key"] = `$Global:PSGSuiteKey
}
elseif (`$Global:PSGSuiteKey -is [System.Security.SecureString]) {
`$encParams["SecureKey"] = `$Global:PSGSuiteKey
}
ConvertTo-SecureString `$String @encParams
}
"ConvertTo-SecureString" = {
param([string]`$String)
`$encParams = @{}
if (`$Global:PSGSuiteKey -is [System.Byte[]]) {
`$encParams["Key"] = `$Global:PSGSuiteKey
}
elseif (`$Global:PSGSuiteKey -is [System.Security.SecureString]) {
`$encParams["SecureKey"] = `$Global:PSGSuiteKey
}
ConvertTo-SecureString `$String @encParams
}
}
try {
`$confParams = @{
Scope = `$ConfigScope
}
if (`$ConfigName) {
`$confParams["ConfigName"] = `$ConfigName
`$Script:ConfigName = `$ConfigName
}
try {
if (`$global:PSGSuite) {
Write-Warning "Using config `$(if (`$global:PSGSuite.ConfigName){"name '`$(`$global:PSGSuite.ConfigName)' "})found in variable: ```$global:PSGSuite"
Write-Verbose "`$((`$global:PSGSuite | Format-List | Out-String).Trim())"
if (`$global:PSGSuite -is [System.Collections.Hashtable]) {
`$global:PSGSuite = New-Object PSObject -Property `$global:PSGSuite
}
`$script:PSGSuite = `$global:PSGSuite
}
else {
Get-PSGSuiteConfig @confParams -ErrorAction Stop
}
}
catch {
if (Test-Path "`$ModuleRoot\`$env:USERNAME-`$env:COMPUTERNAME-`$env:PSGSuiteDefaultDomain-PSGSuite.xml") {
Get-PSGSuiteConfig -Path "`$ModuleRoot\`$env:USERNAME-`$env:COMPUTERNAME-`$env:PSGSuiteDefaultDomain-PSGSuite.xml" -ErrorAction Stop
Write-Warning "No Configuration.psd1 found at scope '`$ConfigScope'; falling back to legacy XML. If you would like to convert your legacy XML to the newer Configuration.psd1, run the following command:`n`nGet-PSGSuiteConfig -Path '`$ModuleRoot\`$env:USERNAME-`$env:COMPUTERNAME-`$env:PSGSuiteDefaultDomain-PSGSuite.xml' -PassThru | Set-PSGSuiteConfig`n"
}
else {
Write-Warning "There was no config returned! Please make sure you are using the correct key or have a configuration already saved."
}
}
}
catch {
Write-Warning "There was no config returned! Please make sure you are using the correct key or have a configuration already saved."
}
"@ | Add-Content -Path $psm1 -Encoding UTF8
# Copy over manifest
Copy-Item -Path $env:BHPSModuleManifest -Destination $outputModVerDir
# Update FunctionsToExport on manifest
Update-ModuleManifest -Path (Join-Path $outputModVerDir "$($env:BHProjectName).psd1") -FunctionsToExport ($functionsToExport | Sort-Object) -AliasesToExport ($aliasesToExport | Sort-Object)
if ((Get-ChildItem $outputModVerDir | Where-Object {$_.Name -eq "$($env:BHProjectName).psd1"}).BaseName -cne $env:BHProjectName) {
" Renaming manifest to correct casing"
Rename-Item (Join-Path $outputModVerDir "$($env:BHProjectName).psd1") -NewName "$($env:BHProjectName).psd1" -Force
}
" Created compiled module at [$outputModDir]"
" Output version directory contents"
Get-ChildItem $outputModVerDir | Format-Table -Autosize
} -description 'Compiles module from source'
Task Docs -Depends Init {
'platyPS','PSGSuite' | ForEach-Object {
" Installing $_ if missing"
$_ | Resolve-Module -Verbose
Import-Module $_
}
$docPath = Join-Path $PSScriptRoot 'docs'
$funcPath = Join-Path $docPath 'Function Help'
$docStage = Join-Path $PSScriptRoot 'docstage'
$sitePath = Join-Path $PSScriptRoot 'site'
" Setting index.md content from README"
Get-Content (Join-Path $PSScriptRoot 'README.md') -Raw | Set-Content (Join-Path $docPath 'index.md') -Force
if (-not (Test-Path $docPath)) {
" Creating Doc Path: $docPath"
New-Item $docPath -ItemType Directory -Force | Out-Null
}
if (-not (Test-Path $sitePath)) {
" Creating Site Path: $sitePath"
New-Item $sitePath -ItemType Directory -Force | Out-Null
}
if (Test-Path $docstage) {
" Clearing out Doc Stage Path: $docstage"
Remove-Item $docstage -Recurse -Force
}
" Creating a fresh Doc Stage folder: $docstage"
New-Item $docstage -ItemType Directory -Force | Out-Null
New-MarkdownHelp -Module PSGSuite -NoMetadata -OutputFolder $docstage -Force -AlphabeticParamsOrder -ExcludeDontShow -Verbose | Out-Null
$env:PSModulePath = $origPSModulePath
$stagesDocs = Get-ChildItem $docstage -Recurse -Filter "*.md"
foreach ($folder in (Get-ChildItem (Join-Path -Path $sut -ChildPath 'Public') -Directory)) {
$docFolder = Join-Path $funcPath $folder.BaseName
if (-not (Test-Path $docFolder)) {
" Creating Doc Folder: $docFolder"
New-Item $docFolder -ItemType Directory -Force | Out-Null
}
else {
" Cleaning up existing Doc Folder"
Get-ChildItem $docFolder -Recurse | Remove-Item -Recurse -Force
}
foreach ($func in (Get-ChildItem $folder.FullName -Recurse -Filter "*.ps1")) {
if ($doc = $stagesDocs | Where-Object {$_.BaseName -eq $func.BaseName}) {
" Moving function doc '$($func.BaseName)' to doc folder: $docFolder"
Move-Item $doc.FullName -Destination $docFolder -Force | Out-Null
}
}
}
Set-Location $PSScriptRoot
if ($null -eq (python -m mkdocs --version)) {
python -m pip install --user wheel
python -m pip install --user mkdocs
python -m pip install --user mkdocs-material
python -m pip install --user mkdocs-minify-plugin
python -m pip install --user pymdown-extensions
}
python -m mkdocs gh-deploy --message "[skip ci] Deploying Docs update @ $(Get-Date) to https://psgsuite.io" --verbose --force --ignore-version | Tee-Object -Variable mkdocs
if ($errors = ($mkdocs -split "`n") | Where-Object {$_ -match 'Error\s+\-\s+'}) {
Write-BuildError ($errors -join "`n")
}
}
Task Import -Depends Compile {
' Testing import of compiled module'
Import-Module (Join-Path $outputModVerDir "$($env:BHProjectName).psd1")
} -description 'Imports the newly compiled module'
$pesterScriptBlock = {
'Pester' | Resolve-Module -UpdateModules -Verbose
Push-Location
Set-Location -PassThru $outputModDir
if (-not $ENV:BHProjectPath) {
Set-BuildEnvironment -Path $PSScriptRoot\..
}
$origModulePath = $env:PSModulePath
if ( $env:PSModulePath.split($pathSeperator) -notcontains $outputDir ) {
$env:PSModulePath = ($outputDir + $pathSeperator + $origModulePath)
}
Remove-Module $ENV:BHProjectName -ErrorAction SilentlyContinue -Verbose:$false
Import-Module -Name $outputModDir -Force -Verbose:$false
$testResultsXml = Join-Path -Path $outputDir -ChildPath $TestFile
$pesterParams = @{
OutputFormat = 'NUnitXml'
OutputFile = $testResultsXml
PassThru = $true
Path = $tests
}
if ($PSVersionTable.PSVersion.Major -lt 6) {
### $pesterParams['CodeCoverage'] = (Join-Path $outputModVerDir "$($env:BHProjectName).psm1")
}
if ($global:ExcludeTag) {
$pesterParams['ExcludeTag'] = $global:ExcludeTag
" Invoking Pester and excluding tag(s) [$($global:ExcludeTag -join ', ')]..."
}
else {
' Invoking Pester...'
}
$testResults = Invoke-Pester @pesterParams
' Pester invocation complete!'
if ($testResults.FailedCount -gt 0) {
$testResults.TestResult | Where-Object {-not $_.Passed} | Format-List
Write-BuildError -Message 'One or more Pester tests failed. Build cannot continue!'
}
Pop-Location
$env:PSModulePath = $origModulePath
}
task Full -Depends Compile $pesterScriptBlock -description 'Run Pester tests'
task Test -Depends Init $pesterScriptBlock -description 'Run Pester tests only [no module compilation]'
$deployScriptBlock = {
function Publish-GitHubRelease {
<#
.SYNOPSIS
Publishes a release to GitHub Releases. Borrowed from https://www.herebedragons.io/powershell-create-github-release-with-artifact
#>
[CmdletBinding()]
Param (
[parameter(Mandatory = $true)]
[String]
$VersionNumber,
[parameter(Mandatory = $false)]
[String]
$CommitId = 'master',
[parameter(Mandatory = $true)]
[String]
$ReleaseNotes,
[parameter(Mandatory = $true)]
[ValidateScript( {Test-Path $_})]
[String]
$ArtifactPath,
[parameter(Mandatory = $true)]
[String]
$GitHubUsername,
[parameter(Mandatory = $true)]
[String]
$GitHubRepository,
[parameter(Mandatory = $true)]
[String]
$GitHubApiKey,
[parameter(Mandatory = $false)]
[Switch]
$PreRelease,
[parameter(Mandatory = $false)]
[Switch]
$Draft
)
$releaseData = @{
tag_name = [string]::Format("v{0}", $VersionNumber)
target_commitish = $CommitId
name = [string]::Format("$($env:BHProjectName) v{0}", $VersionNumber)
body = $ReleaseNotes
draft = [bool]$Draft
prerelease = [bool]$PreRelease
}
$auth = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($gitHubApiKey + ":x-oauth-basic"))
$releaseParams = @{
Uri = "https://api.github.com/repos/$GitHubUsername/$GitHubRepository/releases"
Method = 'POST'
Headers = @{
Authorization = $auth
}
ContentType = 'application/json'
Body = (ConvertTo-Json $releaseData -Compress)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$result = Invoke-RestMethod @releaseParams
$uploadUri = $result | Select-Object -ExpandProperty upload_url
$uploadUri = $uploadUri -creplace '\{\?name,label\}'
$artifact = Get-Item $ArtifactPath
$uploadUri = $uploadUri + "?name=$($artifact.Name)"
$uploadFile = $artifact.FullName
$uploadParams = @{
Uri = $uploadUri
Method = 'POST'
Headers = @{
Authorization = $auth
}
ContentType = 'application/zip'
InFile = $uploadFile
}
$result = Invoke-RestMethod @uploadParams
}
if (($ENV:BHBuildSystem -eq 'VSTS' -and $env:BHCommitMessage -match '!deploy' -and $env:BHBranchName -eq "master") -or $global:ForceDeploy -eq $true) {
if ($null -eq (Get-Module PoshTwit -ListAvailable)) {
" Installing PoshTwit module..."
Install-Module PoshTwit -Scope CurrentUser
}
Import-Module PoshTwit -Verbose:$false
# Load the module, read the exported functions, update the psd1 FunctionsToExport
$commParsed = $env:BHCommitMessage | Select-String -Pattern '\sv\d+\.\d+\.\d+\s'
if ($commParsed) {
$commitVer = $commParsed.Matches.Value.Trim().Replace('v','')
}
$curVer = (Get-Module $env:BHProjectName).Version
$galVer = (Find-Module $env:BHProjectName -Repository PSGallery).Version.ToString()
$galVerSplit = $galVer.Split('.')
$nextGalVer = [System.Version](($galVerSplit[0..($galVerSplit.Count - 2)] -join '.') + '.' + ([int]$galVerSplit[-1] + 1))
$versionToDeploy = if ($commitVer -and ([System.Version]$commitVer -lt $nextGalVer)) {
Write-Host -ForegroundColor Yellow "Version in commit message is $commitVer, which is less than the next Gallery version and would result in an error. Possible duplicate deployment build, skipping module bump and negating deployment"
$env:BHCommitMessage = $env:BHCommitMessage.Replace('!deploy','')
$null
}
elseif ($commitVer -and ([System.Version]$commitVer -gt $nextGalVer)) {
Write-Host -ForegroundColor Green "Module version to deploy: $commitVer [from commit message]"
[System.Version]$commitVer
}
elseif ($curVer -ge $nextGalVer) {
Write-Host -ForegroundColor Green "Module version to deploy: $curVer [from manifest]"
$curVer
}
elseif ($env:BHCommitMessage -match '!hotfix') {
Write-Host -ForegroundColor Green "Module version to deploy: $nextGalVer [commit message match '!hotfix']"
$nextGalVer
}
elseif ($env:BHCommitMessage -match '!minor') {
$minorVers = [System.Version]("{0}.{1}.{2}" -f $nextGalVer.Major,([int]$nextGalVer.Minor + 1),0)
Write-Host -ForegroundColor Green "Module version to deploy: $minorVers [commit message match '!minor']"
$minorVers
}
elseif ($env:BHCommitMessage -match '!major') {
$majorVers = [System.Version]("{0}.{1}.{2}" -f ([int]$nextGalVer.Major + 1),0,0)
Write-Host -ForegroundColor Green "Module version to deploy: $majorVers [commit message match '!major']"
$majorVers
}
else {
Write-Host -ForegroundColor Green "Module version to deploy: $nextGalVer [PSGallery next version]"
$nextGalVer
}
# Bump the module version
if ($versionToDeploy) {
try {
if ($ENV:BHBuildSystem -eq 'VSTS' -and -not [String]::IsNullOrEmpty($env:NugetApiKey)) {
" Publishing version [$($versionToDeploy)] to PSGallery..."
Update-Metadata -Path (Join-Path $outputModVerDir "$($env:BHProjectName).psd1") -PropertyName ModuleVersion -Value $versionToDeploy
Publish-Module -Path $outputModVerDir -NuGetApiKey $env:NugetApiKey -Repository PSGallery
" Deployment successful!"
}
else {
" [SKIPPED] Deployment of version [$($versionToDeploy)] to PSGallery"
}
$commitId = git rev-parse --verify HEAD
if (-not [String]::IsNullOrEmpty($env:GitHubPAT)) {
" Creating Release ZIP..."
$zipPath = [System.IO.Path]::Combine($PSScriptRoot,"$($env:BHProjectName).zip")
if (Test-Path $zipPath) {
Remove-Item $zipPath -Force
}
Add-Type -Assembly System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory($outputModDir,$zipPath)
" Publishing Release v$($versionToDeploy) @ commit Id [$($commitId)] to GitHub..."
$ReleaseNotes = "# Changelog`n`n"
$ReleaseNotes += (git log -1 --pretty=%B | Select-Object -Skip 2) -join "`n"
$ReleaseNotes += "`n`n***`n`n# Instructions`n`n"
$ReleaseNotes += @"
**IMPORTANT: You MUST have the module '[Configuration](https://github.com/poshcode/Configuration)' installed as a prerequisite! Installing the module from the repo source or the release page does not automatically install dependencies!!**
1. [Click here](https://github.com/scrthq/$($env:BHProjectName)/releases/download/v$($versionToDeploy.ToString())/$($env:BHProjectName).zip) to download the *$($env:BHProjectName).zip* file attached to the release.
2. **If on Windows**: Right-click the downloaded zip, select Properties, then unblock the file.
> _This is to prevent having to unblock each file individually after unzipping._
3. Unzip the archive.
4. (Optional) Place the module folder somewhere in your ``PSModulePath``.
> _You can view the paths listed by running the environment variable ```$env:PSModulePath``_
5. Import the module, using the full path to the PSD1 file in place of ``$($env:BHProjectName)`` if the unzipped module folder is not in your ``PSModulePath``:
``````powershell
# In `$env:PSModulePath
Import-Module $($env:BHProjectName)
# Otherwise, provide the path to the manifest:
Import-Module -Path C:\MyPSModules\$($env:BHProjectName)\$($versionToDeploy.ToString())\$($env:BHProjectName).psd1
``````
"@
$gitHubParams = @{
VersionNumber = $versionToDeploy.ToString()
CommitId = $commitId
ReleaseNotes = $ReleaseNotes
ArtifactPath = $zipPath
GitHubUsername = 'scrthq'
GitHubRepository = $env:BHProjectName
GitHubApiKey = $env:GitHubPAT
Draft = $false
}
Publish-GitHubRelease @gitHubParams
" Release creation successful!"
}
else {
" [SKIPPED] Publishing Release v$($versionToDeploy) @ commit Id [$($commitId)] to GitHub"
}
if ($ENV:BHBuildSystem -eq 'VSTS' -and -not [String]::IsNullOrEmpty($env:TwitterAccessSecret) -and -not [String]::IsNullOrEmpty($env:TwitterAccessToken) -and -not [String]::IsNullOrEmpty($env:TwitterConsumerKey) -and -not [String]::IsNullOrEmpty($env:TwitterConsumerSecret)) {
" Publishing tweet about new release..."
$manifest = Import-PowerShellDataFile -Path (Join-Path $outputModVerDir "$($env:BHProjectName).psd1")
$text = "#$($env:BHProjectName) v$($versionToDeploy) is now available on the #PSGallery! https://www.powershellgallery.com/packages/$($env:BHProjectName)/$($versionToDeploy) #PowerShell"
$manifest.PrivateData.PSData.Tags | Foreach-Object {
$text += " #$($_)"
}
if ($text.Length -gt 280) {
" Trimming [$($text.Length - 280)] extra characters from tweet text to get to 280 character limit..."
$text = $text.Substring(0,280)
}
" Tweet text: $text"
Publish-Tweet -Tweet $text -ConsumerKey $env:TwitterConsumerKey -ConsumerSecret $env:TwitterConsumerSecret -AccessToken $env:TwitterAccessToken -AccessSecret $env:TwitterAccessSecret
" Tweet successful!"
}
else {
" [SKIPPED] Twitter update of new release"
}
}
catch {
Write-Error $_ -ErrorAction Stop
}
}
else {
Write-Host -ForegroundColor Yellow "No module version matched! Negating deployment to prevent errors"
$env:BHCommitMessage = $env:BHCommitMessage.Replace('!deploy','')
}
}
else {
Write-Host -ForegroundColor Magenta "Build system is not VSTS, commit message does not contain '!deploy' and/or branch is not 'master' -- skipping module update!"
}
}
Task Deploy -Depends Init $deployScriptBlock -description 'Deploy module to PSGallery' -preaction {
Import-Module -Name $outputModDir -Force -Verbose:$false
}