-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc1-format.go
387 lines (340 loc) · 12.6 KB
/
c1-format.go
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
package main
import (
"encoding/json"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"log"
"math"
"os"
"strconv"
"strings"
)
// Ruby's simplecov coveraage.json struct types list
type Rspec struct {
Rspec RubyCoverage `json:"RSpec"`
}
type RubyCoverage struct {
Coverage LineBranchMap `json:"coverage"`
Timestamp int64 `json:"timestamp"`
}
type LineBranchMap map[string]RubyLineBranch
type RubyLineBranch struct {
Lines []int64 `json:"lines"`
RubyBranches RubyBranchStartMap `json:"branches"`
}
type RubyBranchStartMap map[string]RubyBranchMap
type RubyBranchMap map[string]int
// struct to create generic branch coerage report for sonarqube
type coverage struct {
Version string `xml:"version,attr"`
File []FileCoverage `xml:"file"`
}
type FileCoverage struct {
Path string `xml:"path,attr"`
LineToCover []LineToCover `xml:"lineToCover"`
}
type LineToCover struct {
LineNumber string `xml:"lineNumber,attr"`
Covered string `xml:"covered,attr"`
BranchesToCover string `xml:"branchesToCover,attr"`
CoveredBranches string `xml:"coveredBranches,attr"`
}
// struct for creation of all-branch-cover.json file to find full branch coverage rate
type BranchCoverageData struct {
Start string `json:"Start"`
Code string `json:"Code"`
TrueCount int `json:"TrueCount"`
FalseCount int `json:"FalseCount"`
}
type BranchCoverageDataCoverage struct {
Filename string `json:"filename"`
Covered int `json:"covered"`
BranchesToCover int64 `json:"total"`
CoverageRate float64 `json:"coverageRate"`
CoverageData []*BranchCoverageData `json:"coverageData"`
}
type BranchCoverage struct {
CoverageRate float64 `json:"coverageRate"`
BranchesToCover int64 `json:"totalBranch"`
TotalCoveredBranch int `json:"totalCoveredBranch"`
AllData []BranchCoverageDataCoverage `json:"allData"`
}
const EMPTY_CHECK = 0
func main() {
// Get command line arguments
packageName := flag.String("packageName", "", "")
isUpdateJson := flag.Bool("isUpdateJson", false, "")
flag.Parse()
if !fileExists(*packageName+"/branch-cover.json") && *packageName != "c1-ruby" {
return
}
var currentContent []byte
var err error
if *packageName == "c1-ruby" {
currentContent, err = ioutil.ReadFile("coverage/.resultset.json")
} else {
currentContent, err = ioutil.ReadFile(*packageName + "/branch-cover.json")
}
if err != nil {
log.Fatal("Error when opening file: ", err)
}
if len(currentContent) == EMPTY_CHECK {
log.Printf("Empty content")
var filelemList []FileCoverage
if *packageName == "./test-results" {
createXmlFile(filelemList, "test-results")
} else if *packageName == "c1-ruby" {
createXmlFile(filelemList, "coverage")
}
return
}
var payloadCurrent []*BranchCoverageData
var newpayloadCurrent []*BranchCoverageData
var allDataCover []BranchCoverageDataCoverage
if !(*isUpdateJson) {
var filenamecover string
var totalBranchInFile int64
var coveredBranchInFile int
var totalBranch int64
var coveredBranch int
if *packageName == "./test-results" {
err = json.NewDecoder(strings.NewReader(string(currentContent[:]))).Decode(&payloadCurrent)
if err != nil {
log.Fatal("Error while reading .resultset.json file\n", err)
}
if err != nil {
log.Fatal("Error during Unmarshal() of currentContent: ", err)
}
// To generate xml file atlast
var fileElementList []FileCoverage
for i := 0; i < len(payloadCurrent); i++ {
lineNumber := payloadCurrent[i].Start
fileName := strings.Split(lineNumber, ":")[0]
if (len(filenamecover) > 0 && (fileName != filenamecover)) || i == len(payloadCurrent)-1 {
var branchCoverageDataCoverage BranchCoverageDataCoverage
branchCoverageDataCoverage.Filename = filenamecover
branchCoverageDataCoverage.Covered = coveredBranchInFile
branchCoverageDataCoverage.BranchesToCover = totalBranchInFile
branchCoverageDataCoverage.CoverageRate = getScore(totalBranchInFile, coveredBranchInFile)
branchCoverageDataCoverage.CoverageData = append(branchCoverageDataCoverage.CoverageData, newpayloadCurrent...)
allDataCover = append(allDataCover, branchCoverageDataCoverage)
xmlLineToCoverElemList := createDataForXmlfile(branchCoverageDataCoverage)
fileElement := FileCoverage{
Path: filenamecover,
LineToCover: xmlLineToCoverElemList,
}
fileElementList = append(fileElementList, fileElement)
totalBranch = totalBranch + totalBranchInFile
coveredBranch = coveredBranch + coveredBranchInFile
totalBranchInFile = EMPTY_CHECK
coveredBranchInFile = EMPTY_CHECK
newpayloadCurrent = nil
filenamecover = fileName
}
newpayloadCurrent = append(newpayloadCurrent, payloadCurrent[i])
totalBranchInFile = totalBranchInFile + 2
if payloadCurrent[i].TrueCount > EMPTY_CHECK {
coveredBranchInFile++
}
if payloadCurrent[i].FalseCount > EMPTY_CHECK {
coveredBranchInFile++
}
if i == EMPTY_CHECK {
filenamecover = fileName
}
}
createXmlFile(fileElementList, "test-results")
/* To print coverage rate from gobco output*/
var branchCoverage BranchCoverage
branchCoverage.AllData = allDataCover
branchCoverage.CoverageRate = getScore(totalBranch, coveredBranch)
branchCoverage.BranchesToCover = totalBranch
branchCoverage.TotalCoveredBranch = coveredBranch
jsonfileall, _ := json.Marshal(branchCoverage)
_ = ioutil.WriteFile("test-results/all-branch-cover.json", jsonfileall, 0644)
// log.Println("Total Branches: ", totalBranch)
// log.Println("Total Covered: ", coveredBranch)
// log.Println("Coverage= ", getScore(totalBranch, coveredBranch))
} else if *packageName == "c1-ruby" {
log.Println("C1 Coverage report for ruby")
var rspec Rspec
err = json.NewDecoder(strings.NewReader(string(currentContent[:]))).Decode(&rspec)
if err != nil {
log.Fatal("Error while reading .resultset.json file\n", err)
}
ParseJsonForRubyAndPrepareXmlData(rspec)
} else {
err = json.NewDecoder(strings.NewReader(string(currentContent[:]))).Decode(&payloadCurrent)
if err != nil {
log.Fatal("Error during Unmarshal() of currentContent for packagename update: ", err)
}
// To update package name of the files in gobco output json file(it only has filename without package)
for i := 0; i < len(payloadCurrent); i++ {
lineNumber := payloadCurrent[i].Start
fileName := strings.Split(lineNumber, ":")[0]
lineNumberStartSplitted, _ := strconv.Atoi(strings.Split(lineNumber, ":")[1])
ColNumberStartSplitted, _ := strconv.Atoi(strings.Split(lineNumber, ":")[2])
payloadCurrent[i].Start = *packageName + "/" + fileName + ":" + strconv.Itoa(lineNumberStartSplitted) + ":" + strconv.Itoa(ColNumberStartSplitted)
}
jsonfile, _ := json.Marshal(payloadCurrent)
_ = ioutil.WriteFile(*packageName+"/branch-cover.json", jsonfile, 0644)
}
} else if *isUpdateJson {
// Copy branch-cover.json file from each package and write it in test-results folder
contentAll, err := ioutil.ReadFile(*packageName + "/branch-cover.json")
if err != nil {
log.Fatal("Error when opening file: ", err)
}
if len(contentAll) > 0 {
var payloadAll []*BranchCoverageData
err = json.NewDecoder(strings.NewReader(string(contentAll[:]))).Decode(&payloadAll)
if err != nil {
log.Fatal("Error during Unmarshal() of contentAll: ", err)
}
payloadAll = append(payloadAll, payloadCurrent...)
jsonfile, _ := json.Marshal(payloadAll)
_ = ioutil.WriteFile("test-results/branch-cover.json", jsonfile, 0644)
} else {
jsonfile, _ := json.Marshal(payloadCurrent)
_ = ioutil.WriteFile("test-results/branch-cover.json", jsonfile, 0644)
}
}
}
//Find branch coveage rate
func getScore(total int64, covered int) float64 {
return math.Floor(float64(covered) / float64(total) * 100)
}
// Create lineToCover element list for a file
func createDataForXmlfile(branchCoverageDataCoverage BranchCoverageDataCoverage) []LineToCover {
var branchCoverDataForaFile = branchCoverageDataCoverage.CoverageData
var lineToCoverElemList []LineToCover
for j := 0; j < len(branchCoverDataForaFile); j++ {
var coveredBranchXml = 0
var isCovered = true
if branchCoverageDataCoverage.CoverageData[j].TrueCount > EMPTY_CHECK {
coveredBranchXml++
}
if branchCoverageDataCoverage.CoverageData[j].FalseCount > EMPTY_CHECK {
coveredBranchXml++
}
if coveredBranchXml < 2 {
isCovered = false
}
codeStart := branchCoverageDataCoverage.CoverageData[j].Start
lineNumber := strings.Split(codeStart, ":")[1]
lineToCoverElement := prepareLineElement(lineNumber, "2", fmt.Sprint(coveredBranchXml), isCovered)
lineToCoverElemList = append(lineToCoverElemList, lineToCoverElement)
}
return lineToCoverElemList
}
// fileExists checks if a file exists and is not a directory before we
// try using it to prevent further errors.
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return !os.IsNotExist(err)
}
func ParseJsonForRubyAndPrepareXmlData(rspec Rspec) {
keys := make([]string, 0, len(rspec.Rspec.Coverage))
for k := range rspec.Rspec.Coverage {
keys = append(keys, k)
}
var fileElementList []FileCoverage
// To generate xml file atlast
for i := 0; i < len(keys); i++ {
var lineToCoverElemList []LineToCover
fileName := keys[i]
rubyBranchMap := rspec.Rspec.Coverage[fileName].RubyBranches
branchKeys := make([]string, 0, len(rubyBranchMap))
for c1 := range rubyBranchMap {
branchKeys = append(branchKeys, c1)
}
for k := 0; k < len(branchKeys); k++ {
outetKey := branchKeys[k]
newKey := strings.Replace(strings.Replace(outetKey, "[", "", -1), "]", "", -1)
branchKeyArray := strings.Split(newKey, ",")
branchMap := rubyBranchMap[outetKey]
ifelseKeys := make([]string, 0, len(branchMap))
for k1 := range branchMap {
ifelseKeys = append(ifelseKeys, k1)
}
notCovered := 0
for branchCount := 0; branchCount < len(ifelseKeys); branchCount++ {
if branchMap[ifelseKeys[branchCount]] == EMPTY_CHECK {
notCovered++
}
}
lineToCoverElement := prepareLineElement(branchKeyArray[2], strconv.Itoa(len(ifelseKeys)), strconv.Itoa(len(ifelseKeys)-notCovered),
(len(ifelseKeys)-notCovered) == len(ifelseKeys))
linePresentAt := checkIfLineAlreadyPresent(lineToCoverElement.LineNumber, lineToCoverElemList)
if linePresentAt != -1 {
lineElementTarget := lineToCoverElemList[linePresentAt]
lineElementTarget.BranchesToCover = fmt.Sprint(parseAndGetInt(lineElementTarget.BranchesToCover) + parseAndGetInt(lineToCoverElement.BranchesToCover))
lineElementTarget.CoveredBranches = fmt.Sprint(parseAndGetInt(lineElementTarget.CoveredBranches) + parseAndGetInt(lineToCoverElement.CoveredBranches))
lineElementTarget.Covered = fmt.Sprint(parseAndGetBool(lineElementTarget.CoveredBranches) && parseAndGetBool(lineToCoverElement.CoveredBranches))
lineToCoverElemList[linePresentAt] = lineElementTarget
} else {
lineToCoverElemList = append(lineToCoverElemList, lineToCoverElement)
}
}
if len(lineToCoverElemList) > 0 {
fileElement := FileCoverage{
Path: fileName,
LineToCover: lineToCoverElemList,
}
fileElementList = append(fileElementList, fileElement)
}
}
createXmlFile(fileElementList, "coverage")
}
func parseAndGetBool(iscovered string) bool {
val, err := strconv.ParseBool(iscovered)
if err == nil {
return val
} else {
return false
}
}
func parseAndGetInt(iscovered string) int {
val, err := strconv.Atoi(iscovered)
if err == nil {
return val
} else {
return -1
}
}
// Preare LineTocover element
func prepareLineElement(filename string, total string, covered string, isCovered bool) LineToCover {
lineToCoverElement := LineToCover{
LineNumber: strings.Trim(filename, " "),
BranchesToCover: total,
CoveredBranches: covered,
Covered: fmt.Sprint(isCovered),
}
return lineToCoverElement
}
// Pass data and create generic test coverage report for sonaqube
func createXmlFile(fileElementList []FileCoverage, folderPath string) {
xmlData := coverage{
Version: "1",
File: fileElementList}
xmlFile, err := os.Create(folderPath + "/branch-coverage.xml")
enc := xml.NewEncoder(xmlFile)
enc.Indent("", "\t")
if err := enc.Encode(xmlData); err != nil {
fmt.Printf("error: %v\n", err)
}
if err != nil {
fmt.Println("Error creating XML file: ", err)
return
}
}
func checkIfLineAlreadyPresent(lineNumber string, lineToCoverElemList []LineToCover) int {
for count := 0; count < len(lineToCoverElemList); count++ {
if lineToCoverElemList[count].LineNumber == lineNumber {
return count
}
}
return -1
}