aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/build_rules
diff options
context:
space:
mode:
authorGravatar vladmos <vladmos@google.com>2018-06-01 04:51:21 -0700
committerGravatar Copybara-Service <copybara-piper@google.com>2018-06-01 04:52:44 -0700
commit20a042faa91acf8db78684de9f38c4e628d61dd6 (patch)
treec2fc5c6d30cb51cb3f6e30ed0fb2d25f5525585f /tools/build_rules
parent2269ee2af91b7df13820381d61e8e4e26a257b3a (diff)
Format all bzl files with buildifier
This CL aslo enables a presubmit check for correct formatting of all bzl files in //third_party/bazel. PiperOrigin-RevId: 198857055
Diffstat (limited to 'tools/build_rules')
-rw-r--r--tools/build_rules/genproto.bzl44
-rw-r--r--tools/build_rules/java_rules_skylark.bzl392
-rw-r--r--tools/build_rules/test_rules.bzl444
-rw-r--r--tools/build_rules/utilities.bzl33
4 files changed, 475 insertions, 438 deletions
diff --git a/tools/build_rules/genproto.bzl b/tools/build_rules/genproto.bzl
index f935e52b68..f63ba005f2 100644
--- a/tools/build_rules/genproto.bzl
+++ b/tools/build_rules/genproto.bzl
@@ -18,25 +18,27 @@
proto_filetype = [".proto"]
def cc_grpc_library(name, src):
- basename = src[:-len(".proto")]
- protoc_label = str(Label("//third_party/protobuf:protoc"))
- cpp_plugin_label = str(Label("//third_party/grpc:cpp_plugin"))
- native.genrule(
- name = name + "_codegen",
- srcs = [src],
- tools = [protoc_label, cpp_plugin_label],
- cmd = "\\\n".join([
- "$(location " + protoc_label + ")",
- " --plugin=protoc-gen-grpc=$(location " + cpp_plugin_label + ")",
- " --cpp_out=$(GENDIR)",
- " --grpc_out=$(GENDIR)",
- " $(location " + src + ")"]),
- outs = [basename + ".grpc.pb.h", basename + ".grpc.pb.cc", basename + ".pb.cc", basename + ".pb.h"])
-
- native.cc_library(
- name = name,
- srcs = [basename + ".grpc.pb.cc", basename + ".pb.cc"],
- hdrs = [basename + ".grpc.pb.h", basename + ".pb.h"],
- deps = [str(Label("//third_party/grpc:grpc++_unsecure"))],
- includes = ["."])
+ basename = src[:-len(".proto")]
+ protoc_label = str(Label("//third_party/protobuf:protoc"))
+ cpp_plugin_label = str(Label("//third_party/grpc:cpp_plugin"))
+ native.genrule(
+ name = name + "_codegen",
+ srcs = [src],
+ tools = [protoc_label, cpp_plugin_label],
+ cmd = "\\\n".join([
+ "$(location " + protoc_label + ")",
+ " --plugin=protoc-gen-grpc=$(location " + cpp_plugin_label + ")",
+ " --cpp_out=$(GENDIR)",
+ " --grpc_out=$(GENDIR)",
+ " $(location " + src + ")",
+ ]),
+ outs = [basename + ".grpc.pb.h", basename + ".grpc.pb.cc", basename + ".pb.cc", basename + ".pb.h"],
+ )
+ native.cc_library(
+ name = name,
+ srcs = [basename + ".grpc.pb.cc", basename + ".pb.cc"],
+ hdrs = [basename + ".grpc.pb.h", basename + ".pb.h"],
+ deps = [str(Label("//third_party/grpc:grpc++_unsecure"))],
+ includes = ["."],
+ )
diff --git a/tools/build_rules/java_rules_skylark.bzl b/tools/build_rules/java_rules_skylark.bzl
index ec103830d2..50a657728e 100644
--- a/tools/build_rules/java_rules_skylark.bzl
+++ b/tools/build_rules/java_rules_skylark.bzl
@@ -20,177 +20,183 @@ srcjar_filetype = FileType([".jar", ".srcjar"])
# production ready.
def java_library_impl(ctx):
- javac_options = ctx.fragments.java.default_javac_flags
- class_jar = ctx.outputs.class_jar
- compile_time_jars = depset(order="topological")
- runtime_jars = depset(order="topological")
- for dep in ctx.attr.deps:
- compile_time_jars += dep.compile_time_jars
- runtime_jars += dep.runtime_jars
-
- jars = jar_filetype.filter(ctx.files.jars)
- neverlink_jars = jar_filetype.filter(ctx.files.neverlink_jars)
- compile_time_jars += jars + neverlink_jars
- runtime_jars += jars
- compile_time_jars_list = list(compile_time_jars) # TODO: This is weird.
-
- build_output = class_jar.path + ".build_output"
- java_output = class_jar.path + ".build_java"
- javalist_output = class_jar.path + ".build_java_list"
- sources = ctx.files.srcs
-
- sources_param_file = ctx.new_file(ctx.bin_dir, class_jar, "-2.params")
- ctx.file_action(
- output = sources_param_file,
- content = cmd_helper.join_paths("\n", depset(sources)),
- executable = False)
-
- # Cleaning build output directory
- cmd = "set -e;rm -rf " + build_output + " " + java_output + " " + javalist_output + "\n"
- cmd += "mkdir " + build_output + " " + java_output + "\n"
- files = " @" + sources_param_file.path
-
- if ctx.files.srcjars:
- files += " @" + javalist_output
- for file in ctx.files.srcjars:
- cmd += "%s tf %s | grep '\.java$' | sed 's|^|%s/|' >> %s\n" % (ctx.file._jar.path, file.path, java_output, javalist_output)
- cmd += "unzip %s -d %s >/dev/null\n" % (file.path, java_output)
-
- if ctx.files.srcs or ctx.files.srcjars:
- cmd += ctx.file._javac.path
- cmd += " " + " ".join(javac_options)
- if compile_time_jars:
- cmd += " -classpath '" + cmd_helper.join_paths(ctx.configuration.host_path_separator, compile_time_jars) + "'"
- cmd += " -d " + build_output + files + "\n"
-
- # We haven't got a good story for where these should end up, so
- # stick them in the root of the jar.
- for r in ctx.files.resources:
- cmd += "cp %s %s\n" % (r.path, build_output)
- cmd += (ctx.file._jar.path + " cf " + class_jar.path + " -C " + build_output + " .\n" +
- "touch " + build_output + "\n")
- ctx.action(
- inputs = (sources + compile_time_jars_list + [sources_param_file] +
- [ctx.file._jar] + ctx.files._jdk + ctx.files.resources + ctx.files.srcjars),
- outputs = [class_jar],
- mnemonic='JavacBootstrap',
- command=cmd,
- use_default_shell_env=True)
-
- runfiles = ctx.runfiles(collect_data = True)
-
- return struct(files = depset([class_jar]),
- compile_time_jars = compile_time_jars + [class_jar],
- runtime_jars = runtime_jars + [class_jar],
- runfiles = runfiles)
-
+ javac_options = ctx.fragments.java.default_javac_flags
+ class_jar = ctx.outputs.class_jar
+ compile_time_jars = depset(order = "topological")
+ runtime_jars = depset(order = "topological")
+ for dep in ctx.attr.deps:
+ compile_time_jars += dep.compile_time_jars
+ runtime_jars += dep.runtime_jars
+
+ jars = jar_filetype.filter(ctx.files.jars)
+ neverlink_jars = jar_filetype.filter(ctx.files.neverlink_jars)
+ compile_time_jars += jars + neverlink_jars
+ runtime_jars += jars
+ compile_time_jars_list = list(compile_time_jars) # TODO: This is weird.
+
+ build_output = class_jar.path + ".build_output"
+ java_output = class_jar.path + ".build_java"
+ javalist_output = class_jar.path + ".build_java_list"
+ sources = ctx.files.srcs
+
+ sources_param_file = ctx.new_file(ctx.bin_dir, class_jar, "-2.params")
+ ctx.file_action(
+ output = sources_param_file,
+ content = cmd_helper.join_paths("\n", depset(sources)),
+ executable = False,
+ )
+
+ # Cleaning build output directory
+ cmd = "set -e;rm -rf " + build_output + " " + java_output + " " + javalist_output + "\n"
+ cmd += "mkdir " + build_output + " " + java_output + "\n"
+ files = " @" + sources_param_file.path
+
+ if ctx.files.srcjars:
+ files += " @" + javalist_output
+ for file in ctx.files.srcjars:
+ cmd += "%s tf %s | grep '\.java$' | sed 's|^|%s/|' >> %s\n" % (ctx.file._jar.path, file.path, java_output, javalist_output)
+ cmd += "unzip %s -d %s >/dev/null\n" % (file.path, java_output)
+
+ if ctx.files.srcs or ctx.files.srcjars:
+ cmd += ctx.file._javac.path
+ cmd += " " + " ".join(javac_options)
+ if compile_time_jars:
+ cmd += " -classpath '" + cmd_helper.join_paths(ctx.configuration.host_path_separator, compile_time_jars) + "'"
+ cmd += " -d " + build_output + files + "\n"
+
+ # We haven't got a good story for where these should end up, so
+ # stick them in the root of the jar.
+ for r in ctx.files.resources:
+ cmd += "cp %s %s\n" % (r.path, build_output)
+ cmd += (ctx.file._jar.path + " cf " + class_jar.path + " -C " + build_output + " .\n" +
+ "touch " + build_output + "\n")
+ ctx.action(
+ inputs = (sources + compile_time_jars_list + [sources_param_file] +
+ [ctx.file._jar] + ctx.files._jdk + ctx.files.resources + ctx.files.srcjars),
+ outputs = [class_jar],
+ mnemonic = "JavacBootstrap",
+ command = cmd,
+ use_default_shell_env = True,
+ )
+
+ runfiles = ctx.runfiles(collect_data = True)
+
+ return struct(
+ files = depset([class_jar]),
+ compile_time_jars = compile_time_jars + [class_jar],
+ runtime_jars = runtime_jars + [class_jar],
+ runfiles = runfiles,
+ )
def java_binary_impl(ctx):
- library_result = java_library_impl(ctx)
-
- deploy_jar = ctx.outputs.deploy_jar
- manifest = ctx.outputs.manifest
- build_output = deploy_jar.path + ".build_output"
- main_class = ctx.attr.main_class
- ctx.file_action(
- output = manifest,
- content = "Main-Class: " + main_class + "\n",
- executable = False)
-
- # Cleaning build output directory
- cmd = "set -e;rm -rf " + build_output + ";mkdir " + build_output + "\n"
- for jar in library_result.runtime_jars:
- cmd += "unzip -qn " + jar.path + " -d " + build_output + "\n"
- cmd += (ctx.file._jar.path + " cmf " + manifest.path + " " +
- deploy_jar.path + " -C " + build_output + " .\n" +
- "touch " + build_output + "\n")
-
- ctx.action(
- inputs=list(library_result.runtime_jars) + [manifest] + ctx.files._jdk,
- outputs=[deploy_jar],
- mnemonic='Deployjar',
- command=cmd,
- use_default_shell_env=True)
-
- # Write the wrapper.
- executable = ctx.outputs.executable
- ctx.file_action(
- output = executable,
- content = '\n'.join([
- "#!/bin/bash",
- "# autogenerated - do not edit.",
- "case \"$0\" in",
- "/*) self=\"$0\" ;;",
- "*) self=\"$PWD/$0\";;",
- "esac",
- "",
- "if [[ -z \"$JAVA_RUNFILES\" ]]; then",
- " if [[ -e \"${self}.runfiles\" ]]; then",
- " export JAVA_RUNFILES=\"${self}.runfiles\"",
- " fi",
- " if [[ -n \"$JAVA_RUNFILES\" ]]; then",
- " export TEST_SRCDIR=${TEST_SRCDIR:-$JAVA_RUNFILES}",
- " fi",
- "fi",
- "",
-
- "jvm_bin=%s" % (ctx.file._java.path),
- "if [[ ! -x ${jvm_bin} ]]; then",
- " jvm_bin=$(which java)",
- "fi",
-
- # We extract the .so into a temp dir. If only we could mmap
- # directly from the zip file.
- "DEPLOY=$(dirname $self)/$(basename %s)" % deploy_jar.path,
-
- # This works both on Darwin and Linux, with the darwin path
- # looking like tmp.XXXXXXXX.{random}
- "SO_DIR=$(mktemp -d -t tmp.XXXXXXXXX)",
- "function cleanup() {",
- " rm -rf ${SO_DIR}",
- "}",
- "trap cleanup EXIT",
- "unzip -q -d ${SO_DIR} ${DEPLOY} \"*.so\" \"*.dll\" \"*.dylib\" >& /dev/null",
- ("${jvm_bin} -Djava.library.path=${SO_DIR} %s -jar $DEPLOY \"$@\""
- % ' '.join(ctx.attr.jvm_flags)) ,
- "",
+ library_result = java_library_impl(ctx)
+
+ deploy_jar = ctx.outputs.deploy_jar
+ manifest = ctx.outputs.manifest
+ build_output = deploy_jar.path + ".build_output"
+ main_class = ctx.attr.main_class
+ ctx.file_action(
+ output = manifest,
+ content = "Main-Class: " + main_class + "\n",
+ executable = False,
+ )
+
+ # Cleaning build output directory
+ cmd = "set -e;rm -rf " + build_output + ";mkdir " + build_output + "\n"
+ for jar in library_result.runtime_jars:
+ cmd += "unzip -qn " + jar.path + " -d " + build_output + "\n"
+ cmd += (ctx.file._jar.path + " cmf " + manifest.path + " " +
+ deploy_jar.path + " -C " + build_output + " .\n" +
+ "touch " + build_output + "\n")
+
+ ctx.action(
+ inputs = list(library_result.runtime_jars) + [manifest] + ctx.files._jdk,
+ outputs = [deploy_jar],
+ mnemonic = "Deployjar",
+ command = cmd,
+ use_default_shell_env = True,
+ )
+
+ # Write the wrapper.
+ executable = ctx.outputs.executable
+ ctx.file_action(
+ output = executable,
+ content = "\n".join([
+ "#!/bin/bash",
+ "# autogenerated - do not edit.",
+ "case \"$0\" in",
+ "/*) self=\"$0\" ;;",
+ "*) self=\"$PWD/$0\";;",
+ "esac",
+ "",
+ "if [[ -z \"$JAVA_RUNFILES\" ]]; then",
+ " if [[ -e \"${self}.runfiles\" ]]; then",
+ " export JAVA_RUNFILES=\"${self}.runfiles\"",
+ " fi",
+ " if [[ -n \"$JAVA_RUNFILES\" ]]; then",
+ " export TEST_SRCDIR=${TEST_SRCDIR:-$JAVA_RUNFILES}",
+ " fi",
+ "fi",
+ "",
+ "jvm_bin=%s" % (ctx.file._java.path),
+ "if [[ ! -x ${jvm_bin} ]]; then",
+ " jvm_bin=$(which java)",
+ "fi",
+
+ # We extract the .so into a temp dir. If only we could mmap
+ # directly from the zip file.
+ "DEPLOY=$(dirname $self)/$(basename %s)" % deploy_jar.path,
+
+ # This works both on Darwin and Linux, with the darwin path
+ # looking like tmp.XXXXXXXX.{random}
+ "SO_DIR=$(mktemp -d -t tmp.XXXXXXXXX)",
+ "function cleanup() {",
+ " rm -rf ${SO_DIR}",
+ "}",
+ "trap cleanup EXIT",
+ "unzip -q -d ${SO_DIR} ${DEPLOY} \"*.so\" \"*.dll\" \"*.dylib\" >& /dev/null",
+ ("${jvm_bin} -Djava.library.path=${SO_DIR} %s -jar $DEPLOY \"$@\"" %
+ " ".join(ctx.attr.jvm_flags)),
+ "",
]),
- executable = True)
-
- runfiles = ctx.runfiles(files = [deploy_jar, executable] + ctx.files._jdk, collect_data = True)
- files_to_build = depset([deploy_jar, manifest, executable])
- files_to_build += library_result.files
+ executable = True,
+ )
- return struct(files = files_to_build, runfiles = runfiles)
+ runfiles = ctx.runfiles(files = [deploy_jar, executable] + ctx.files._jdk, collect_data = True)
+ files_to_build = depset([deploy_jar, manifest, executable])
+ files_to_build += library_result.files
+ return struct(files = files_to_build, runfiles = runfiles)
def java_import_impl(ctx):
- # TODO(bazel-team): Why do we need to filter here? The attribute
- # already says only jars are allowed.
- jars = depset(jar_filetype.filter(ctx.files.jars))
- neverlink_jars = depset(jar_filetype.filter(ctx.files.neverlink_jars))
- runfiles = ctx.runfiles(collect_data = True)
- return struct(files = jars,
- compile_time_jars = jars + neverlink_jars,
- runtime_jars = jars,
- runfiles = runfiles)
-
+ # TODO(bazel-team): Why do we need to filter here? The attribute
+ # already says only jars are allowed.
+ jars = depset(jar_filetype.filter(ctx.files.jars))
+ neverlink_jars = depset(jar_filetype.filter(ctx.files.neverlink_jars))
+ runfiles = ctx.runfiles(collect_data = True)
+ return struct(
+ files = jars,
+ compile_time_jars = jars + neverlink_jars,
+ runtime_jars = jars,
+ runfiles = runfiles,
+ )
java_library_attrs = {
- "_java": attr.label(default=Label("//tools/jdk:java"), single_file=True),
- "_javac": attr.label(default=Label("//tools/jdk:javac"), single_file=True),
- "_jar": attr.label(default=Label("//tools/jdk:jar"), single_file=True),
- "_jdk": attr.label(default=Label("//tools/jdk:jdk"), allow_files=True),
- "data": attr.label_list(allow_files=True, cfg="data"),
- "resources": attr.label_list(allow_files=True),
- "srcs": attr.label_list(allow_files=java_filetype),
- "jars": attr.label_list(allow_files=jar_filetype),
- "neverlink_jars": attr.label_list(allow_files=jar_filetype),
- "srcjars": attr.label_list(allow_files=srcjar_filetype),
+ "_java": attr.label(default = Label("//tools/jdk:java"), single_file = True),
+ "_javac": attr.label(default = Label("//tools/jdk:javac"), single_file = True),
+ "_jar": attr.label(default = Label("//tools/jdk:jar"), single_file = True),
+ "_jdk": attr.label(default = Label("//tools/jdk:jdk"), allow_files = True),
+ "data": attr.label_list(allow_files = True, cfg = "data"),
+ "resources": attr.label_list(allow_files = True),
+ "srcs": attr.label_list(allow_files = java_filetype),
+ "jars": attr.label_list(allow_files = jar_filetype),
+ "neverlink_jars": attr.label_list(allow_files = jar_filetype),
+ "srcjars": attr.label_list(allow_files = srcjar_filetype),
"deps": attr.label_list(
- allow_files=False,
- providers = ["compile_time_jars", "runtime_jars"]),
- }
+ allow_files = False,
+ providers = ["compile_time_jars", "runtime_jars"],
+ ),
+}
java_library = rule(
java_library_impl,
@@ -198,7 +204,7 @@ java_library = rule(
outputs = {
"class_jar": "lib%{name}.jar",
},
- fragments = ['java', 'cpp'],
+ fragments = ["java", "cpp"],
)
# A copy to avoid conflict with native rule.
@@ -208,56 +214,60 @@ bootstrap_java_library = rule(
outputs = {
"class_jar": "lib%{name}.jar",
},
- fragments = ['java'],
+ fragments = ["java"],
)
java_binary_attrs_common = dict(java_library_attrs)
java_binary_attrs_common.update({
"jvm_flags": attr.string_list(),
- "jvm": attr.label(default=Label("//tools/jdk:jdk"), allow_files=True),
+ "jvm": attr.label(default = Label("//tools/jdk:jdk"), allow_files = True),
})
java_binary_attrs = dict(java_binary_attrs_common)
-java_binary_attrs["main_class"] = attr.string(mandatory=True)
+java_binary_attrs["main_class"] = attr.string(mandatory = True)
java_binary_outputs = {
"class_jar": "lib%{name}.jar",
"deploy_jar": "%{name}_deploy.jar",
- "manifest": "%{name}_MANIFEST.MF"
+ "manifest": "%{name}_MANIFEST.MF",
}
-java_binary = rule(java_binary_impl,
- executable = True,
- attrs = java_binary_attrs,
- outputs = java_binary_outputs,
- fragments = ['java', 'cpp'],
+java_binary = rule(
+ java_binary_impl,
+ executable = True,
+ attrs = java_binary_attrs,
+ outputs = java_binary_outputs,
+ fragments = ["java", "cpp"],
)
# A copy to avoid conflict with native rule
-bootstrap_java_binary = rule(java_binary_impl,
- executable = True,
- attrs = java_binary_attrs,
- outputs = java_binary_outputs,
- fragments = ['java'],
+bootstrap_java_binary = rule(
+ java_binary_impl,
+ executable = True,
+ attrs = java_binary_attrs,
+ outputs = java_binary_outputs,
+ fragments = ["java"],
)
-java_test = rule(java_binary_impl,
- executable = True,
- attrs = dict(java_binary_attrs_common.items() + [
- ("main_class", attr.string(default="org.junit.runner.JUnitCore")),
- # TODO(bazel-team): it would be better if we could offer a
- # test_class attribute, but the "args" attribute is hard
- # coded in the bazel infrastructure.
- ]),
- outputs = java_binary_outputs,
- test = True,
- fragments = ['java', 'cpp'],
+java_test = rule(
+ java_binary_impl,
+ executable = True,
+ attrs = dict(java_binary_attrs_common.items() + [
+ ("main_class", attr.string(default = "org.junit.runner.JUnitCore")),
+ # TODO(bazel-team): it would be better if we could offer a
+ # test_class attribute, but the "args" attribute is hard
+ # coded in the bazel infrastructure.
+ ]),
+ outputs = java_binary_outputs,
+ test = True,
+ fragments = ["java", "cpp"],
)
java_import = rule(
java_import_impl,
attrs = {
- "jars": attr.label_list(allow_files=jar_filetype),
- "srcjar": attr.label(allow_files=srcjar_filetype),
- "neverlink_jars": attr.label_list(allow_files=jar_filetype, default=[]),
- })
+ "jars": attr.label_list(allow_files = jar_filetype),
+ "srcjar": attr.label(allow_files = srcjar_filetype),
+ "neverlink_jars": attr.label_list(allow_files = jar_filetype, default = []),
+ },
+)
diff --git a/tools/build_rules/test_rules.bzl b/tools/build_rules/test_rules.bzl
index d815129687..c365021c74 100644
--- a/tools/build_rules/test_rules.bzl
+++ b/tools/build_rules/test_rules.bzl
@@ -18,31 +18,33 @@
### or sometimes pass depending on a trivial computation.
def success_target(ctx, msg):
- """Return a success for an analysis test.
-
- The test rule must have an executable output.
-
- Args:
- ctx: the Bazel rule context
- msg: an informative message to display
-
- Returns:
- a suitable rule implementation struct(),
- with actions that always succeed at execution time.
- """
- exe = ctx.outputs.executable
- dat = ctx.new_file(ctx.genfiles_dir, exe, ".dat")
- ctx.actions.write(
- output=dat,
- content=msg)
- ctx.actions.write(
- output=exe,
- content="cat " + dat.path + " ; echo",
- is_executable=True)
- return struct(runfiles=ctx.runfiles([exe, dat]))
+ """Return a success for an analysis test.
+
+ The test rule must have an executable output.
+
+ Args:
+ ctx: the Bazel rule context
+ msg: an informative message to display
+
+ Returns:
+ a suitable rule implementation struct(),
+ with actions that always succeed at execution time.
+ """
+ exe = ctx.outputs.executable
+ dat = ctx.new_file(ctx.genfiles_dir, exe, ".dat")
+ ctx.actions.write(
+ output = dat,
+ content = msg,
+ )
+ ctx.actions.write(
+ output = exe,
+ content = "cat " + dat.path + " ; echo",
+ is_executable = True,
+ )
+ return struct(runfiles = ctx.runfiles([exe, dat]))
def _successful_test_impl(ctx):
- return success_target(ctx, ctx.attr.msg)
+ return success_target(ctx, ctx.attr.msg)
successful_test = rule(
attrs = {"msg": attr.string(mandatory = True)},
@@ -52,32 +54,35 @@ successful_test = rule(
)
def failure_target(ctx, msg):
- """Return a failure for an analysis test.
-
- The test rule must have an executable output.
-
- Args:
- ctx: the Bazel rule context
- msg: an informative message to display
-
- Returns:
- a suitable rule implementation struct(),
- with actions that always fail at execution time.
- """
- ### fail(msg) ### <--- This would fail at analysis time.
- exe = ctx.outputs.executable
- dat = ctx.new_file(ctx.genfiles_dir, exe, ".dat")
- ctx.file_action(
- output=dat,
- content=msg)
- ctx.file_action(
- output=exe,
- content="(cat " + dat.short_path + " ; echo ) >&2 ; exit 1",
- executable=True)
- return struct(runfiles=ctx.runfiles([exe, dat]))
+ """Return a failure for an analysis test.
+
+ The test rule must have an executable output.
+
+ Args:
+ ctx: the Bazel rule context
+ msg: an informative message to display
+
+ Returns:
+ a suitable rule implementation struct(),
+ with actions that always fail at execution time.
+ """
+
+ ### fail(msg) ### <--- This would fail at analysis time.
+ exe = ctx.outputs.executable
+ dat = ctx.new_file(ctx.genfiles_dir, exe, ".dat")
+ ctx.file_action(
+ output = dat,
+ content = msg,
+ )
+ ctx.file_action(
+ output = exe,
+ content = "(cat " + dat.short_path + " ; echo ) >&2 ; exit 1",
+ executable = True,
+ )
+ return struct(runfiles = ctx.runfiles([exe, dat]))
def _failed_test_impl(ctx):
- return failure_target(ctx, ctx.attr.msg)
+ return failure_target(ctx, ctx.attr.msg)
failed_test = rule(
attrs = {"msg": attr.string(mandatory = True)},
@@ -88,151 +93,166 @@ failed_test = rule(
### Second, general purpose utilities
-def assert_(condition, string="assertion failed", *args):
- """Trivial assertion mechanism.
+def assert_(condition, string = "assertion failed", *args):
+ """Trivial assertion mechanism.
- Args:
- condition: a generalized boolean expected to be true
- string: a format string for the error message should the assertion fail
- *args: format arguments for the error message should the assertion fail
+ Args:
+ condition: a generalized boolean expected to be true
+ string: a format string for the error message should the assertion fail
+ *args: format arguments for the error message should the assertion fail
- Returns:
- None.
+ Returns:
+ None.
- Raises:
- an error if the condition isn't true.
- """
+ Raises:
+ an error if the condition isn't true.
+ """
- if not condition:
- fail(string % args)
+ if not condition:
+ fail(string % args)
def strip_prefix(prefix, string):
- assert_(string.startswith(prefix),
- "%s does not start with %s", string, prefix)
- return string[len(prefix):len(string)]
-
-def expectation_description(expect=None, expect_failure=None):
- """Turn expectation of result or error into a string."""
- if expect_failure:
- return "failure " + str(expect_failure)
- else:
- return "result " + repr(expect)
+ assert_(
+ string.startswith(prefix),
+ "%s does not start with %s",
+ string,
+ prefix,
+ )
+ return string[len(prefix):len(string)]
+
+def expectation_description(expect = None, expect_failure = None):
+ """Turn expectation of result or error into a string."""
+ if expect_failure:
+ return "failure " + str(expect_failure)
+ else:
+ return "result " + repr(expect)
def check_results(result, failure, expect, expect_failure):
- """See if actual computation results match expectations.
-
- Args:
- result: the result returned by the test if it ran to completion
- failure: the failure message caught while testing, if any
- expect: the expected result for a successful test, if no failure expected
- expect_failure: the expected failure message for the test, if any
-
- Returns:
- a pair (tuple) of a boolean (true if success) and a message (string).
- """
- wanted = expectation_description(expect, expect_failure)
- found = expectation_description(result, failure)
- if wanted == found:
- return (True, "successfully computed " + wanted)
- else:
- return (False, "expect " + wanted + " but found " + found)
-
-def load_results(name, result=None, failure=None,
- expect=None, expect_failure=None):
- """issue load-time results of a test.
-
- Args:
- name: the name of the Bazel rule at load time.
- result: the result returned by the test if it ran to completion
- failure: the failure message caught while testing, if any
- expect: the expected result for a successful test, if no failure expected
- expect_failure: the expected failure message for the test, if any
-
- Returns:
- None, after issuing a rule that will succeed at execution time if
- expectations were met.
- """
- (is_success, msg) = check_results(result, failure, expect, expect_failure)
- this_test = successful_test if is_success else failed_test
- return this_test(name=name, msg=msg)
-
-def analysis_results(ctx, result=None, failure=None,
- expect=None, expect_failure=None):
- """issue analysis-time results of a test.
-
- Args:
- ctx: the Bazel rule context
- result: the result returned by the test if it ran to completion
- failure: the failure message caught while testing, if any
- expect: the expected result for a successful test, if no failure expected
- expect_failure: the expected failure message for the test, if any
-
- Returns:
- a suitable rule implementation struct(),
- with actions that succeed at execution time if expectation were met,
- or fail at execution time if they didn't.
- """
- (is_success, msg) = check_results(result, failure, expect, expect_failure)
- this_test = success_target if is_success else failure_target
- return this_test(ctx, msg)
+ """See if actual computation results match expectations.
+
+ Args:
+ result: the result returned by the test if it ran to completion
+ failure: the failure message caught while testing, if any
+ expect: the expected result for a successful test, if no failure expected
+ expect_failure: the expected failure message for the test, if any
+
+ Returns:
+ a pair (tuple) of a boolean (true if success) and a message (string).
+ """
+ wanted = expectation_description(expect, expect_failure)
+ found = expectation_description(result, failure)
+ if wanted == found:
+ return (True, "successfully computed " + wanted)
+ else:
+ return (False, "expect " + wanted + " but found " + found)
+
+def load_results(
+ name,
+ result = None,
+ failure = None,
+ expect = None,
+ expect_failure = None):
+ """issue load-time results of a test.
+
+ Args:
+ name: the name of the Bazel rule at load time.
+ result: the result returned by the test if it ran to completion
+ failure: the failure message caught while testing, if any
+ expect: the expected result for a successful test, if no failure expected
+ expect_failure: the expected failure message for the test, if any
+
+ Returns:
+ None, after issuing a rule that will succeed at execution time if
+ expectations were met.
+ """
+ (is_success, msg) = check_results(result, failure, expect, expect_failure)
+ this_test = successful_test if is_success else failed_test
+ return this_test(name = name, msg = msg)
+
+def analysis_results(
+ ctx,
+ result = None,
+ failure = None,
+ expect = None,
+ expect_failure = None):
+ """issue analysis-time results of a test.
+
+ Args:
+ ctx: the Bazel rule context
+ result: the result returned by the test if it ran to completion
+ failure: the failure message caught while testing, if any
+ expect: the expected result for a successful test, if no failure expected
+ expect_failure: the expected failure message for the test, if any
+
+ Returns:
+ a suitable rule implementation struct(),
+ with actions that succeed at execution time if expectation were met,
+ or fail at execution time if they didn't.
+ """
+ (is_success, msg) = check_results(result, failure, expect, expect_failure)
+ this_test = success_target if is_success else failure_target
+ return this_test(ctx, msg)
### Simple tests
def _rule_test_impl(ctx):
- """check that a rule generates the desired outputs and providers."""
- rule_ = ctx.attr.rule
- rule_name = str(rule_.label)
- exe = ctx.outputs.executable
- if ctx.attr.generates:
- # Generate the proper prefix to remove from generated files.
- prefix_parts = []
-
- if rule_.label.workspace_root:
- # Create a prefix that is correctly relative to the output of this rule.
- prefix_parts = ["..", strip_prefix("external/", rule_.label.workspace_root)]
-
- if rule_.label.package:
- prefix_parts.append(rule_.label.package)
-
- prefix = "/".join(prefix_parts)
-
- if prefix:
- # If the prefix isn't empty, it needs a trailing slash.
- prefix = prefix + "/"
-
- # TODO(bazel-team): Use set() instead of sorted() once
- # set comparison is implemented.
- # TODO(bazel-team): Use a better way to determine if two paths refer to
- # the same file.
- generates = sorted(ctx.attr.generates)
- generated = sorted([strip_prefix(prefix, f.short_path)
- for f in rule_.files.to_list()])
- if generates != generated:
- fail("rule %s generates %s not %s"
- % (rule_name, repr(generated), repr(generates)))
- provides = ctx.attr.provides
- if provides:
- files = []
- commands = []
- for k in provides.keys():
- if hasattr(rule_, k):
- v = repr(getattr(rule_, k))
- else:
- fail(("rule %s doesn't provide attribute %s. "
- + "Its list of attributes is: %s")
- % (rule_name, k, dir(rule_)))
- file_ = ctx.new_file(ctx.genfiles_dir, exe, "." + k)
- files += [file_]
- regexp = provides[k]
- commands += [
- "if ! grep %s %s ; then echo 'bad %s:' ; cat %s ; echo ; exit 1 ; fi"
- % (repr(regexp), file_.short_path, k, file_.short_path)]
- ctx.file_action(output=file_, content=v)
- script = "\n".join(commands + ["true"])
- ctx.file_action(output=exe, content=script, executable=True)
- return struct(runfiles=ctx.runfiles([exe] + files))
- else:
- return success_target(ctx, "success")
+ """check that a rule generates the desired outputs and providers."""
+ rule_ = ctx.attr.rule
+ rule_name = str(rule_.label)
+ exe = ctx.outputs.executable
+ if ctx.attr.generates:
+ # Generate the proper prefix to remove from generated files.
+ prefix_parts = []
+
+ if rule_.label.workspace_root:
+ # Create a prefix that is correctly relative to the output of this rule.
+ prefix_parts = ["..", strip_prefix("external/", rule_.label.workspace_root)]
+
+ if rule_.label.package:
+ prefix_parts.append(rule_.label.package)
+
+ prefix = "/".join(prefix_parts)
+
+ if prefix:
+ # If the prefix isn't empty, it needs a trailing slash.
+ prefix = prefix + "/"
+
+ # TODO(bazel-team): Use set() instead of sorted() once
+ # set comparison is implemented.
+ # TODO(bazel-team): Use a better way to determine if two paths refer to
+ # the same file.
+ generates = sorted(ctx.attr.generates)
+ generated = sorted([
+ strip_prefix(prefix, f.short_path)
+ for f in rule_.files.to_list()
+ ])
+ if generates != generated:
+ fail("rule %s generates %s not %s" %
+ (rule_name, repr(generated), repr(generates)))
+ provides = ctx.attr.provides
+ if provides:
+ files = []
+ commands = []
+ for k in provides.keys():
+ if hasattr(rule_, k):
+ v = repr(getattr(rule_, k))
+ else:
+ fail(("rule %s doesn't provide attribute %s. " +
+ "Its list of attributes is: %s") %
+ (rule_name, k, dir(rule_)))
+ file_ = ctx.new_file(ctx.genfiles_dir, exe, "." + k)
+ files += [file_]
+ regexp = provides[k]
+ commands += [
+ "if ! grep %s %s ; then echo 'bad %s:' ; cat %s ; echo ; exit 1 ; fi" %
+ (repr(regexp), file_.short_path, k, file_.short_path),
+ ]
+ ctx.file_action(output = file_, content = v)
+ script = "\n".join(commands + ["true"])
+ ctx.file_action(output = exe, content = script, executable = True)
+ return struct(runfiles = ctx.runfiles([exe] + files))
+ else:
+ return success_target(ctx, "success")
rule_test = rule(
attrs = {
@@ -246,36 +266,42 @@ rule_test = rule(
)
def _file_test_impl(ctx):
- """check that a file has a given content."""
- exe = ctx.outputs.executable
- file_ = ctx.file.file
- content = ctx.attr.content
- regexp = ctx.attr.regexp
- matches = ctx.attr.matches
- if bool(content) == bool(regexp):
- fail("Must specify one and only one of content or regexp")
- if content and matches != -1:
- fail("matches only makes sense with regexp")
- if content:
- dat = ctx.new_file(ctx.genfiles_dir, exe, ".dat")
- ctx.file_action(
- output=dat,
- content=content)
+ """check that a file has a given content."""
+ exe = ctx.outputs.executable
+ file_ = ctx.file.file
+ content = ctx.attr.content
+ regexp = ctx.attr.regexp
+ matches = ctx.attr.matches
+ if bool(content) == bool(regexp):
+ fail("Must specify one and only one of content or regexp")
+ if content and matches != -1:
+ fail("matches only makes sense with regexp")
+ if content:
+ dat = ctx.new_file(ctx.genfiles_dir, exe, ".dat")
+ ctx.file_action(
+ output = dat,
+ content = content,
+ )
+ ctx.file_action(
+ output = exe,
+ content = "diff -u %s %s" % (dat.short_path, file_.short_path),
+ executable = True,
+ )
+ return struct(runfiles = ctx.runfiles([exe, dat, file_]))
+ if matches != -1:
+ script = "[ %s == $(grep -c %s %s) ]" % (
+ matches,
+ repr(regexp),
+ file_.short_path,
+ )
+ else:
+ script = "grep %s %s" % (repr(regexp), file_.short_path)
ctx.file_action(
- output=exe,
- content="diff -u %s %s" % (dat.short_path, file_.short_path),
- executable=True)
- return struct(runfiles=ctx.runfiles([exe, dat, file_]))
- if matches != -1:
- script = "[ %s == $(grep -c %s %s) ]" % (
- matches, repr(regexp), file_.short_path)
- else:
- script = "grep %s %s" % (repr(regexp), file_.short_path)
- ctx.file_action(
- output=exe,
- content=script,
- executable=True)
- return struct(runfiles=ctx.runfiles([exe, file_]))
+ output = exe,
+ content = script,
+ executable = True,
+ )
+ return struct(runfiles = ctx.runfiles([exe, file_]))
file_test = rule(
attrs = {
diff --git a/tools/build_rules/utilities.bzl b/tools/build_rules/utilities.bzl
index 5574c63187..2dc290c798 100644
--- a/tools/build_rules/utilities.bzl
+++ b/tools/build_rules/utilities.bzl
@@ -16,23 +16,22 @@
"""This rule exposes the source jar of a java_*_library rule as a label."""
def _java_library_srcs_impl(ctx):
- if len(ctx.attr.deps) != 1:
- fail("Only one deps value supported", "deps")
- dep = ctx.attr.deps[0]
- return [DefaultInfo(files=depset(dep.java.source_jars))]
-
+ if len(ctx.attr.deps) != 1:
+ fail("Only one deps value supported", "deps")
+ dep = ctx.attr.deps[0]
+ return [DefaultInfo(files = depset(dep.java.source_jars))]
_java_library_srcs = rule(
- implementation=_java_library_srcs_impl,
- attrs={
- "deps":
- attr.label_list(
- mandatory=True,
- non_empty=True,
- providers=["java"],)
- })
-
+ implementation = _java_library_srcs_impl,
+ attrs = {
+ "deps": attr.label_list(
+ mandatory = True,
+ non_empty = True,
+ providers = ["java"],
+ ),
+ },
+)
-def java_library_srcs(name, deps, visibility=None, **kwargs):
- """Provides the source jars generated by a java_*_library rule."""
- _java_library_srcs(name=name, deps=deps, visibility=visibility, **kwargs)
+def java_library_srcs(name, deps, visibility = None, **kwargs):
+ """Provides the source jars generated by a java_*_library rule."""
+ _java_library_srcs(name = name, deps = deps, visibility = visibility, **kwargs)