This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
/
ScoverageSensor.scala
182 lines (157 loc) · 6.88 KB
/
ScoverageSensor.scala
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
/*
* Copyright (C) 2018-2022 All sonar-scala contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mwz.sonar.scala
package scoverage
import java.nio.file.Path
import java.nio.file.Paths
import scala.jdk.CollectionConverters._
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import cats.syntax.eq._
import com.mwz.sonar.scala.scoverage.ScoverageSensor._
import com.mwz.sonar.scala.util.Log
import com.mwz.sonar.scala.util.PathUtils
import com.mwz.sonar.scala.util.PathUtils._
import com.mwz.sonar.scala.util.syntax.Optionals._
import org.sonar.api.batch.fs.FileSystem
import org.sonar.api.batch.fs.InputComponent
import org.sonar.api.batch.fs.InputFile
import org.sonar.api.batch.sensor.Sensor
import org.sonar.api.batch.sensor.SensorContext
import org.sonar.api.batch.sensor.SensorDescriptor
import org.sonar.api.config.Configuration
import org.sonar.api.measures.Metric
import scalariform.ScalaVersion
/** Main sensor for importing Scoverage reports into SonarQube. */
final class ScoverageSensor(
globalConfig: GlobalConfig,
scoverageReportParser: ScoverageReportParserAPI
) extends Sensor {
private[this] val log = Log(classOf[ScoverageSensor], "scoverage")
/** Populates the SensorDescriptor of this sensor. */
override def describe(descriptor: SensorDescriptor): Unit = {
descriptor
.name(SensorName)
.onlyOnLanguage(Scala.LanguageKey)
.onlyOnFileType(InputFile.Type.MAIN)
.onlyWhenConfiguration(shouldEnableSensor)
}
/** Saves in SonarQube the scoverage information of the project. */
override def execute(context: SensorContext): Unit = {
log.info("Initializing the scoverage sensor.")
log.debug(s"The current working directory is: '${PathUtils.cwd}'.")
val settings = context.config
val filesystem = context.fileSystem
val projectPath = getProjectBaseDirectory(filesystem)
val reportPath = projectPath.resolve(getScoverageReportPath(settings))
val sources = Scala.getSourcesPaths(settings)
val sourcePrefixes = sources.map(PathUtils.relativize(PathUtils.cwd, projectPath, _))
log.debug(s"The source prefixes are: ${sourcePrefixes.mkString("[", ",", "]")}.")
log.info(s"Loading the scoverage report file: '$reportPath'.")
Try(scoverageReportParser.parse(reportPath, projectPath, sourcePrefixes)) match {
case Success(projectCoverage) =>
log.info("Successfully loaded the scoverage report file.")
log.debug(s"Project scoverage information: $projectCoverage.")
// Save the coverage information of each file of the project.
getProjectSourceFiles(filesystem) foreach { file =>
val filename = PathUtils.cwd.relativize(Paths.get(file.uri())).toString
log.debug(s"Saving the scoverage information of the file: '$filename'.")
projectCoverage.filesCoverage.get(filename) match {
case Some(fileCoverage) =>
log.debug(s"File scoverage information: $fileCoverage.")
// save the file overall scoverage information
saveComponentScoverage(context, file, fileCoverage.fileScoverage)
// save the coverage of each line of the file
val coverage = context.newCoverage()
coverage.onFile(file)
fileCoverage.linesCoverage foreach { case (lineNum, hits) =>
coverage.lineHits(lineNum, hits)
}
// Save the coverage (if not in pr decoration mode).
if (!globalConfig.prDecoration)
coverage.save()
case None =>
log.warn(s"The file '$filename' has no scoverage information associated with it.")
}
}
case Failure(ex) =>
log.error(
"Aborting the scoverage sensor execution, " +
s"cause: an error occurred while reading the scoverage report file: '$reportPath', " +
s"the error was: ${ex.getMessage}."
)
}
}
/** Returns all scala main files from this project. */
private[scoverage] def getProjectSourceFiles(fs: FileSystem): Iterable[InputFile] = {
val predicates = fs.predicates
val predicate =
predicates.and(
predicates.hasLanguage(Scala.LanguageKey),
predicates.hasType(InputFile.Type.MAIN)
)
fs.inputFiles(predicate).asScala
}
/** Returns the filename of the scoverage report for this project. */
private[scoverage] def getScoverageReportPath(settings: Configuration): Path = {
val scalaVersion = Scala.getScalaVersion(settings)
val defaultScoverageReportPath = getDefaultScoverageReportPath(scalaVersion)
Paths.get(
settings
.get(ScoverageReportPathPropertyKey)
.toOption
.getOrElse(defaultScoverageReportPath.toString)
)
}
/** Saves the [[ScoverageMetrics]] of a component */
private[scoverage] def saveComponentScoverage(
context: SensorContext,
component: InputComponent,
scoverage: Scoverage
): Unit = {
List(
(ScoverageMetrics.statements, scoverage.statements),
(ScoverageMetrics.coveredStatements, scoverage.coveredStatements),
(ScoverageMetrics.branches, scoverage.branches),
(ScoverageMetrics.coveredBranches, scoverage.coveredBranches)
).foreach { case (metric, value) => save[java.lang.Integer](metric, value) }
List(
(ScoverageMetrics.statementCoverage, scoverage.statementCoverage),
(ScoverageMetrics.branchCoverage, scoverage.branchCoverage)
).foreach { case (metric, value) => save[java.lang.Double](metric, value) }
def save[A <: java.io.Serializable](metric: Metric[A], value: A): Unit =
context
.newMeasure()
.on(component)
.forMetric(metric)
.withValue(value)
.save()
}
}
private[scoverage] object ScoverageSensor {
final val SensorName: String = "Scoverage Sensor"
final val ScoverageDisablePropertyKey: String = "sonar.scala.scoverage.disable"
final val ScoverageReportPathPropertyKey: String = "sonar.scala.scoverage.reportPath"
def shouldEnableSensor(conf: Configuration): Boolean =
conf
.get(ScoverageDisablePropertyKey)
.toOption
.forall(s => s.toLowerCase =!= "true")
def getDefaultScoverageReportPath(scalaVersion: ScalaVersion): Path =
Paths.get(s"target/scala-${scalaVersion.major}.${scalaVersion.minor}/scoverage-report/scoverage.xml")
}