forked from Zetten/bazel-sonarqube
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdefs.bzl
267 lines (242 loc) · 10.2 KB
/
defs.bzl
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
def sonarqube_coverage_generator_binary():
deps = ["@remote_coverage_tools//:all_lcov_merger_lib"]
native.java_binary(
name = "SonarQubeCoverageGenerator",
srcs = [
"src/main/java/com/google/devtools/coverageoutputgenerator/SonarQubeCoverageGenerator.java",
"src/main/java/com/google/devtools/coverageoutputgenerator/SonarQubeCoverageReportPrinter.java",
],
main_class = "com.google.devtools.coverageoutputgenerator.SonarQubeCoverageGenerator",
deps = deps,
)
def _build_sonar_project_properties(ctx, sq_properties_file):
module_path = ctx.build_file_path.replace("BUILD", "")
depth = len(module_path.split("/")) - 1
parent_path = "../" * depth
# SonarQube requires test reports to be named like TEST-foo.xml, so we step
# through `test_targets` to find the matching `test_reports` values, and
# symlink them to the usable name
if hasattr(ctx.attr, "test_targets") and ctx.attr.test_targets and hasattr(ctx.attr, "test_reports") and ctx.attr.test_reports and ctx.files.test_reports:
test_reports_path = module_path + "test-reports"
test_reports_runfiles = []
for t in ctx.attr.test_targets:
test_target = ctx.label.relative(t)
bazel_test_report_path = "bazel-testlogs/" + test_target.package + "/" + test_target.name + "/test.xml"
matching_test_reports = [t for t in ctx.files.test_reports if t.short_path == bazel_test_report_path]
if matching_test_reports:
bazel_test_report = matching_test_reports[0]
sq_test_report = ctx.actions.declare_file("%s/TEST-%s.xml" % (test_reports_path, test_target.name))
ctx.actions.symlink(
output = sq_test_report,
target_file = bazel_test_report,
)
test_reports_runfiles.append(sq_test_report)
inc += 1
else:
print("Expected Bazel test report for %s with path %s" % (test_target, bazel_test_report_path))
else:
test_reports_path = ""
test_reports_runfiles = []
if hasattr(ctx.attr, "coverage_report") and ctx.attr.coverage_report:
coverage_report_path = parent_path + ctx.file.coverage_report.short_path
coverage_runfiles = [ctx.file.coverage_report]
else:
coverage_report_path = ""
coverage_runfiles = []
java_files = _get_java_files([t for t in ctx.attr.targets if t[JavaInfo]])
ctx.actions.expand_template(
template = ctx.file.sq_properties_template,
output = sq_properties_file,
substitutions = {
"{PROJECT_KEY}": ctx.attr.project_key,
"{PROJECT_NAME}": ctx.attr.project_name,
"{SOURCES}": ",".join([parent_path + f.short_path for f in ctx.files.srcs]),
"{TEST_SOURCES}": ",".join([parent_path + f.short_path for f in ctx.files.test_srcs]),
"{SOURCE_ENCODING}": ctx.attr.source_encoding,
"{JAVA_BINARIES}": ",".join([parent_path + j.short_path for j in java_files["output_jars"].to_list()]),
"{JAVA_LIBRARIES}": ",".join([parent_path + j.short_path for j in java_files["deps_jars"].to_list()]),
"{MODULES}": ",".join(ctx.attr.modules.values()),
"{TEST_REPORTS}": test_reports_path,
"{COVERAGE_REPORT}": coverage_report_path,
},
is_executable = False,
)
return ctx.runfiles(
files = [sq_properties_file] + ctx.files.srcs + ctx.files.test_srcs + test_reports_runfiles + coverage_runfiles,
transitive_files = depset(transitive = [java_files["output_jars"], java_files["deps_jars"]]),
)
def _get_java_files(java_targets):
return {
"output_jars": depset(direct = [j.class_jar for t in java_targets for j in t[JavaInfo].outputs.jars]),
"deps_jars": depset(transitive = [t[JavaInfo].transitive_deps for t in java_targets] + [t[JavaInfo].transitive_runtime_deps for t in java_targets]),
}
def _test_report_path(parent_path, test_target):
return parent_path + "bazel-testlogs/" + test_target.package + "/" + test_target.name
def _sonarqube_impl(ctx):
sq_properties_file = ctx.actions.declare_file("sonar-project.properties")
local_runfiles = _build_sonar_project_properties(ctx, sq_properties_file)
module_runfiles = ctx.runfiles(files = [])
for module in ctx.attr.modules.keys():
module_runfiles = module_runfiles.merge(module[DefaultInfo].default_runfiles)
ctx.actions.write(
output = ctx.outputs.executable,
content = "\n".join([
"#!/bin/bash",
#"echo 'Dereferencing bazel runfiles symlinks for accurate SCM resolution...'",
#"for f in $(find $(dirname %s) -type l); do echo $f; done" % sq_properties_file.short_path,
#"echo '... done.'",
#
"find $(dirname %s) -type l -exec bash -c 'ln -f $(readlink $0) $0' {} \\;" % sq_properties_file.short_path,
"exec %s -Dproject.settings=%s $@" % (ctx.executable.sonar_scanner.short_path, sq_properties_file.short_path),
]),
is_executable = True,
)
return [DefaultInfo(
runfiles = ctx.runfiles(files = [ctx.executable.sonar_scanner] + ctx.files.scm_info).merge(ctx.attr.sonar_scanner[DefaultInfo].default_runfiles).merge(local_runfiles).merge(module_runfiles),
)]
_COMMON_ATTRS = dict(dict(), **{
"project_key": attr.string(
mandatory = True,
doc = """SonarQube project key, e.g. `com.example.project:module`.""",
),
"project_name": attr.string(
doc = """SonarQube project display name.""",
),
"srcs": attr.label_list(
allow_files = True,
default = [],
doc = """Project sources to be analysed by SonarQube.""",
),
"source_encoding": attr.string(
default = "UTF-8",
doc = """Source file encoding.""",
),
"targets": attr.label_list(
default = [],
doc = """Bazel targets to be analysed by SonarQube.
These may be used to provide additional provider information to the SQ analysis , e.g. Java classpath context.
""",
),
"modules": attr.label_keyed_string_dict(
default = {},
doc = """Sub-projects to associate with this SonarQube project.""",
),
"test_srcs": attr.label_list(
allow_files = True,
default = [],
doc = """Project test sources to be analysed by SonarQube. This must be set along with `test_reports` and `test_sources` for accurate test reporting.""",
),
"test_targets": attr.string_list(
default = [],
doc = """A list of test targets relevant to the SQ project. This will be used with the `test_reports` attribute to generate the report paths in sonar-project.properties.""",
),
"test_reports": attr.label_list(
allow_files = True,
default = [],
doc = """Junit-format execution reports, e.g. `filegroup(name = "test_reports", srcs = glob(["bazel-testlogs/**/test.xml"]))`""",
),
"sq_properties_template": attr.label(
allow_single_file = True,
default = "@bazel_sonarqube//:sonar-project.properties.tpl",
doc = """Template file for sonar-project.properties.""",
),
"sq_properties": attr.output(),
})
_sonarqube = rule(
attrs = dict(_COMMON_ATTRS, **{
"coverage_report": attr.label(
allow_single_file = True,
mandatory = False,
doc = """Coverage file in SonarQube generic coverage report format.""",
),
"scm_info": attr.label_list(
allow_files = True,
doc = """Source code metadata, e.g. `filegroup(name = "git_info", srcs = glob([".git/**"], exclude = [".git/**/*[*"], # gitk creates temp files with []))`""",
),
"sonar_scanner": attr.label(
executable = True,
default = "@bazel_sonarqube//:sonar_scanner",
cfg = "host",
doc = """Bazel binary target to execute the SonarQube CLI Scanner""",
),
}),
fragments = ["jvm"],
host_fragments = ["jvm"],
implementation = _sonarqube_impl,
executable = True,
)
def sonarqube(
name,
project_key,
scm_info,
coverage_report = None,
project_name = None,
srcs = [],
source_encoding = None,
targets = [],
test_srcs = [],
test_targets = [],
test_reports = [],
modules = {},
sonar_scanner = None,
sq_properties_template = None,
tags = [],
visibility = []):
_sonarqube(
name = name,
project_key = project_key,
project_name = project_name,
scm_info = scm_info,
srcs = srcs,
source_encoding = source_encoding,
targets = targets,
modules = modules,
test_srcs = test_srcs,
test_targets = test_targets,
test_reports = test_reports,
coverage_report = coverage_report,
sonar_scanner = sonar_scanner,
sq_properties_template = sq_properties_template,
sq_properties = "sonar-project.properties",
tags = tags,
visibility = visibility,
)
def _sq_project_impl(ctx):
local_runfiles = _build_sonar_project_properties(ctx, ctx.outputs.sq_properties)
return [DefaultInfo(
runfiles = local_runfiles,
)]
_sq_project = rule(
attrs = _COMMON_ATTRS,
implementation = _sq_project_impl,
)
def sq_project(
name,
project_key,
project_name = None,
srcs = [],
source_encoding = None,
targets = [],
test_srcs = [],
test_targets = [],
test_reports = [],
modules = {},
sq_properties_template = None,
tags = [],
visibility = []):
_sq_project(
name = name,
project_key = project_key,
project_name = project_name,
srcs = srcs,
test_srcs = test_srcs,
source_encoding = source_encoding,
targets = targets,
test_targets = test_targets,
test_reports = test_reports,
modules = modules,
sq_properties_template = sq_properties_template,
sq_properties = "sonar-project.properties",
tags = tags,
visibility = visibility,
)