File size: 14,044 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
param(
    [Parameter(Mandatory = $true, Position = 0)] $coverallsToken,
    [Parameter(Mandatory = $true, Position = 1)] $codecovToken,
    [Parameter(Position = 2)] $azureLogDrive = "L:\",
    [switch] $SuppressQuiet
)

# Read the XML and create a dictionary for FileUID -> file full path.
function GetFileTable()
{
    $files = $script:covData | Select-Xml './/File'
    foreach($file in $files)
    {
        $script:fileTable[$file.Node.uid] = $file.Node.fullPath
    }
}

# Get sequence points for a particular file
function GetSequencePointsForFile([string] $fileId)
{
    $lineCoverage = [System.Collections.Generic.Dictionary[string,int]]::new()

    $sequencePoints = $script:covData | Select-Xml ".//SequencePoint[@fileid = '$fileId']"

    if($sequencePoints.Count -gt 0)
    {
        foreach($sp in $sequencePoints)
        {
            $visitedCount = [int]::Parse($sp.Node.vc)
            $lineNumber = [int]::Parse($sp.Node.sl)
            $lineCoverage[$lineNumber] += [int]::Parse($visitedCount)
        }

        return $lineCoverage
    }
}

#### Convert the OpenCover XML output for CodeCov.io JSON format as it is smaller.
function ConvertTo-CodeCovJson
{
    param(
        [string] $Path,
        [string] $DestinationPath
    )

    $Script:fileTable = [ordered]@{}
    $Script:covData = [xml] (Get-Content -ReadCount 0 -Raw -Path $Path)
    $totalCoverage = [PSCustomObject]::new()
    $totalCoverage | Add-Member -MemberType NoteProperty -Name "coverage" -Value ([PSCustomObject]::new())

    ## Populate the dictionary with file uid and file names.
    GetFileTable
    $keys = $Script:fileTable.Keys
    $progress=0
    foreach($f in $keys)
    {
        Write-Progress -Id 1 -Activity "Converting to JSON" -Status 'Converting' -PercentComplete ($progress * 100 / $keys.Count)
        $fileCoverage = GetSequencePointsForFile -fileId $f
        $fileName = $Script:fileTable[$f]
        $previousFileCoverage = $totalCoverage.coverage.${fileName}

        ##Update the values for the lines in the file.
        if($null -ne $previousFileCoverage)
        {
            foreach($lineNumber in $fileCoverage.Keys)
            {
                $previousFileCoverage[$lineNumber] += [int]::Parse($fileCoverage[$lineNumber])
            }
        }
        else ## the file is new, so add the values as a new NoteProperty.
        {
            $totalCoverage.coverage | Add-Member -MemberType NoteProperty -Value $fileCoverage -Name $fileName
        }

        $progress++
    }

    Write-Progress -Id 1 -Completed -Activity "Converting to JSON"

    $totalCoverage | ConvertTo-Json -Depth 5 -Compress | Out-File $DestinationPath -Encoding ascii
}

function Write-LogPassThru
{
    Param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position = 0)]
        [string] $Message,
        $Path = "$env:Temp\CodeCoverageRunLogs.txt"
    )

    $message = "{0:d} - {0:t} : {1}" -f ([datetime]::now),$message
    Add-Content -Path $Path -Value $Message -PassThru -Force
}

function Push-CodeCovData
{
    param (
        [Parameter(Mandatory=$true)]$file,
        [Parameter(Mandatory=$true)]$CommitID,
        [Parameter(Mandatory=$false)]$token,
        [Parameter(Mandatory=$false)]$Branch = "master"
    )
    $VERSION="64c1150"
    $url="https://codecov.io"

    $query = "package=bash-${VERSION}&token=${token}&branch=${Branch}&commit=${CommitID}&build=&build_url=&tag=&slug=&yaml=&service=&flags=&pr=&job="
    $uri = "$url/upload/v2?${query}"
    $response = Invoke-WebRequest -Method Post -InFile $file -Uri $uri

    if ( $response.StatusCode -ne 200 )
    {
        Write-LogPassThru -Message "Upload failed for upload uri: $uploaduri"
        throw "upload failed"
    }
}

Write-LogPassThru -Message "***** New Run *****"

Write-LogPassThru -Message "Forcing winrm quickconfig as it is required for remoting tests."
winrm quickconfig -force

$appVeyorUri = "https://ci.appveyor.com/api"
$project = Invoke-RestMethod -Method Get -Uri "${appVeyorUri}/projects/PowerShell/powershell-f975h"
$jobId = $project.build.jobs[0].jobId

$appVeyorBaseUri = "${appVeyorUri}/buildjobs/${jobId}/artifacts"
$codeCoverageZip = "${appVeyorBaseUri}/CodeCoverage.zip"
$testContentZip =  "${appVeyorBaseUri}/tests.zip"
$openCoverZip =    "${appVeyorBaseUri}/OpenCover.zip"

Write-LogPassThru -Message "codeCoverageZip: $codeCoverageZip"
Write-LogPassThru -Message "testcontentZip: $testContentZip"
Write-LogPassThru -Message "openCoverZip: $openCoverZip"

$outputBaseFolder = "$env:Temp\CC"
$null = New-Item -ItemType Directory -Path $outputBaseFolder -Force

$openCoverPath = "$outputBaseFolder\OpenCover"
$testRootPath = "$outputBaseFolder\tests"
$testPath = "$testRootPath\powershell"
$psBinPath = "$outputBaseFolder\PSCodeCoverage"
$openCoverTargetDirectory = "$outputBaseFolder\OpenCoverToolset"
$outputLog = "$outputBaseFolder\CodeCoverageOutput.xml"
$elevatedLogs = "$outputBaseFolder\TestResults_Elevated.xml"
$unelevatedLogs = "$outputBaseFolder\TestResults_Unelevated.xml"
$testToolsPath = "$testRootPath\tools"
$jsonFile = "$outputBaseFolder\CC.json"

try
{
    ## Github needs TLS1.2 whereas the defaults for Invoke-WebRequest do not have TLS1.2
    $prevSecProtocol = [System.Net.ServicePointManager]::SecurityProtocol

    [System.Net.ServicePointManager]::SecurityProtocol =
        [System.Net.ServicePointManager]::SecurityProtocol -bor
        [System.Security.Authentication.SslProtocols]::Tls12 -bor
        [System.Security.Authentication.SslProtocols]::Tls11

    # first thing to do is to be sure that no processes are running which will cause us issues
    Get-Process pwsh -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction Stop

    ## This is required so we do not keep on merging coverage reports.
    if(Test-Path $outputLog)
    {
        Remove-Item $outputLog -Force -ErrorAction SilentlyContinue
    }

    $oldErrorActionPreference = $ErrorActionPreference
    $ErrorActionPreference = 'Stop'
    $oldProgressPreference = $ProgressPreference
    $ProgressPreference = 'SilentlyContinue'
    Write-LogPassThru -Message "Starting downloads."

    $CoverageZipFilePath = "$outputBaseFolder\PSCodeCoverage.zip"
    if(Test-Path $CoverageZipFilePath)
    {
        Remove-Item $CoverageZipFilePath -Force
    }
    Invoke-WebRequest -Uri $codeCoverageZip -OutFile "$outputBaseFolder\PSCodeCoverage.zip"

    $TestsZipFilePath = "$outputBaseFolder\tests.zip"
    if(Test-Path $TestsZipFilePath)
    {
        Remove-Item $TestsZipFilePath -Force
    }
    Invoke-WebRequest -Uri $testContentZip -OutFile $TestsZipFilePath

    $OpenCoverZipFilePath = "$outputBaseFolder\OpenCover.zip"
    if(Test-Path $OpenCoverZipFilePath)
    {
        Remove-Item $OpenCoverZipFilePath -Force
    }
    Invoke-WebRequest -Uri $openCoverZip -OutFile $OpenCoverZipFilePath

    Write-LogPassThru -Message "Downloads complete. Starting expansion"

    if(Test-Path $psBinPath)
    {
        Remove-Item -Force -Recurse $psBinPath
    }
    Expand-Archive -Path $CoverageZipFilePath -DestinationPath "$psBinPath" -Force

    if(Test-Path $testRootPath)
    {
        Remove-Item -Force -Recurse $testRootPath
    }
    Expand-Archive -Path $TestsZipFilePath -DestinationPath $testRootPath -Force

    if(Test-Path $openCoverPath)
    {
        Remove-Item -Force -Recurse $openCoverPath
    }
    Expand-Archive -Path $OpenCoverZipFilePath -DestinationPath $openCoverPath -Force
    Write-LogPassThru -Message "Expansion complete."

    if(Test-Path $elevatedLogs)
    {
        Remove-Item -Force -Recurse $elevatedLogs
    }

    if(Test-Path $unelevatedLogs)
    {
        Remove-Item -Force -Recurse $unelevatedLogs
    }

    if(Test-Path $outputLog)
    {
        Remove-Item $outputLog -Force -ErrorAction SilentlyContinue
    }

    Import-Module "$openCoverPath\OpenCover" -Force
    Install-OpenCover -TargetDirectory $openCoverTargetDirectory -force
    Write-LogPassThru -Message "OpenCover installed."

    Write-LogPassThru -Message "TestPath : $testPath"
    Write-LogPassThru -Message "openCoverPath : $openCoverTargetDirectory\OpenCover"
    Write-LogPassThru -Message "psbinpath : $psBinPath"
    Write-LogPassThru -Message "elevatedLog : $elevatedLogs"
    Write-LogPassThru -Message "unelevatedLog : $unelevatedLogs"
    Write-LogPassThru -Message "TestToolsPath : $testToolsPath"

    $openCoverParams = @{outputlog = $outputLog;
        TestPath = $testPath;
        OpenCoverPath = "$openCoverTargetDirectory\OpenCover";
        PowerShellExeDirectory = "$psBinPath";
        PesterLogElevated = $elevatedLogs;
        PesterLogUnelevated = $unelevatedLogs;
        TestToolsModulesPath = "$testToolsPath\Modules";
    }

    if($SuppressQuiet)
    {
        $openCoverParams.Add('SuppressQuiet', $true)
    }

    # grab the commitID, we need this to grab the right sources
    $assemblyLocation = & "$psBinPath\pwsh.exe" -noprofile -command { Get-Item ([psobject].Assembly.Location) }
    $productVersion = $assemblyLocation.VersionInfo.productVersion
    $commitId = $productVersion.split(" ")[-1]

    Write-LogPassThru -Message "Using GitCommitId: $commitId"

    # download the src directory
    try
    {
        $gitexe = "C:\Program Files\git\bin\git.exe"
        # operations relative to where the test location is.
        # some tests rely on source files being available in $outputBaseFolder/test
        Push-Location $outputBaseFolder

        # clean up partial repo clone before starting
        $cleanupDirectories = "${outputBaseFolder}/.git",
            "${outputBaseFolder}/src",
            "${outputBaseFolder}/assets"
        foreach($directory in $cleanupDirectories)
        {
            if ( Test-Path "$directory" )
            {
                Remove-Item -Force -Recurse "$directory"
            }
        }

        Write-LogPassThru -Message "initializing repo in $outputBaseFolder"
        & $gitexe init
        Write-LogPassThru -Message "git operation 'init' returned $LASTEXITCODE"

        Write-LogPassThru -Message "adding remote"
        & $gitexe remote add origin https://github.com/PowerShell/PowerShell
        Write-LogPassThru -Message "git operation 'remote add' returned $LASTEXITCODE"

        Write-LogPassThru -Message "setting sparse-checkout"
        & $gitexe config core.sparsecheckout true
        Write-LogPassThru -Message "git operation 'set sparse-checkout' returned $LASTEXITCODE"

        Write-LogPassThru -Message "pulling sparse repo"
        "/src" | Out-File -Encoding ascii .git\info\sparse-checkout -Force
        "/assets" | Out-File -Encoding ascii .git\info\sparse-checkout -Append
        & $gitexe pull origin master
        Write-LogPassThru -Message "git operation 'pull' returned $LASTEXITCODE"

        Write-LogPassThru -Message "checkout commit $commitId"
        & $gitexe checkout $commitId
        Write-LogPassThru -Message "git operation 'checkout' returned $LASTEXITCODE"
    }
    finally
    {
        Pop-Location
    }

    $openCoverParams | Out-String | Write-LogPassThru
    Write-LogPassThru -Message "Starting test run."

    try {
        # now invoke opencover
        Invoke-OpenCover @openCoverParams | Out-String | Write-LogPassThru
    }
    catch {
        ("ERROR: " + $_.ScriptStackTrace) | Write-LogPassThru
        $_ 2>&1 | Out-String -Stream | %{ "ERROR: $_" } | Write-LogPassThru
    }

    if(Test-Path $outputLog)
    {
        Write-LogPassThru -Message (Get-ChildItem $outputLog).FullName
    }

    Write-LogPassThru -Message "Test run done."

    Write-LogPassThru -Message $commitId

    $commitInfo = Invoke-RestMethod -Method Get "https://api.github.com/repos/powershell/powershell/git/commits/$commitId"
    $message = ($commitInfo.message).replace("`n", " ")

    Write-LogPassThru -Message "Uploading to CodeCov"
    if ( Test-Path $outputLog ) {
        ConvertTo-CodeCovJson -Path $outputLog -DestinationPath $jsonFile
        Push-CodeCovData -file $jsonFile -CommitID $commitId -token $codecovToken -Branch 'master'

        Write-LogPassThru -Message "Upload complete."
    }
    else {
        Write-LogPassThru -Message "ERROR: Could not find $outputLog - no upload"
    }
}
catch
{
    Write-LogPassThru -Message $_
}
finally
{
    ## reset TLS1.2 settings.
    [System.Net.ServicePointManager]::SecurityProtocol = $prevSecProtocol

    # the powershell execution should be done, be sure that there are no PowerShell test executables running because
    # they will cause subsequent coverage runs to behave poorly. Make sure that the path is properly formatted, and
    # we need to use like rather than match because on Windows, there will be "\" as path separators which would need
    # escaping for -match
    $ResolvedPSBinPath = (Resolve-Path ${psbinpath}).Path
    Get-Process PowerShell | Where-Object { $_.Path -like "*${ResolvedPSBinPath}*" } | Stop-Process -Force -ErrorAction Continue

    ## See if Azure log directory is mounted
    if(Test-Path $azureLogDrive)
    {
        ##Create yyyy-dd folder
        $monthFolder = "{0:yyyy-MM}" -f [datetime]::Now
        $monthFolderFullPath = New-Item -Path (Join-Path $azureLogDrive $monthFolder) -ItemType Directory -Force
        $windowsFolderPath = New-Item (Join-Path $monthFolderFullPath "Windows") -ItemType Directory -Force

        $destinationPath = Join-Path $env:Temp ("CodeCoverageLogs-{0:yyyy_MM_dd}-{0:hh_mm_ss}.zip" -f [datetime]::Now)
        Compress-Archive -Path $elevatedLogs,$unelevatedLogs,$outputLog -DestinationPath $destinationPath
        Copy-Item $destinationPath $windowsFolderPath -Force -ErrorAction SilentlyContinue

        Remove-Item -Path $destinationPath -Force -ErrorAction SilentlyContinue
    }

    Write-LogPassThru -Message "**** COMPLETE ****"

    ## Disable the cleanup till we stabilize.
    #Remove-Item -recurse -force -path $outputBaseFolder
    $ErrorActionPreference = $oldErrorActionPreference
    $ProgressPreference = $oldProgressPreference
}