-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdefs.bzl
414 lines (354 loc) · 15.6 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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""
Rules to analyse Bazel projects with SonarQube.
"""
load("@bazel_version//:bazel_version.bzl", "bazel_version")
load("@bazel_skylib//lib:versions.bzl", "versions")
def sonarqube_coverage_generator_binary(name = None):
if versions.is_at_least(threshold = "2.1.0", version = bazel_version):
deps = ["@remote_coverage_tools//:all_lcov_merger_lib"]
else:
deps = ["@bazel_tools//tools/test/CoverageOutputGenerator/java/com/google/devtools/coverageoutputgenerator: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,
)
TargetInfo = provider(
fields = {
"deps": "depset of targets",
},
)
SqProjectInfo = provider(
fields = {
"srcs": "main sources",
"test_srcs": "test sources",
},
)
def _test_targets_aspect_impl(target, ctx):
transitive = []
direct = []
if ctx.rule.kind.endswith("_test"):
direct.append(target)
if hasattr(ctx.rule.attr, "tests"):
for dep in ctx.rule.attr.tests:
transitive.append(dep[TargetInfo].deps)
return TargetInfo(deps = depset(direct = direct, transitive = transitive))
# This aspect is for collecting test targets from test_suite rules
# to save some duplication in the BUILD files.
test_targets_aspect = aspect(
implementation = _test_targets_aspect_impl,
attr_aspects = ["tests"],
)
def _build_sonar_project_properties(ctx, sq_properties_file, rule):
module_path = ctx.build_file_path.replace("/BUILD.bazel", "/").replace("/BUILD", "/")
depth = len(module_path.split("/")) - 1
if rule == "sq_project":
parent_path = "../" * depth
else:
parent_path = ""
# 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"
if rule == "sq_project":
local_test_reports_path = module_path + "test-reports"
else:
local_test_reports_path = "test-reports"
test_reports_runfiles = []
inc = 0
for dep in ctx.attr.test_targets:
if TargetInfo in dep:
for t in dep[TargetInfo].deps.to_list():
test_target = t.label
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" % (local_test_reports_path, inc))
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_compile_time_jars for t in java_targets] +
[t[JavaInfo].transitive_runtime_jars for t in java_targets],
),
}
def _test_report_path(parent_path, test_target):
return parent_path + "bazel-testlogs/" + test_target.package + "/" + test_target.name
_sonarqube_template = """
#!/bin/bash
set -e
echo 'Dereferencing bazel runfiles symlinks for accurate SCM resolution...'
for f in {srcs} {test_srcs}
do
mkdir -p $(dirname orig/$f)
mv $f orig/$f
cp -L orig/$f $f
done
echo '... done.'
{sonar_scanner} ${{1+"$@"}} -Dproject.settings={sq_properties_file}
echo 'Restoring original bazel runfiles symlinks...'
for f in {srcs} {test_srcs}
do
rm $f
mv orig/$f $f
done
rm -rf orig
echo '... done.'
"""
def _sonarqube_impl(ctx):
sq_properties_file = ctx.actions.declare_file("sonar-project.properties")
local_runfiles = _build_sonar_project_properties(ctx, sq_properties_file, "sonarqube")
module_runfiles = ctx.runfiles(files = [])
for module in ctx.attr.modules.keys():
module_runfiles = module_runfiles.merge(module[DefaultInfo].default_runfiles)
src_paths = []
for t in ctx.attr.srcs:
for f in t[DefaultInfo].files.to_list():
src_paths.append(f.short_path)
test_src_paths = []
for t in ctx.attr.test_srcs:
for f in t[DefaultInfo].files.to_list():
test_src_paths.append(f.short_path)
for module in ctx.attr.modules.keys():
for t in module[SqProjectInfo].srcs:
for f in t[DefaultInfo].files.to_list():
src_paths.append(f.short_path)
for t in module[SqProjectInfo].test_srcs:
for f in t[DefaultInfo].files.to_list():
test_src_paths.append(f.short_path)
ctx.actions.write(
output = ctx.outputs.executable,
content = _sonarqube_template.format(
sq_properties_file = sq_properties_file.short_path,
sonar_scanner = ctx.executable.sonar_scanner.short_path,
srcs = " ".join(src_paths),
test_srcs = " ".join(test_src_paths),
),
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),
"project_name": attr.string(),
"srcs": attr.label_list(allow_files = True, default = []),
"source_encoding": attr.string(default = "UTF-8"),
"targets": attr.label_list(default = []),
"modules": attr.label_keyed_string_dict(default = {}),
"test_srcs": attr.label_list(allow_files = True, default = []),
"test_targets": attr.label_list(default = [], aspects = [test_targets_aspect]),
"test_reports": attr.label_list(allow_files = True, default = []),
"sq_properties_template": attr.label(allow_single_file = True, default = "@bazel_sonarqube//:sonar-project.properties.tpl"),
"sq_properties": attr.output(),
})
_sonarqube = rule(
attrs = dict(_COMMON_ATTRS, **{
"coverage_report": attr.label(allow_single_file = True, mandatory = False),
"scm_info": attr.label_list(allow_files = True),
"sonar_scanner": attr.label(executable = True, default = "@bazel_sonarqube//:sonar_scanner", cfg = "host"),
}),
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 = "@bazel_sonarqube//:sonar_scanner",
sq_properties_template = "@bazel_sonarqube//:sonar-project.properties.tpl",
tags = [],
visibility = [],
**kwargs):
"""A runnable rule to execute SonarQube analysis.
Generates `sonar-project.properties` and invokes the SonarScanner CLI tool
to perform the analysis.
Args:
name: Name of the target.
project_key: SonarQube project key, e.g. `com.example.project:module`.
scm_info: Source code metadata. For example, to include Git data from
the workspace root, create a filegroup:
`filegroup(name = "git_info", srcs = glob([".git/**"], exclude = [".git/**/*[*"]))`
and reference it as `scm_info = [":git_info"],`.
coverage_report: Coverage file in SonarQube generic coverage report
format. This can be created using the generator from this project
(see the README for example usage).
project_name: SonarQube project display name.
srcs: Project sources to be analysed by SonarQube.
source_encoding: Source file encoding.
targets: 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: Sub-projects to associate with this SonarQube project, i.e.
`sq_project` targets.
test_srcs: 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: 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: Targets describing Junit-format execution reports. May be
configured in the workspace root to use Bazel's execution reports
as below:
`filegroup(name = "test_reports", srcs = glob(["bazel-testlogs/**/test.xml"]))`
and referenced as `test_reports = [":test_reports"],`.
**Note:** this requires manually executing `bazel test` or `bazel
coverage` before running the `sonarqube` target.
sonar_scanner: Bazel binary target to execute the SonarQube CLI Scanner.
sq_properties_template: Template file for `sonar-project.properties`.
tags: Bazel target tags, e.g. `["manual"]`.
visibility: Bazel target visibility, e.g. `["//visibility:public"]`.
"""
_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,
**kwargs
)
def _sq_project_impl(ctx):
local_runfiles = _build_sonar_project_properties(ctx, ctx.outputs.sq_properties, "sq_project")
return [DefaultInfo(
runfiles = local_runfiles,
), SqProjectInfo(
srcs = ctx.attr.srcs,
test_srcs = ctx.attr.test_srcs,
)]
_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 = "@bazel_sonarqube//:sonar-project.properties.tpl",
tags = [],
visibility = [],
**kwargs):
"""A configuration rule to generate SonarQube analysis properties.
Targets of this type may be referenced by the [`modules`](#sonarqube-modules)
attribute of the `sonarqube` rule, to create a multi-module SonarQube
project.
Args:
name: Name of the target.
project_key: SonarQube project key, e.g. `com.example.project:module`.
project_name: SonarQube project display name.
srcs: Project sources to be analysed by SonarQube.
source_encoding: Source file encoding.
targets: 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: Sub-projects to associate with this SonarQube project, i.e.
`sq_project` targets.
test_srcs: 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: 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: Targets describing Junit-format execution reports. May be
configured in the workspace root to use Bazel's execution reports
as below:
`filegroup(name = "test_reports", srcs = glob(["bazel-testlogs/**/test.xml"]))`
and referenced as `test_reports = [":test_reports"],`.
**Note:** this requires manually executing `bazel test` or `bazel
coverage` before running the `sonarqube` target.
sq_properties_template: Template file for `sonar-project.properties`.
tags: Bazel target tags, e.g. `["manual"]`.
visibility: Bazel target visibility, e.g. `["//visibility:public"]`.
"""
_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,
**kwargs
)