PSCodeCovIo.psm1

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
# Copied from https://github.com/PowerShell/DscResource.Tests/blob/491688867dc53894b92ca53520a18d145deb7760/DscResource.CodeCoverage/CodeCovIo.psm1
# Modified to work cross-platform
#
# https://github.com/PowerShell/DscResource.Tests/blob/491688867dc53894b92ca53520a18d145deb7760/LICENSE
#
# The MIT License (MIT)
#
# Copyright (c) 2015 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

<#
  .SYNOPSIS
  Updates a hash table with the Unique file lines
  Structure:
  RootTable.[FileKey].[SubTable].[Line]

  .PARAMETER FileLine
  The table to update

  .PARAMETER Command
  The list of Command from pester to update the table based on

  .PARAMETER RepoRoot
  The path to the root of the repo. This part of the path will not be included in the report. Needed to normalize all the reports.

  .PARAMETER TableName
  The path of the file to write the report to.
#>

function Add-UniqueFileLineToTable {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [HashTable]
        $FileLine,

        [Parameter(Mandatory = $true)]
        [Object]
        $Command,

        [Parameter(Mandatory = $true)]
        [String]
        $RepoRoot,

        [Parameter(Mandatory = $true)]
        [String]
        $TableName
    )

    # file paths need to be relative to repo root when querying GIT
    Push-Location -LiteralPath $RepoRoot
    try {
        Write-Verbose -Message "running git ls-files" -Verbose

        # Get the list of files as Git sees them
        $fileKeys = git ls-files

        # Populate the sub-table
        foreach ($command in $Command) {
            #Find the file as Git sees it
            $file = $command.File
            $fileKey = $file.replace($RepoRoot, '').replace('\', '/').TrimStart('/')
            $fileKey = $fileKeys.where{$_ -like $fileKey}

            if ($null -eq $fileKey) {
                Write-Warning -Message "Unexpected error filekey was null"
                continue
            }
            elseif ($fileKey.Count -ne 1) {
                Write-Warning -Message "Unexpected error, more than one git file matched file ($file): $($fileKey -join ', ')"
                continue
            }

            $fileKey = $fileKey | Select-Object -First 1

            if (!$FileLine.ContainsKey($fileKey)) {
                $FileLine.add($fileKey, @{ $TableName = @{}})
            }

            if (!$FileLine.$fileKey.ContainsKey($TableName)) {
                $FileLine.$fileKey.Add($TableName, @{})
            }

            $lines = $FileLine.($fileKey).$TableName
            $lineKey = $($command.line)
            if (!$lines.ContainsKey($lineKey)) {
                $lines.Add($lineKey, 1)
            }
            else {
                $lines.$lineKey ++
            }
        }
    }
    finally {
        Pop-Location
    }
}

<#
  .SYNOPSIS
  Tests if the specified property is a CodeCoverage object
  For use in a ValidateScript attribute

  .PARAMETER CodeCoverage
  The CodeCoverage property of the output of Invoke-Pester with the -PassThru and -CodeCoverage options

#>

function Test-CodeCoverage {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [Object]
        $CodeCoverage
    )

    if (!($CodeCoverage | Get-Member -Name MissedCommands)) {
        throw 'Must be a Pester CodeCoverage object'
    }

    return $true
}

<#
  .SYNOPSIS
  Exports a Pester CodeCoverage report as a CodeCov.io json report

  .PARAMETER CodeCoverage
  The CodeCoverage property of the output of Invoke-Pester with the -PassThru and -CodeCoverage options

  .PARAMETER RepoRoot
  The path to the root of the repo. This part of the path will not be included in the report. Needed to normalize all the reports.

  .PARAMETER Path
  The path of the file to write the report to.
#>

function Export-CodeCovIoJson {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateScript( {Test-CodeCoverage -CodeCoverage $_})]
        [Object]
        $CodeCoverage,

        [Parameter(Mandatory = $true)]
        [String]
        $RepoRoot,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [String]
        $Path = (Join-Path -Path $env:TEMP -ChildPath 'codeCov.json')
    )

    Write-Verbose -Message "RepoRoot: $RepoRoot"

    # Get a list of all unique files
    $files = @()
    foreach ($file in ($CodeCoverage.MissedCommands | Select-Object -ExpandProperty File -Unique)) {
        if ($files -notcontains $file) {
            $files += $file
        }
    }

    foreach ($file in ($CodeCoverage.HitCommands | Select-Object -ExpandProperty File -Unique)) {
        if ($files -notcontains $file) {
            $files += $file
        }
    }

    # A table of the file key then a sub-tables of `misses` and `hits` lines.
    $FileLine = @{}

    # define common parameters
    $addUniqueFileLineParams = @{
        FileLine = $FileLine
        RepoRoo  = $RepoRoot
    }

    <#
        Basically indexing all the hit and miss lines by file and line.
        Populate the misses sub-table
    #>

    Add-UniqueFileLineToTable -Command $CodeCoverage.MissedCommands -TableName 'misses' @addUniqueFileLineParams

    # Populate the hits sub-table
    Add-UniqueFileLineToTable -Command $CodeCoverage.HitCommands -TableName 'hits' @addUniqueFileLineParams

    # Create the results structure
    $resultLineData = @{}
    $resultMessages = @{}
    $result = @{
        coverage = $resultLineData
        messages = $resultMessages
    }

    foreach ($file in $FileLine.Keys) {
        $hit = 0
        $partial = 0
        $missed = 0
        Write-Verbose -Message "summarizing for file: $file"

        # Get the hits, if they exist
        $hits = @{}
        if ($FileLine.$file.ContainsKey('hits')) {
            $hits = $FileLine.$file.hits
        }

        # Get the misses, if they exist
        $misses = @{}
        if ($FileLine.$file.ContainsKey('misses')) {
            $misses = $FileLine.$file.misses
        }

        Write-Verbose -Message "fileKeys: $($FileLine.$file.Keys)"
        $max = $hits.Keys | Sort-Object -Descending | Select-Object -First 1
        $maxMissLine = $misses.Keys | Sort-Object -Descending | Select-Object -First 1

        <#
            if max missed line is greater than maxed hit line
            used max missed line as the max line
        #>

        if ($maxMissLine -gt $max) {
            $max = $maxMissLine
        }

        $lineData = @()
        $messages = @{}

        <#
            produce the results
            start at line 0 per codecov doc
        #>

        for ($lineNumber = 0; $lineNumber -le $max; $lineNumber++) {
            $hitInfo = $null
            $missInfo = $null
            switch ($true) {
                # Hit
                ($hits.ContainsKey($lineNumber) -and ! $misses.ContainsKey($lineNumber)) {
                    Write-Verbose -Message "Got code coverage hit at $lineNumber"
                    $lineData += "$($hits.$lineNumber)"
                }

                # Miss
                ($misses.ContainsKey($lineNumber) -and ! $hits.ContainsKey($lineNumber)) {
                    Write-Verbose -Message "Got code coverage miss at $lineNumber"
                    $lineData += '0'
                }

                # Partial Hit
                ($misses.ContainsKey($lineNumber) -and $hits.ContainsKey($lineNumber)) {
                    Write-Verbose -Message "Got code coverage partial at $lineNumber"

                    $missInfo = $misses.$lineNumber
                    $hitInfo = $hits.$lineNumber
                    $lineData += "$hitInfo/$($hitInfo+$missInfo)"
                }

                # Non-Code Line
                (!$misses.ContainsKey($lineNumber) -and !$hits.ContainsKey($lineNumber)) {
                    Write-Verbose -Message "Got non-code at $lineNumber"

                    <#
                        If I put an actual null in an array ConvertTo-Json just leaves it out
                        I'll put this string in and clean it up later.
                    #>

                    $lineData += '!null!'
                }

                default {
                    throw "Unexpected error occured generating codeCov.io report for $file at line $lineNumber with hits: $($hits.ContainsKey($lineNumber)) and misses: $($misses.ContainsKey($lineNumber))"
                }
            }
        }

        $resultLineData.Add($file, $lineData)
        $resultMessages.add($file, $messages)
    }

    $commitOutput = @(&git log -1 --pretty=format:%H)
    $commit = $commitOutput[0]

    Write-Verbose -Message "Branch: $Branch"

    $json = $result | ConvertTo-Json
    $json = $json.Replace('"!null!"', 'null')

    $json | Out-File -Encoding ascii -LiteralPath $Path -Force
    return $Path
}