forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtravis.ps1
More file actions
425 lines (368 loc) · 15.7 KB
/
travis.ps1
File metadata and controls
425 lines (368 loc) · 15.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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
param(
[ValidateSet('Bootstrap','Build','Failure','Success')]
[String]$Stage = 'Build',
[String]$NugetKey
)
Import-Module $PSScriptRoot/../build.psm1 -Force
Import-Module $PSScriptRoot/packaging -Force
function Send-DailyWebHook
{
param (
[Parameter(Mandatory=$true,Position=0)][ValidateSet("Pass","Fail")]$result
)
# Only send web hook if the environment variable is present
# Varible should be set in Travis-CI.org settings
if ($env:WebHookUrl)
{
Write-Log "Sending DailyWebHook with result '$result'."
$webhook = $env:WebHookUrl
$Body = @{
'text'= @"
Build Result: $result </br>
OS Type: $($PSVersionTable.OS) </br>
<a href="https://travis-ci.org/$env:TRAVIS_REPO_SLUG/builds/$env:TRAVIS_BUILD_ID">Build $env:TRAVIS_BUILD_NUMBER</a> </br>
<a href="https://travis-ci.org/$env:TRAVIS_REPO_SLUG/jobs/$env:TRAVIS_JOB_ID">Job $env:TRAVIS_JOB_NUMBER</a>
"@
}
$params = @{
Headers = @{'accept'='application/json'}
Body = $Body | convertto-json
Method = 'Post'
URI = $webhook
}
Invoke-RestMethod @params
}
else
{
Write-Log "Skipping DailyWebHook. WebHookUrl environment variable not present."
}
}
function Get-ReleaseTag
{
$metaDataPath = Join-Path -Path $PSScriptRoot -ChildPath 'metadata.json'
$metaData = Get-Content $metaDataPath | ConvertFrom-Json
$releaseTag = $metadata.PreviewReleaseTag
$previewVersion = $releaseTag.Split('-')
$previewPrefix = $previewVersion[0]
$previewLabel = $previewVersion[1].replace('.','')
if($isDailyBuild)
{
$previewLabel= "daily{0}" -f $previewLabel
}
$preReleaseVersion = "$previewPrefix-$previewLabel.$env:BUILD_BUILDID"
return $preReleaseVersion
}
# This function retrieves the appropriate svg to be used when presenting
# the daily test run badge
# the location in azure is public readonly
function Get-DailyBadge
{
param (
[Parameter(Mandatory=$true,Position=0)][ValidateSet("Pass","Fail")]$result
)
$PASS = "https://jimtru1979.blob.core.windows.net/badges/DailyBuild.Pass.svg"
$FAIL = "https://jimtru1979.blob.core.windows.net/badges/DailyBuild.Fail.svg"
if ( $result -eq "Pass" ) { $BadgeUrl = $PASS } else { $BadgeUrl = $FAIL }
$response = Invoke-WebRequest -Uri $BadgeUrl
if ( $response.StatusCode -ne 200 ) { throw "Could not read badge '$BadgeUrl'" }
$response.Content
}
# This function uses Azure REST api to update the daily test pass results
# it relies on writing a specific SVG into a constant location so the
# README.MD can report on the status of the daily test pass
# it also relies on two environment variables which need to be set in the
# Travis-CI config which is the account name and key for the azure blob location
#
# the best way to do this would be if travis-ci supported a webcall to get
# the status of cron_job builds, but it doesn't, so we have this
# also, since we can have a build on Linux which succeeds and one on macOS which
# doesn't we'll set the appropriate badge so the the README can pick it up
function Set-DailyBuildBadge
{
[CmdletBinding(SupportsShouldProcess=$true)]
param ( [Parameter(Mandatory=$true,Position=0)]$content )
$method = "PUT"
$headerDate = '2015-12-11'
$storageAccountName = $Env:TestResultAccountName
$storageAccountKey = $Env:TestResultAccountKey
# this is the url referenced in README.MD which displays the badge
$platform = if ( $IsLinux ) { "Linux" } else { "OSX" }
$Url = "https://jimtru1979.blob.core.windows.net/badges/DailyBuildStatus.${platform}.svg"
$body = $content
$bytes = ([System.Text.Encoding]::UTF8.GetBytes($body))
$contentLength = $bytes.length
$now = [datetime]::UtcNow.ToString("R", [System.Globalization.CultureInfo]::InvariantCulture)
$headers = @{
"x-ms-date" = $now
"cache-control" = "no-cache"
"x-ms-blob-type" = "BlockBlob"
"x-ms-version" = "$headerDate"
}
$contentType = "image/svg+xml"
# more info: https://docs.microsoft.com/rest/api/storageservices/fileservices/put-blob
$sb = [text.stringbuilder]::new()
# can't use AppendLine because the `r`n causes the command to fail, it must be `n and only `n
$null = $sb.Append("$method`n")
$null = $sb.Append("`n")
$null = $sb.Append("`n")
$null = $sb.Append("$contentLength`n")
$null = $sb.Append("`n")
$null = $sb.Append("$contentType`n")
$null = $sb.Append("`n")
$null = $sb.Append("`n")
$null = $sb.Append("`n")
$null = $sb.Append("`n")
$null = $sb.Append("`n")
$null = $sb.Append("`n")
$null = $sb.Append("x-ms-blob-type:" + $headers["x-ms-blob-type"] + "`n")
$null = $sb.Append("x-ms-date:" + $headers["x-ms-date"] + "`n")
$null = $sb.Append("x-ms-version:" + $headers["x-ms-version"] + "`n")
$null = $sb.Append("/" + $storageAccountName + ([System.Uri]::new($url).AbsolutePath))
$dataToMac = [System.Text.Encoding]::UTF8.GetBytes($sb.ToString())
$accountKeyBytes = [System.Convert]::FromBase64String($storageAccountKey)
$hmac = [System.Security.Cryptography.HMACSHA256]::new($accountKeyBytes)
$signature = [System.Convert]::ToBase64String($hmac.ComputeHash($dataToMac))
$headers["Authorization"] = "SharedKey " + $storageAccountName + ":" + $signature
if ( $PSCmdlet.ShouldProcess("$signaturestring"))
{
# if this fails, it will throw, you can't check the response for a success code
$response = Invoke-RestMethod -Uri $Url -Method $method -headers $headers -Body $body -ContentType "image/svg+xml"
}
}
# https://docs.travis-ci.com/user/environment-variables/
# TRAVIS_EVENT_TYPE: Indicates how the build was triggered.
# One of push, pull_request, api, cron.
$isPR = $env:TRAVIS_EVENT_TYPE -eq 'pull_request'
$commitMessage = [string]::Empty
# For PRs, Travis-ci strips out [ and ] so read the message directly from git
if($env:TRAVIS_EVENT_TYPE -eq 'pull_request' -or $env:BUILD_REASON)
{
$commitId = $null
if ($env:TRAVIS_EVENT_TYPE)
{
# We are in Travis-CI
$commitId = $env:TRAVIS_PULL_REQUEST_SHA
# If the current job is a pull request, the env variable 'TRAVIS_PULL_REQUEST_SHA' contains
# the commit SHA of the HEAD commit of the PR.
$commitMessage = git log --format=%B -n 1 $commitId
Write-Log -message "commitMessage: $commitMessage"
}
elseif($env:TF_BUILD)
{
if($env:BUILD_SOURCEVERSIONMESSAGE -match 'Merge\s*([0-9A-F]*)')
{
# We are in VSTS and have a commit ID in the Source Version Message
$commitId = $Matches[1]
$commitMessage = git log --format=%B -n 1 $commitId
}
else
{
Write-Log "Unknown BUILD_SOURCEVERSIONMESSAGE format '$env:BUILD_SOURCEVERSIONMESSAGE'" -Verbose
}
}
}
else
{
$commitMessage = $env:TRAVIS_COMMIT_MESSAGE
}
# Run a full build if the build was trigger via cron, api or the commit message contains `[Feature]`
# or the environment variable `FORCE_FEATURE` equals `True`
$hasFeatureTag = $commitMessage -match '\[feature\]' -or $env:FORCE_FEATURE -eq 'True'
# Run a packaging if the commit message contains `[Package]`
# or the environment variable `FORCE_PACKAGE` equals `True`
$hasPackageTag = $commitMessage -match '\[package\]' -or $env:FORCE_PACKAGE -eq 'True'
$createPackages = -not $isPr -or $hasPackageTag
$hasRunFailingTestTag = $commitMessage -match '\[includeFailingTest\]'
$isDailyBuild = $env:TRAVIS_EVENT_TYPE -eq 'cron' -or $env:TRAVIS_EVENT_TYPE -eq 'api' -or $env:BUILD_REASON -eq 'Schedule'
# only update the build badge for the cron job
$cronBuild = $env:TRAVIS_EVENT_TYPE -eq 'cron' -or $env:BUILD_REASON -eq 'Schedule'
$isFullBuild = $isDailyBuild -or $hasFeatureTag
if($Stage -eq 'Bootstrap')
{
if($cronBuild -and $env:TF_BUILD)
{
Write-Host "##vso[build.updatebuildnumber]Daily-$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))"
}
Write-Host -Foreground Green "Executing travis.ps1 -BootStrap `$isPR='$isPr' - $commitMessage"
# Make sure we have all the tags
Sync-PSTags -AddRemoteIfMissing
Start-PSBootstrap -Package:$createPackages
}
elseif($Stage -eq 'Build')
{
$releaseTag = Get-ReleaseTag
Write-Host -Foreground Green "Executing travis.ps1 `$isPR='$isPr' `$isFullBuild='$isFullBuild' - $commitMessage"
$originalProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
## We use CrossGen build to run tests only if it's the daily build.
Start-PSBuild -CrossGen -PSModuleRestore -CI -ReleaseTag $releaseTag -Configuration 'Release'
}
finally{
$ProgressPreference = $originalProgressPreference
}
$output = Split-Path -Parent (Get-PSOutput -Options (Get-PSOptions))
$testResultsNoSudo = "$pwd/TestResultsNoSudo.xml"
$testResultsSudo = "$pwd/TestResultsSudo.xml"
$excludeTag = @('RequireSudoOnUnix')
$noSudoPesterParam = @{
'BinDir' = $output
'PassThru' = $true
'Terse' = $true
'Tag' = @()
'ExcludeTag' = $excludeTag
'OutputFile' = $testResultsNoSudo
}
if ($isFullBuild) {
$noSudoPesterParam['Tag'] = @('CI','Feature','Scenario')
} else {
$noSudoPesterParam['Tag'] = @('CI')
$noSudoPesterParam['ThrowOnFailure'] = $true
}
if ($hasRunFailingTestTag) {
$noSudoPesterParam['IncludeFailingTest'] = $true
}
# Get the experimental feature names and the tests associated with them
$ExperimentalFeatureTests = Get-ExperimentalFeatureTests
# Running tests which do not require sudo.
$pesterPassThruNoSudoObject = Start-PSPester @noSudoPesterParam -Title 'Pester No Sudo'
# Running tests that do not require sudo, with specified experimental features enabled
$noSudoResultsWithExpFeatures = @()
foreach ($entry in $ExperimentalFeatureTests.GetEnumerator()) {
$featureName = $entry.Key
$testFiles = $entry.Value
$expFeatureTestResultFile = "$pwd\TestResultsNoSudo.$featureName.xml"
$noSudoPesterParam['OutputFile'] = $expFeatureTestResultFile
$noSudoPesterParam['ExperimentalFeatureName'] = $featureName
if ($testFiles.Count -eq 0) {
# If an empty array is specified for the feature name, we run all tests with the feature enabled.
# This allows us to prevent regressions to a critical engine experimental feature.
$noSudoPesterParam.Remove('Path')
} else {
# If a non-empty string or array is specified for the feature name, we only run those test files.
$noSudoPesterParam['Path'] = $testFiles
}
$passThruResult = Start-PSPester @noSudoPesterParam -Title "Pester Experimental No Sudo - $featureName"
$noSudoResultsWithExpFeatures += $passThruResult
}
# Running tests, which require sudo.
$sudoPesterParam = $noSudoPesterParam.Clone()
$sudoPesterParam.Remove('Path')
$sudoPesterParam['Tag'] = @('RequireSudoOnUnix')
$sudoPesterParam['ExcludeTag'] = @()
$sudoPesterParam['Sudo'] = $true
$sudoPesterParam['OutputFile'] = $testResultsSudo
$pesterPassThruSudoObject = Start-PSPester @sudoPesterParam -Title 'Pester Sudo'
# Running tests that require sudo, with specified experimental features enabled
$sudoResultsWithExpFeatures = @()
foreach ($entry in $ExperimentalFeatureTests.GetEnumerator()) {
$featureName = $entry.Key
$testFiles = $entry.Value
$expFeatureTestResultFile = "$pwd\TestResultsSudo.$featureName.xml"
$sudoPesterParam['OutputFile'] = $expFeatureTestResultFile
$sudoPesterParam['ExperimentalFeatureName'] = $featureName
if ($testFiles.Count -eq 0) {
# If an empty array is specified for the feature name, we run all tests with the feature enabled.
# This allows us to prevent regressions to a critical engine experimental feature.
$sudoPesterParam.Remove('Path')
} else {
# If a non-empty string or array is specified for the feature name, we only run those test files.
$sudoPesterParam['Path'] = $testFiles
}
$passThruResult = Start-PSPester @sudoPesterParam -Title "Pester Experimental Sudo - $featureName"
$sudoResultsWithExpFeatures += $passThruResult
}
# Determine whether the build passed
try {
$allTestResultsWithNoExpFeature = @($pesterPassThruNoSudoObject, $pesterPassThruSudoObject)
$allTestResultsWithExpFeatures = $noSudoResultsWithExpFeatures + $sudoResultsWithExpFeatures
# this throws if there was an error
$allTestResultsWithNoExpFeature | ForEach-Object { Test-PSPesterResults -ResultObject $_ }
$allTestResultsWithExpFeatures | ForEach-Object { Test-PSPesterResults -ResultObject $_ -CanHaveNoResult }
$result = "PASS"
}
catch {
$resultError = $_
$result = "FAIL"
}
try {
$ParallelXUnitTestResultsFile = "$pwd/ParallelXUnitTestResults.xml"
Start-PSxUnit -ParallelTestResultsFile $ParallelXUnitTestResultsFile
# If there are failures, Test-XUnitTestResults throws
Test-XUnitTestResults -TestResultsFile $ParallelXUnitTestResultsFile
}
catch {
$result = "FAIL"
if (!$resultError)
{
$resultError = $_
}
}
if ($createPackages) {
$packageParams = @{}
$packageParams += @{ReleaseTag=$releaseTag}
# Only build packages for branches, not pull requests
$packages = @(Start-PSPackage @packageParams -SkipReleaseChecks)
foreach($package in $packages)
{
# Publish the packages to the nuget feed if:
# 1 - It's a Daily build (already checked, for not a PR)
# 2 - We have the info to publish (NUGET_KEY and NUGET_URL)
# 3 - it's a nupkg file
if($isDailyBuild -and $NugetKey -and $env:NUGET_URL -and [system.io.path]::GetExtension($package) -ieq '.nupkg')
{
Write-Log "pushing $package to $env:NUGET_URL"
Start-NativeExecution -sb {dotnet nuget push $package --api-key $NugetKey --source "$env:NUGET_URL/api/v2/package"} -IgnoreExitcode
}
}
if ($IsLinux)
{
# Create and package Raspbian .tgz
Start-PSBuild -PSModuleRestore -Clean -Runtime linux-arm -Configuration 'Release'
Start-PSPackage @packageParams -Type tar-arm -SkipReleaseChecks
}
if ($isDailyBuild)
{
New-TestPackage -Destination $pwd
}
}
# if the tests did not pass, throw the reason why
if ( $result -eq "FAIL" ) {
Throw $resultError
}
}
elseif($Stage -in 'Failure', 'Success')
{
$result = 'PASS'
if($Stage -eq 'Failure')
{
$result = 'FAIL'
}
if ($cronBuild) {
# update the badge if you've done a cron build, these are not fatal issues
try {
$svgData = Get-DailyBadge -result $result
if ( ! $svgData ) {
write-warning "Could not retrieve $result badge"
}
else {
Write-Log "Setting status badge to '$result'"
Set-DailyBuildBadge -content $svgData
}
}
catch {
Write-Warning "Could not update status badge: $_"
}
try {
Send-DailyWebHook -result $result
}
catch {
Write-Warning "Could not send webhook: $_"
}
}
else {
Write-Log 'We only send bagde or webhook update for Cron builds'
}
}