diff options
author | Kristina Chodorow <kchodorow@google.com> | 2016-03-23 21:20:22 +0000 |
---|---|---|
committer | Damien Martin-Guillerez <dmarting@google.com> | 2016-03-24 10:31:46 +0000 |
commit | 96df361ac0fe25d908515234bff944bad3269216 (patch) | |
tree | c477e47b57f6d998a1cddc9bc981e2ee1e29e450 /tools/build_rules | |
parent | 1325cc1ba2f5e9318df8d673bab4f440c595cac0 (diff) |
Remove deprecated Skylark rules
--
MOS_MIGRATED_REVID=117968196
Diffstat (limited to 'tools/build_rules')
-rw-r--r-- | tools/build_rules/appengine/BUILD | 25 | ||||
-rw-r--r-- | tools/build_rules/appengine/README.md | 231 | ||||
-rw-r--r-- | tools/build_rules/appengine/appengine.bzl | 316 | ||||
-rw-r--r-- | tools/build_rules/appengine/appengine_deploy.sh.template | 48 | ||||
-rw-r--r-- | tools/build_rules/appengine/appengine_runner.sh.template | 52 | ||||
-rw-r--r-- | tools/build_rules/deprecation.bzl | 27 | ||||
-rw-r--r-- | tools/build_rules/go/BUILD | 15 | ||||
-rw-r--r-- | tools/build_rules/go/DESIGN.md | 61 | ||||
-rw-r--r-- | tools/build_rules/go/README.md | 292 | ||||
-rw-r--r-- | tools/build_rules/go/def.bzl | 431 | ||||
-rw-r--r-- | tools/build_rules/go/toolchain/BUILD | 42 | ||||
-rw-r--r-- | tools/build_rules/go/tools/BUILD | 17 | ||||
-rw-r--r-- | tools/build_rules/go/tools/filter_tags/BUILD | 19 | ||||
-rw-r--r-- | tools/build_rules/go/tools/filter_tags/filter_tags.go | 51 | ||||
-rw-r--r-- | tools/build_rules/go/tools/filter_tags/filter_tags_test.go | 119 | ||||
-rw-r--r-- | tools/build_rules/go/tools/generate_test_main.go | 95 |
16 files changed, 0 insertions, 1841 deletions
diff --git a/tools/build_rules/appengine/BUILD b/tools/build_rules/appengine/BUILD deleted file mode 100644 index 235ebf0873..0000000000 --- a/tools/build_rules/appengine/BUILD +++ /dev/null @@ -1,25 +0,0 @@ -# A target to ensure the servlet-api is not linked in the webapp. -java_library( - name = "javax.servlet.api", - neverlink = 1, - visibility = ["//visibility:public"], - exports = ["@javax_servlet_api//jar:jar"], -) - -filegroup( - name = "runner_template", - srcs = ["appengine_runner.sh.template"], - visibility = ["//visibility:public"], -) - -filegroup( - name = "deploy_template", - srcs = ["appengine_deploy.sh.template"], - visibility = ["//visibility:public"], -) - -filegroup( - name = "srcs", - srcs = glob(["**"]), - visibility = ["//tools:__pkg__"], -) diff --git a/tools/build_rules/appengine/README.md b/tools/build_rules/appengine/README.md deleted file mode 100644 index 0b047c9203..0000000000 --- a/tools/build_rules/appengine/README.md +++ /dev/null @@ -1,231 +0,0 @@ -# Java App Engine Rules for Bazel - -<div class="toc"> - <h2>Rules</h2> - <ul> - <li><a href="#appengine_war">appengine_war</a></li> - <li><a href="#java_war">java_war</a></li> - </ul> -</div> - -## Overview - -These build rules are used for building -[Java App Engine](https://cloud.google.com/appengine/docs/java/) -application with Bazel. It does not aim at general Java web application -support but can be easily modified to handle a standard web application. - -<a name="setup"></a> -## Setup - -To be able to use the Java App Engine rules, you must make the App Engine SDK -available to Bazel. The easiest way to do so is by adding the following to your -`WORKSPACE` file: - -```python -load("@bazel_tools//tools/build_rules/appengine:appengine.bzl", "appengine_repositories") - -appengine_repositories() -``` - -<a name="basic-example"></a> -## Basic Example - -Suppose you have the following directory structure for a simple App Engine -application: - -``` -[workspace]/ - WORKSPACE - hello_app/ - BUILD - java/my/webapp/ - TestServlet.java - webapp/ - index.html - webapp/WEB-INF - web.xml - appengine-web.xml -``` - -Then, to build your webapp, your `hello_app/BUILD` can look like: - -```python -load("@bazel_tools//tools/build_rules/appengine:appengine.bzl", "appengine_war") - -java_library( - name = "mylib", - srcs = ["java/my/webapp/TestServlet.java"], - deps = [ - "//external:appengine/java/api", - "//external:javax/servlet/api", - ], -) - -appengine_war( - name = "myapp", - jars = [":mylib"], - data = glob(["webapp/**"]), - data_path = "webapp", -) -``` - -For simplicity, you can use the `java_war` rule to build an app from source. -Your `hello_app/BUILD` file would then look like: - -```python -load("@bazel_tools//tools/build_rules/appengine:appengine.bzl", "java_war") - -java_war( - name = "myapp", - srcs = ["java/my/webapp/TestServlet.java"], - data = glob(["webapp/**"]), - data_path = "webapp", - deps = [ - "//external:appengine/java/api", - "//external:javax/servlet/api", - ], -) -``` - -You can then build the application with `bazel build //hello_app:myapp` and -run in it a development server with `bazel run //hello_app:myapp`. This will -bind a test server on port 8080. If you wish to select another port, -simply append the `--port=12345` to the command-line. - -Another target `//hello_app:myapp.deploy` allows you to deploy your -application to App Engine. It takes an optional argument: the -`APP_ID`. If not specified, it uses the default `APP_ID` provided in -the application. This target needs to be authorized to App Engine. Since -Bazel does not connect the standard input, it is easier to run it by: -``` -bazel-bin/hello_app/myapp.deploy APP_ID -``` - -After the first launch, subsequent launch will be registered to -App Engine so you can just do a normal `bazel run -//hello_app:myapp.deploy APP_ID` to deploy next versions of -your application. - -<a name="appengine_war"></a> -## appengine_war - -```python -appengine_war(name, jars, data, data_path) -``` - -<table class="table table-condensed table-bordered table-params"> - <colgroup> - <col class="col-param" /> - <col class="param-description" /> - </colgroup> - <thead> - <tr> - <th colspan="2">Attributes</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>name</code></td> - <td> - <code>Name, required</code> - <p>A unique name for this rule.</p> - </td> - </tr> - <tr> - <td><code>jars</code></td> - <td> - <code>List of labels, required</code> - <p> - List of JAR files that will be uncompressed as the code for the - Web Application. - </p> - <p> - If it is a `java_library` or a `java_import`, the - JAR from the runtime classpath will be added in the `lib` directory - of the Web Application. - </p> - </td> - </tr> - <tr> - <td><code>data</code></td> - <td> - <code>List of files, optional</code> - <p>List of files used by the Web Application at runtime.</p> - <p> - This attribute can be used to specify the list of resources to - be included into the WAR file. - </p> - </td> - </tr> - <tr> - <td><code>data_path</code></td> - <td> - <code>String, optional</code> - <p>Root path of the data.</p> - <p> - The directory structure from the data is preserved inside the - WebApplication but a prefix path determined by `data_path` - is removed from the the directory structure. This path can - be absolute from the workspace root if starting with a `/` or - relative to the rule's directory. It is set to `.` by default. - </p> - </td> - </tr> - </tbody> -</table> - -<a name="java_war"></a> -## java_war - -``` -java_war(name, data, data_path, **kwargs) -``` - -<table class="table table-condensed table-bordered table-params"> - <colgroup> - <col class="col-param" /> - <col class="param-description" /> - </colgroup> - <thead> - <tr> - <th colspan="2">Attributes</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>name</code></td> - <td> - <code>Name, required</code> - <p>A unique name for this rule.</p> - </td> - </tr> - <tr> - <td><code>data</code></td> - <td> - <code>List of labels, optional</code> - <p>List of files used by the Web Application at runtime.</p> - <p>Passed to the <a href="#appengine_war">appengine_war</a> rule.</p> - </td> - </tr> - <tr> - <td><code>data_path</code></td> - <td> - <code>String, optional</code> - <p>Root path of the data.</p> - <p>Passed to the <a href="#appengine_war">appengine_war</a> rule.</p> - </td> - </tr> - <tr> - <td><code>**kwargs</code></td> - <td> - <code>see <a href="http://bazel.io/docs/be/java.html#java_library">java_library</a></code> - <p> - The other arguments of this rule will be passed to build a `java_library` - that will be passed in the `jar` arguments of a - <a href="#appengine_war">appengine_war</a> rule. - </p> - </td> - </tr> - </tbody> -</table> diff --git a/tools/build_rules/appengine/appengine.bzl b/tools/build_rules/appengine/appengine.bzl deleted file mode 100644 index 1abbc83a44..0000000000 --- a/tools/build_rules/appengine/appengine.bzl +++ /dev/null @@ -1,316 +0,0 @@ -# Copyright 2015 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Java AppEngine support for Bazel. - -For now, it only support bundling a WebApp and running locally. - -To create a WebApp for Google AppEngine, add the rules: -appengine_war( - name = "MyWebApp", - # Jars to use for the classpath in the webapp. - jars = ["//java/com/google/examples/mywebapp:java"], - # data to put in the webapp, the directory structure of the data set - # will be maintained. - data = ["//java/com/google/examples/mywebapp:data"], - # Data's root path, it will be considered as the root of the data files. - # If unspecified, the path to the current package will be used. The path is - # relative to current package or, relative to the workspace root if starting - # with a leading slash. - data_path = "/java/com/google/examples/mywebapp", -) - - -You can also make directly a single target for it with: - -java_war( - name = "MyWebApp", - srcs = glob(["**/*.java"]), - resources = ["..."], - data = ["..."], - data_path = "...", -) - -Resources will be put in the classpath whereas data will be bundled at the root -of the war file. This is strictly equivalent to (it is actually a convenience -macros that translate to that): - -java_library( - name = "libMyWebApp", - srcs = glob(["**/*.java"]), - resources = ["..."], -) - -appengine_war( - name = "MyWebApp", - jars = [":libMyWebApp"], - data = ["..."], - data_path = "...", -) - -This rule will also create a .deploy target that will try to use the AppEngine -SDK to upload your application to AppEngine. It takes an optional argument: the -APP_ID. If not specified, it uses the default APP_ID provided in the application -web.xml. -""" - -load("//tools/build_rules:deprecation.bzl", "deprecated") - -def warning(rule): - print(deprecated( - "appengine", - rule, - "@bazel_tools//tools/build_rules/appengine:appengine.bzl", - "@io_bazel_rules_appengine//appengine:appengine.bzl")) - -jar_filetype = FileType([".jar"]) - -def _add_file(in_file, output, path = None): - output_path = output - input_path = in_file.path - if path and input_path.startswith(path): - output_path += input_path[len(path):] - return [ - "mkdir -p $(dirname %s)" % output_path, - "test -L %s || ln -s $(pwd)/%s %s\n" % (output_path, input_path, - output_path) - ] - -def _make_war(zipper, input_dir, output): - return [ - "(root=$(pwd);" + - ("cd %s &&" % input_dir) + - ("${root}/%s Cc ${root}/%s $(find .))" % (zipper.path, output.path)) - ] - -def _common_substring(str1, str2): - i = 0 - res = "" - for c in str1: - if str2[i] != c: - return res - res += c - i += 1 - return res - -def _short_path_dirname(path): - sp = path.short_path - return sp[0:len(sp)-len(path.basename)-1] - -def _war_impl(ctxt): - warning("appengine_war") - zipper = ctxt.file._zipper - - data_path = ctxt.attr.data_path - if not data_path: - data_path = _short_path_dirname(ctxt.outputs.war) - elif data_path[0] == "/": - data_path = data_path[1:] - else: # relative path - data_path = _short_path_dirname(ctxt.outputs.war) + "/" + data_path - - war = ctxt.outputs.war - build_output = war.path + ".build_output" - cmd = [ - "set -e;rm -rf " + build_output, - "mkdir -p " + build_output - ] - - inputs = [zipper] - cmd += ["mkdir -p %s/WEB-INF/lib" % build_output] - - transitive_deps = set() - for jar in ctxt.attr.jars: - if hasattr(jar, "java"): # java_library, java_import - transitive_deps += jar.java.transitive_runtime_deps - elif hasattr(jar, "files"): # a jar file - transitive_deps += jar.files - - for dep in transitive_deps: - cmd += _add_file(dep, build_output + "/WEB-INF/lib") - inputs.append(dep) - - for jar in ctxt.files._appengine_deps: - cmd += _add_file(jar, build_output + "/WEB-INF/lib") - inputs.append(jar) - - inputs += ctxt.files.data - for res in ctxt.files.data: - # Add the data file - cmd += _add_file(res, build_output, path = data_path) - - cmd += _make_war(zipper, build_output, war) - - ctxt.action( - inputs = inputs, - outputs = [war], - mnemonic="WAR", - command="\n".join(cmd), - use_default_shell_env=True) - - executable = ctxt.outputs.executable - appengine_sdk = None - for f in ctxt.files._appengine_sdk: - if not appengine_sdk: - appengine_sdk = f.path - elif not f.path.startswith(appengine_sdk): - appengine_sdk = _common_substring(appengine_sdk, f.path) - - classpath = [ - "${JAVA_RUNFILES}/%s" % jar.short_path - for jar in ctxt.files._appengine_jars - ] - substitutions = { - "%{zipper}": ctxt.file._zipper.short_path, - "%{war}": ctxt.outputs.war.short_path, - "%{java}": ctxt.file._java.short_path, - "%{appengine_sdk}": appengine_sdk, - "%{classpath}": (":".join(classpath)), - } - ctxt.template_action( - output = executable, - template = ctxt.file._runner_template, - substitutions = substitutions, - executable = True) - ctxt.template_action( - output = ctxt.outputs.deploy, - template = ctxt.file._deploy_template, - substitutions = substitutions, - executable = True) - - runfiles = ctxt.runfiles(files = [war, executable] - + ctxt.files._appengine_sdk - + ctxt.files._appengine_jars - + [ctxt.file._java, ctxt.file._zipper]) - return struct(runfiles = runfiles) - -appengine_war = rule( - _war_impl, - attrs = { - "_java": attr.label( - default = Label("@bazel_tools//tools/jdk:java"), - single_file = True, - ), - "_zipper": attr.label( - default = Label("@bazel_tools//tools/zip:zipper"), - single_file = True, - ), - "_runner_template": attr.label( - default = Label("@bazel_tools//tools/build_rules/appengine:runner_template"), - single_file = True, - ), - "_deploy_template": attr.label( - default = Label("@bazel_tools//tools/build_rules/appengine:deploy_template"), - single_file = True, - ), - "_appengine_sdk": attr.label( - default = Label("//external:appengine/java/sdk"), - ), - "_appengine_jars": attr.label( - default = Label("//external:appengine/java/jars"), - ), - "_appengine_deps": attr.label_list( - default = [ - Label("@com_google_appengine_java//:api"), - Label("@org_apache_commons_lang//jar"), - Label("@org_apache_commons_collections//jar"), - ], - ), - "jars": attr.label_list( - allow_files = jar_filetype, - mandatory = True, - ), - "data": attr.label_list(allow_files = True), - "data_path": attr.string(), - }, - executable = True, - outputs = { - "war": "%{name}.war", - "deploy": "%{name}.deploy", - }, -) - -def java_war(name, data=[], data_path=None, **kwargs): - warning("java_war") - native.java_library(name = "lib%s" % name, **kwargs) - appengine_war(name = name, - jars = ["lib%s" % name], - data=data, - data_path=data_path) - -APPENGINE_BUILD_FILE = """ -# BUILD file to use the Java AppEngine SDK with a remote repository. -java_import( - name = "jars", - jars = glob(["**/*.jar"]), - visibility = ["//visibility:public"], -) - -java_import( - name = "api", - jars = ["appengine-java-sdk-1.9.23/lib/impl/appengine-api.jar"], - visibility = ["//visibility:public"], - neverlink = 1, -) - -filegroup( - name = "sdk", - srcs = glob(["appengine-java-sdk-1.9.23/**"]), - visibility = ["//visibility:public"], - path = "appengine-java-sdk-1.9.23", -) -""" - -def appengine_repositories(): - warning("appengine_repositories") - native.new_http_archive( - name = "com_google_appengine_java", - url = "http://central.maven.org/maven2/com/google/appengine/appengine-java-sdk/1.9.23/appengine-java-sdk-1.9.23.zip", - sha256 = "05e667036e9ef4f999b829fc08f8e5395b33a5a3c30afa9919213088db2b2e89", - build_file_content = APPENGINE_BUILD_FILE, - ) - - native.bind( - name = "appengine/java/sdk", - actual = "@com_google_appengine_java//:sdk", - ) - - native.bind( - name = "appengine/java/api", - actual = "@com_google_appengine_java//:api", - ) - - native.bind( - name = "appengine/java/jars", - actual = "@com_google_appengine_java//:jars", - ) - - native.maven_jar( - name = "javax_servlet_api", - artifact = "javax.servlet:servlet-api:2.5", - ) - - native.bind( - name = "javax/servlet/api", - actual = "@bazel_tools//tools/build_rules/appengine:javax.servlet.api", - ) - - native.maven_jar( - name = "org_apache_commons_lang", - artifact = "commons-lang:commons-lang:2.6", - ) - - native.maven_jar( - name = "org_apache_commons_collections", - artifact = "commons-collections:commons-collections:3.2.2", - ) diff --git a/tools/build_rules/appengine/appengine_deploy.sh.template b/tools/build_rules/appengine/appengine_deploy.sh.template deleted file mode 100644 index b61ddb023d..0000000000 --- a/tools/build_rules/appengine/appengine_deploy.sh.template +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -# Copyright 2015 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -case "$0" in -/*) self="$0" ;; -*) self="$PWD/$0";; -esac - -if [[ -z "$JAVA_RUNFILES" ]]; then - if [[ -e "${self%.deploy}.runfiles" ]]; then - JAVA_RUNFILES="${self%.deploy}.runfiles" - else - JAVA_RUNFILES=$PWD - fi -fi - -root_path=$(pwd) -tmp_dir=$(mktemp -d ${TMPDIR:-/tmp}/war.XXXXXXXX) -trap "{ cd ${root_path}; rm -rf ${tmp_dir}; }" EXIT -cd ${tmp_dir} -${JAVA_RUNFILES}/%{zipper} x ${JAVA_RUNFILES}/%{war} -cd ${root_dir} - -APP_ENGINE_ROOT=${JAVA_RUNFILES}/%{appengine_sdk} -if [ -n "${1-}" ]; then - ${APP_ENGINE_ROOT}/bin/appcfg.sh -A "$1" update ${tmp_dir} - retCode=$? -else - ${APP_ENGINE_ROOT}/bin/appcfg.sh update ${tmp_dir} - retCode=$? -fi - -rm -rf ${tmp_dir} -trap - EXIT - -exit $retCode diff --git a/tools/build_rules/appengine/appengine_runner.sh.template b/tools/build_rules/appengine/appengine_runner.sh.template deleted file mode 100644 index d6ff8215f1..0000000000 --- a/tools/build_rules/appengine/appengine_runner.sh.template +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash -# Copyright 2015 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -case "$0" in -/*) self="$0" ;; -*) self="$PWD/$0";; -esac - -if [[ -z "$JAVA_RUNFILES" ]]; then - if [[ -e "${self}.runfiles" ]]; then - JAVA_RUNFILES="${self}.runfiles" - fi -fi - -root_path=$(pwd) -tmp_dir=$(mktemp -d ${TMPDIR:-/tmp}/war.XXXXXXXX) -trap "{ cd ${root_path}; rm -rf ${tmp_dir}; }" EXIT -cd ${tmp_dir} - -${JAVA_RUNFILES}/%{zipper} x ${JAVA_RUNFILES}/%{war} - -jvm_bin=${JAVA_RUNFILES}/%{java} -if [[ ! -x ${jvm_bin} ]]; then - jvm_bin=$(which java) -fi - -APP_ENGINE_ROOT=${JAVA_RUNFILES}/%{appengine_sdk} -main_class="com.google.appengine.tools.development.DevAppServerMain" -classpath="%{classpath}" - -${jvm_bin} -Dappengine.sdk.root=${APP_ENGINE_ROOT} -cp "${classpath}" \ - ${main_class} "$@" ${tmp_dir} -retCode=$? - -# We remove the trap so the return code doesn't get intercepted by it on OS X. -cd ${root_path} -rm -rf ${tmp_dir} -trap - EXIT - -exit $retCode diff --git a/tools/build_rules/deprecation.bzl b/tools/build_rules/deprecation.bzl deleted file mode 100644 index e85953e831..0000000000 --- a/tools/build_rules/deprecation.bzl +++ /dev/null @@ -1,27 +0,0 @@ -# -# Copyright 2016 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -def deprecated(language, rule, old_path, new_path): - return """This rule has moved out of @bazel_tools! - -The {0} rules have moved to https://github.com/bazelbuild/rules_{0}, you -should now refer them via @io_bazel_rules_{0}, use: - -load('{3}', '{1}') - -instead of: - -load('{2}', '{1}') -""".format(language, rule, old_path, new_path) diff --git a/tools/build_rules/go/BUILD b/tools/build_rules/go/BUILD deleted file mode 100644 index 24d5589187..0000000000 --- a/tools/build_rules/go/BUILD +++ /dev/null @@ -1,15 +0,0 @@ -package( - default_visibility = ["//visibility:public"], -) - -filegroup( - name = "srcs", - srcs = glob(["**"]) + [ - "//tools/build_rules/go/tools:srcs", - "//tools/build_rules/go/toolchain:srcs", - ], - visibility = [ - "//src:__subpackages__", - "//tools:__pkg__", - ], -) diff --git a/tools/build_rules/go/DESIGN.md b/tools/build_rules/go/DESIGN.md deleted file mode 100644 index 15015c4ae3..0000000000 --- a/tools/build_rules/go/DESIGN.md +++ /dev/null @@ -1,61 +0,0 @@ -Go support in Bazel -=================== - -Objective ---------- - -Provide Go support in Bazel that feels familiar to existing Go users and -existing Go tools. - - -Use cases ---------- - -Users might find benefit from using Bazel for Go in the following scenarios: - -* Multi-language/multi-platform builds, where not all platforms are supported by `go` natively. For example: test iOS app running against a Go backend from a single tool, or Bazel itself, where the BUILD file formatter (`buildifier`) is written Go, and Bazel (Java/C++) interact. -* Large Go projects, where correctness and scalability of `go` become a problem. -* Go projects where the executable is not the final product. -* Projects with complex native code builds, eg. a Go server that uses first party native code through CGO. -* Projects with complex code generation steps, such as protocol buffers. - -Constraints ------------ - -The Go rules should not impose restrictions on how non-Go projects should organize their source trees. - -Proposal --------- - -* Bazel will support `go_library`, `go_binary` and `go_test` rules. These take go files as srcs, and `go_library` rules as `deps`. Along with the rules, we will have a tool that generates the main.go file based on the sources of a go_test rule. -* The go rules use a global setting `GO_PREFIX`. `GO_PREFIX` is set through Bazel's `WORKSPACE` mechanism, and may be empty. It is recommended that Go projects use the canonical import name (eg. `github.com/name/project`) as `GO_PREFIX` in Bazel. -* The go rules will support dependencies on go_library targets with other names, eg. `//a/b:c`. These are to be imported as `GO_PREFIX/a/b/c`. This convention is typically used for depending on generated Go code. -* The go rules will support a magic target name `go_default_library`. A dependency on `//a/b:go_default_library` will be staged by Bazel so it can be imported in a go file as `GO_PREFIX/a/b`, rather than `GO_PREFIX/a/b/go_default_library`. -* For making Bazel work with Go, we will have a tool called `glaze`, which analyzes the Go source files in a directory, and emits a BUILD file to match. Glaze must be run by hand (or, as an editor hook) when modifying Go code. -* When Glaze encounters an import line `GO_PREFIX/a/b` for which `a/b/` is a directory, it will write a dependency on `//a/b:go_default_library`. -* If a target has a dependency that contains a `vendor` directory component, the compiler will be invoked with a corresponding `-importmap` option, eg. a dependency on `x/y/vendor/domain/p/q:target` will yield `-importmap=domain/p/q/target=GO_PREFIX/x/y/vendor/domain/p/q/target`. - * Multiple dependencies that map to the same importmap key is an analysis-time error. -* When Glaze encounters an import line that can be satisfied from a `vendor/` directory, as specified in the [Go vendoring decision](https://docs.google.com/document/d/1Bz5-UB7g2uPBdOx-rw5t9MxJwkfpx90cqG9AFL0JAYo/), it will emit the full target name of the vendored library. - -Caveats -------- - -Is not fully compatible with the `go` tool: -* `go` still cannot handle generated source code (ie. protocol buffers) -* the workspace will need to be in a directory called `src` for `go` to work with it (possibly through a symlink) -* Does not address compatibility with `go generate`: - * Bazel puts sources and artifacts in different directories, so `go` tooling does not work out of the box if only parts of a go library are generated. - * We could export the generated sources as some sort of tree with `//go:generate` lines in the source, but the command line will not run if the generator was built by Bazel too. - * We could import generated sources by extracting `//go:generate` lines. Since the lines do not declare the sources of the invoked tooling, this will be hard to automatically get right, though. -* The `GO_PREFIX` that `WORKSPACE` sets is similar to the workspace name (see build encyclopedia), but it should only affect Go. Since Go prefixes are URLs, they contain dots, so using the `WORKSPACE` name would break Python imports. -* Does not specify how native interoperability (eg. cgo) should work. - -Implementation plan -------------------- - -* Implement `go_prefix` support in `WORKSPACE` -* Reintroduce the Skylark Go rules, but supporting `go_default_library` and `go_prefix`. -* Ship them in Bazel; this yields bare bones rules. -* Open-source the `BUILD` file formatter, and use it as basis to create `glaze`. -* Open-source compiler glue program and use it in the Skylark rules. This will yields conformance with //+ build tags, and other build system directives embedded in source code. -* Consider cleaning and opening up internal rules. diff --git a/tools/build_rules/go/README.md b/tools/build_rules/go/README.md deleted file mode 100644 index 535c2a487a..0000000000 --- a/tools/build_rules/go/README.md +++ /dev/null @@ -1,292 +0,0 @@ -# Go rules - -<div class="toc"> - <h2>Rules</h2> - <ul> - <li><a href="#go_prefix">go_prefix</a></li> - <li><a href="#go_library">go_library</a></li> - <li><a href="#go_binary">go_binary</a></li> - <li><a href="#go_test">go_test</a></li> - </ul> -</div> - -## Overview - -The rules should be considered experimental. They support: - -* libraries -* binaries -* tests -* vendoring - -They currently do not support (in order of importance): - -* `//+build` tags -* auto generated BUILD files. -* C/C++ interoperation (cgo, swig etc.) -* race detector -* coverage -* test sharding - -## Setup - -* Decide on the name of your package, eg. `github.com/joe/project` -* Add the following to your WORKSPACE file: - - ```python - load("@bazel_tools//tools/build_rules/go:def.bzl", "go_repositories") - - go_repositories() - ``` - -* Add a `BUILD` file to the top of your workspace, declaring the name of your - workspace using `go_prefix`. It is strongly recommended that the prefix is not - empty. - - ```python - load("@bazel_tools//tools/build_rules/go:def.bzl", "go_prefix") - - go_prefix("github.com/joe/project") - ``` - -* For a library `github.com/joe/project/lib`, create `lib/BUILD`, containing - - ```python - load("@bazel_tools//tools/build_rules/go:def.bzl", "go_library") - - go_library( - name = "go_default_library", - srcs = ["file.go"] - ) - ``` - -* Inside your project, you can use this library by declaring a dependency - - ```python - go_binary( - ... - deps = ["//lib:go_default_library"] - ) - ``` - -* In this case, import the library as `github.com/joe/project/lib`. -* For vendored libraries, you may depend on - `//lib/vendor/github.com/user/project:go_default_library`. Vendored - libraries should have BUILD files like normal libraries. -* To declare a test, - - ```python - go_test( - name = "mytest", - srcs = ["file_test.go"], - library = ":go_default_library" - ) - ``` - -## FAQ - -### Can I still use the `go` tool? - -Yes, this setup was deliberately chosen to be compatible with the `go` -tool. Make sure your workspace appears under - -```sh -$GOROOT/src/github.com/joe/project/ -``` - -eg. - -```sh -mkdir -p $GOROOT/src/github.com/joe/ -ln -s my/bazel/workspace $GOROOT/src/github.com/joe/project -``` - -and it should work. - -## Disclaimer - -These rules are not supported by Google's Go team. - -<a name="go_prefix"></a> -## go\_prefix - -```python -go_prefix(prefix) -``` - -<table class="table table-condensed table-bordered table-params"> - <colgroup> - <col class="col-param" /> - <col class="param-description" /> - </colgroup> - <thead> - <tr> - <th colspan="2">Attributes</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>prefix</code></td> - <td> - <code>String, required</code> - <p>Global prefix used to fully quality all Go targets.</p> - <p> - In Go, imports are always fully qualified with a URL, eg. - <code>github.com/user/project</code>. Hence, a label <code>//foo:bar - </code> from within a Bazel workspace must be referred to as - <code>github.com/user/project/foo/bar</code>. To make this work, each - rule must know the repository's URL. This is achieved, by having all - go rules depend on a globally unique target that has a - <code>go_prefix</code> transitive info provider. - </p> - </td> - </tr> - </tbody> -</table> - -<a name="go_library"></a> -## go\_library - -```python -go_library(name, srcs, deps, data) -``` -<table class="table table-condensed table-bordered table-params"> - <colgroup> - <col class="col-param" /> - <col class="param-description" /> - </colgroup> - <thead> - <tr> - <th colspan="2">Attributes</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>name</code></td> - <td> - <code>Name, required</code> - <p>A unique name for this rule.</p> - </td> - </tr> - <tr> - <td><code>srcs</code></td> - <td> - <code>List of labels, required</code> - <p>List of Go <code>.go</code> source files used to build the - library</p> - </td> - </tr> - <tr> - <td><code>deps</code></td> - <td> - <code>List of labels, optional</code> - <p>List of other libraries to linked to this library target</p> - </td> - </tr> - <tr> - <td><code>data</code></td> - <td> - <code>List of labels, optional</code> - <p>List of files needed by this rule at runtime.</p> - </td> - </tr> - </tbody> -</table> - -<a name="go_binary"></a> -## go\_binary - -```python -go_binary(name, srcs, deps, data) -``` -<table class="table table-condensed table-bordered table-params"> - <colgroup> - <col class="col-param" /> - <col class="param-description" /> - </colgroup> - <thead> - <tr> - <th colspan="2">Attributes</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>name</code></td> - <td> - <code>Name, required</code> - <p>A unique name for this rule.</p> - </td> - </tr> - <tr> - <td><code>srcs</code></td> - <td> - <code>List of labels, required</code> - <p>List of Go <code>.go</code> source files used to build the - binary</p> - </td> - </tr> - <tr> - <td><code>deps</code></td> - <td> - <code>List of labels, optional</code> - <p>List of other libraries to linked to this binary target</p> - </td> - </tr> - <tr> - <td><code>data</code></td> - <td> - <code>List of labels, optional</code> - <p>List of files needed by this rule at runtime.</p> - </td> - </tr> - </tbody> -</table> - -<a name="go_test"></a> -## go\_test - -```python -go_test(name, srcs, deps, data) -``` -<table class="table table-condensed table-bordered table-params"> - <colgroup> - <col class="col-param" /> - <col class="param-description" /> - </colgroup> - <thead> - <tr> - <th colspan="2">Attributes</th> - </tr> - </thead> - <tbody> - <tr> - <td><code>name</code></td> - <td> - <code>Name, required</code> - <p>A unique name for this rule.</p> - </td> - </tr> - <tr> - <td><code>srcs</code></td> - <td> - <code>List of labels, required</code> - <p>List of Go <code>.go</code> source files used to build the - test</p> - </td> - </tr> - <tr> - <td><code>deps</code></td> - <td> - <code>List of labels, optional</code> - <p>List of other libraries to linked to this test target</p> - </td> - </tr> - <tr> - <td><code>data</code></td> - <td> - <code>List of labels, optional</code> - <p>List of files needed by this rule at runtime.</p> - </td> - </tr> - </tbody> -</table> diff --git a/tools/build_rules/go/def.bzl b/tools/build_rules/go/def.bzl deleted file mode 100644 index 0527d92bc3..0000000000 --- a/tools/build_rules/go/def.bzl +++ /dev/null @@ -1,431 +0,0 @@ -# Copyright 2014 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""These are bare-bones Go rules. - -In order of priority: - -- No support for build tags - -- BUILD file must be written by hand. - -- No C++ interop (SWIG, cgo). - -- No test sharding or test XML. - -""" - -load("//tools/build_rules:deprecation.bzl", "deprecated") - -def warning(rule): - print(deprecated( - "go", - rule, - "@bazel_tools//tools/build_rules/go:def.bzl", - "@io_bazel_rules_go//go:def.bzl")) - -_DEFAULT_LIB = "go_default_library" - -_VENDOR_PREFIX = "/vendor/" - -go_filetype = FileType([".go"]) - -################ - -# In Go, imports are always fully qualified with a URL, -# eg. github.com/user/project. Hence, a label //foo:bar from within a -# Bazel workspace must be referred to as -# "github.com/user/project/foo/bar". To make this work, each rule must -# know the repository's URL. This is achieved, by having all go rules -# depend on a globally unique target that has a "go_prefix" transitive -# info provider. - -def _go_prefix_impl(ctx): - """go_prefix_impl provides the go prefix to use as a transitive info provider.""" - return struct(go_prefix = ctx.attr.prefix) - -def _go_prefix(ctx): - """slash terminated go-prefix""" - warning("go_prefix") - prefix = ctx.attr.go_prefix.go_prefix - if prefix != "" and not prefix.endswith("/"): - prefix = prefix + "/" - return prefix - -_go_prefix_rule = rule( - _go_prefix_impl, - attrs = { - "prefix": attr.string(mandatory = True), - }, -) - -def go_prefix(prefix): - """go_prefix sets the Go import name to be used for this workspace.""" - _go_prefix_rule(name = "go_prefix", - prefix = prefix, - visibility = ["//visibility:public" ] - ) - -################ - -# TODO(bazel-team): it would be nice if Bazel had this built-in. -def symlink_tree_commands(dest_dir, artifact_dict): - """Symlink_tree_commands returns a list of commands to create the - dest_dir, and populate it according to the given dict. - - Args: - dest_dir: The destination directory, a string. - artifact_dict: The mapping of exec-path => path in the dest_dir. - - Returns: - A list of commands that will setup the symlink tree. - """ - cmds = [ - "rm -rf " + dest_dir, - "mkdir -p " + dest_dir, - ] - - for old_path, new_path in artifact_dict.items(): - new_dir = new_path[:new_path.rfind('/')] - up = (new_dir.count('/') + 1 + - dest_dir.count('/') + 1) - cmds += [ - "mkdir -p %s/%s" % (dest_dir, new_dir), - "ln -s %s%s %s/%s" % ('../' * up, old_path, dest_dir, new_path), - ] - return cmds - -def go_environment_vars(ctx): - """Return a map of environment variables for use with actions, based on - the arguments. Uses the ctx.fragments.cpp.cpu attribute, if present, - and picks a default of target_os="linux" and target_arch="amd64" - otherwise. - - Args: - The skylark Context. - - Returns: - A dict of environment variables for running Go tool commands that build for - the target OS and architecture. - """ - bazel_to_go_toolchain = {"k8": {"GOOS": "linux", - "GOARCH": "amd64"}, - "piii": {"GOOS": "linux", - "GOARCH": "386"}, - "darwin": {"GOOS": "darwin", - "GOARCH": "amd64"}, - "freebsd": {"GOOS": "freebsd", - "GOARCH": "amd64"}, - "armeabi-v7a": {"GOOS": "linux", - "GOARCH": "arm"}, - "arm": {"GOOS": "linux", - "GOARCH": "arm"}} - return bazel_to_go_toolchain.get(ctx.fragments.cpp.cpu, - {"GOOS": "linux", - "GOARCH": "amd64"}) - -def emit_go_compile_action(ctx, sources, deps, out_lib): - """Construct the command line for compiling Go code. - Constructs a symlink tree to accomodate for workspace name. - - Args: - ctx: The skylark Context. - sources: an iterable of source code artifacts (or CTs? or labels?) - deps: an iterable of dependencies. Each dependency d should have an - artifact in d.go_library_object representing an imported library. - out_lib: the artifact (configured target?) that should be produced - """ - config_strip = len(ctx.configuration.bin_dir.path) + 1 - - out_dir = out_lib.path + ".dir" - out_depth = out_dir.count('/') + 1 - tree_layout = {} - inputs = [] - prefix = _go_prefix(ctx) - import_map = {} - for d in deps: - library_artifact_path = d.go_library_object.path[config_strip:] - tree_layout[d.go_library_object.path] = prefix + library_artifact_path - inputs += [d.go_library_object] - - source_import = prefix + d.label.package + "/" + d.label.name - actual_import = prefix + d.label.package + "/" + d.label.name - if d.label.name == _DEFAULT_LIB: - source_import = prefix + d.label.package - - if source_import.rfind(_VENDOR_PREFIX) != -1: - source_import = source_import[len(_VENDOR_PREFIX) + source_import.rfind(_VENDOR_PREFIX):] - - if source_import != actual_import: - if source_import in import_map: - fail("duplicate import %s: adding %s and have %s" - % (source_import, actual_import, import_map[source_import])) - import_map[source_import] = actual_import - - inputs += list(sources) - for s in sources: - tree_layout[s.path] = prefix + s.path - - cmds = symlink_tree_commands(out_dir, tree_layout) - args = [ - "cd ", out_dir, "&&", - ('../' * out_depth) + ctx.file.go_tool.path, - "tool", "compile", - "-o", ('../' * out_depth) + out_lib.path, "-pack", - - # Import path. - "-I", "."] + [ - "-importmap=%s=%s" % (k,v) for k, v in import_map.items() - ] - - # Set -p to the import path of the library, ie. - # (ctx.label.package + "/" ctx.label.name) for now. - cmds += [ "export GOROOT=$(pwd)/" + ctx.file.go_tool.dirname + "/..", - ' '.join(args + cmd_helper.template(sources, prefix + "%{path}"))] - - ctx.action( - inputs = inputs + ctx.files.toolchain, - outputs = [out_lib], - mnemonic = "GoCompile", - command = " && ".join(cmds), - env = go_environment_vars(ctx)) - -def go_library_impl(ctx): - """Implements the go_library() rule.""" - warning("go_library") - - sources = set(ctx.files.srcs) - deps = ctx.attr.deps - if ctx.attr.library: - sources += ctx.attr.library.go_sources - deps += ctx.attr.library.direct_deps - - if not sources: - fail("may not be empty", "srcs") - - out_lib = ctx.outputs.lib - emit_go_compile_action(ctx, set(sources), deps, out_lib) - - transitive_libs = set([out_lib]) - for dep in ctx.attr.deps: - transitive_libs += dep.transitive_go_library_object - - runfiles = ctx.runfiles(collect_data = True) - return struct( - label = ctx.label, - files = set([out_lib]), - direct_deps = deps, - runfiles = runfiles, - go_sources = sources, - go_library_object = out_lib, - transitive_go_library_object = transitive_libs) - -def emit_go_link_action(ctx, transitive_libs, lib, executable): - """Sets up a symlink tree to libraries to link together.""" - out_dir = executable.path + ".dir" - out_depth = out_dir.count('/') + 1 - tree_layout = {} - - config_strip = len(ctx.configuration.bin_dir.path) + 1 - prefix = _go_prefix(ctx) - - for l in transitive_libs: - library_artifact_path = l.path[config_strip:] - tree_layout[l.path] = prefix + library_artifact_path - - tree_layout[lib.path] = prefix + lib.path[config_strip:] - tree_layout[executable.path] = prefix + executable.path[config_strip:] - - cmds = symlink_tree_commands(out_dir, tree_layout) - cmds += [ - "export GOROOT=$(pwd)/" + ctx.file.go_tool.dirname + "/..", - "cd " + out_dir, - ' '.join([ - ('../' * out_depth) + ctx.file.go_tool.path, - "tool", "link", "-L", ".", - "-o", prefix + executable.path[config_strip:], - prefix + lib.path[config_strip:]])] - - ctx.action( - inputs = list(transitive_libs) + [lib] + ctx.files.toolchain, - outputs = [executable], - command = ' && '.join(cmds), - mnemonic = "GoLink", - env = go_environment_vars(ctx)) - -def go_binary_impl(ctx): - """go_binary_impl emits actions for compiling and linking a go executable.""" - warning("go_binary") - lib_result = go_library_impl(ctx) - executable = ctx.outputs.executable - lib_out = ctx.outputs.lib - - emit_go_link_action( - ctx, lib_result.transitive_go_library_object, lib_out, executable) - - runfiles = ctx.runfiles(collect_data = True, - files = ctx.files.data) - return struct(files = set([executable]) + lib_result.files, - runfiles = runfiles) - -def go_test_impl(ctx): - """go_test_impl implements go testing. - - It emits an action to run the test generator, and then compiles the - test into a binary.""" - - warning("go_test") - - lib_result = go_library_impl(ctx) - main_go = ctx.outputs.main_go - prefix = _go_prefix(ctx) - - go_import = prefix + ctx.label.package + "/" + ctx.label.name - - args = (["--package", go_import, "--output", ctx.outputs.main_go.path] + - cmd_helper.template(lib_result.go_sources, "%{path}")) - - inputs = list(lib_result.go_sources) + list(ctx.files.toolchain) - ctx.action( - inputs = inputs, - executable = ctx.executable.test_generator, - outputs = [main_go], - mnemonic = "GoTestGenTest", - arguments = args, - env = dict(go_environment_vars(ctx), RUNDIR=ctx.label.package)) - - emit_go_compile_action( - ctx, set([main_go]), ctx.attr.deps + [lib_result], ctx.outputs.main_lib) - - emit_go_link_action( - ctx, lib_result.transitive_go_library_object, - ctx.outputs.main_lib, ctx.outputs.executable) - - # TODO(bazel-team): the Go tests should do a chdir to the directory - # holding the data files, so open-source go tests continue to work - # without code changes. - runfiles = ctx.runfiles(collect_data = True, - files = ctx.files.data + [ctx.outputs.executable]) - return struct(runfiles=runfiles) - -go_library_attrs = { - "data": attr.label_list( - allow_files = True, - cfg = DATA_CFG, - ), - "srcs": attr.label_list(allow_files = go_filetype), - "deps": attr.label_list( - providers = [ - "direct_deps", - "go_library_object", - "transitive_go_library_object", - ], - ), - "toolchain": attr.label( - default = Label("@bazel_tools//tools/build_rules/go/toolchain:toolchain"), - allow_files = True, - cfg = HOST_CFG, - ), - "go_tool": attr.label( - default = Label("@bazel_tools//tools/build_rules/go/toolchain:go_tool"), - single_file = True, - allow_files = True, - cfg = HOST_CFG, - ), - "library": attr.label( - providers = ["go_sources"], - ), - "go_prefix": attr.label( - providers = ["go_prefix"], - default = Label( - "//:go_prefix", - relative_to_caller_repository = True, - ), - allow_files = False, - cfg = HOST_CFG, - ), -} - -go_library_outputs = { - "lib": "%{name}.a", -} - -go_library = rule( - go_library_impl, - attrs = go_library_attrs, - fragments = ["cpp"], - outputs = go_library_outputs, -) - -go_binary = rule( - go_binary_impl, - attrs = go_library_attrs + { - "stamp": attr.bool(default = False), - }, - executable = True, - fragments = ["cpp"], - outputs = go_library_outputs, -) - -go_test = rule( - go_test_impl, - attrs = go_library_attrs + { - "test_generator": attr.label( - executable = True, - default = Label( - "@bazel_tools//tools/build_rules/go/tools:generate_test_main", - ), - cfg = HOST_CFG, - ), - }, - executable = True, - fragments = ["cpp"], - outputs = { - "lib": "%{name}.a", - "main_lib": "%{name}_main_test.a", - "main_go": "%{name}_main_test.go", - }, - test = True, -) - -GO_TOOLCHAIN_BUILD_FILE = """ -package( - default_visibility = [ "//visibility:public" ]) - -filegroup( - name = "toolchain", - srcs = glob(["go/bin/*", "go/pkg/**", ]), -) - -filegroup( - name = "go_tool", - srcs = [ "go/bin/go" ], -) -""" - -def go_repositories(): - warning("go_repositories") - native.new_http_archive( - name= "golang_linux_amd64", - url = "https://storage.googleapis.com/golang/go1.5.1.linux-amd64.tar.gz", - build_file_content = GO_TOOLCHAIN_BUILD_FILE, - sha256 = "2593132ca490b9ee17509d65ee2cd078441ff544899f6afb97a03d08c25524e7" - ) - - native.new_http_archive( - name= "golang_darwin_amd64", - url = "https://storage.googleapis.com/golang/go1.5.1.darwin-amd64.tar.gz", - build_file_content = GO_TOOLCHAIN_BUILD_FILE, - sha256 = "e94487b8cd2e0239f27dc51e6c6464383b10acb491f753584605e9b28abf48fb" - ) diff --git a/tools/build_rules/go/toolchain/BUILD b/tools/build_rules/go/toolchain/BUILD deleted file mode 100644 index c3afba9268..0000000000 --- a/tools/build_rules/go/toolchain/BUILD +++ /dev/null @@ -1,42 +0,0 @@ -package( - default_visibility = ["//src:__subpackages__"], -) - -config_setting( - name = "darwin", - values = {"host_cpu": "darwin"}, -) - -config_setting( - name = "k8", - values = {"host_cpu": "k8"}, -) - -filegroup( - name = "toolchain", - srcs = select({ - ":darwin": ["@golang_darwin_amd64//:toolchain"], - ":k8": ["@golang_linux_amd64//:toolchain"], - }), - visibility = ["//visibility:public"], -) - -filegroup( - name = "go_tool", - srcs = select({ - ":darwin": ["@golang_darwin_amd64//:go_tool"], - ":k8": ["@golang_linux_amd64//:go_tool"], - }), - visibility = ["//visibility:public"], -) - -filegroup( - name = "srcs", - srcs = [ - "BUILD", - ], - visibility = [ - "//src:__subpackages__", - "//tools/build_rules/go:__pkg__", - ], -) diff --git a/tools/build_rules/go/tools/BUILD b/tools/build_rules/go/tools/BUILD deleted file mode 100644 index 1dfa4c25c4..0000000000 --- a/tools/build_rules/go/tools/BUILD +++ /dev/null @@ -1,17 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("//tools/build_rules/go:def.bzl", "go_binary") - -# This binary is used implicitly by go_test(). -go_binary( - name = "generate_test_main", - srcs = ["generate_test_main.go"], -) - -filegroup( - name = "srcs", - srcs = [ - "BUILD", - "generate_test_main.go", - ], -) diff --git a/tools/build_rules/go/tools/filter_tags/BUILD b/tools/build_rules/go/tools/filter_tags/BUILD deleted file mode 100644 index d1dc3faaa9..0000000000 --- a/tools/build_rules/go/tools/filter_tags/BUILD +++ /dev/null @@ -1,19 +0,0 @@ -package(default_visibility = ["//visibility:public"]) - -load("//tools/build_rules/go:def.bzl", "go_prefix", "go_library", "go_binary", "go_test") - -go_library( - name = "filter_tags_lib", - srcs = ["filter_tags.go"], -) - -go_binary( - name = "filter_tags", - library = ":filter_tags_lib", -) - -go_test( - name = "filter_tags_test", - srcs = ["filter_tags_test.go"], - library = ":filter_tags_lib", -) diff --git a/tools/build_rules/go/tools/filter_tags/filter_tags.go b/tools/build_rules/go/tools/filter_tags/filter_tags.go deleted file mode 100644 index 44ca6bd0b9..0000000000 --- a/tools/build_rules/go/tools/filter_tags/filter_tags.go +++ /dev/null @@ -1,51 +0,0 @@ -package main - -import ( - "flag" - "fmt" - "go/build" - "log" - "path/filepath" - "strings" -) - -// Returns an array of strings containing only the filenames that should build -// according to the Context given. -func filterFilenames(bctx build.Context, inputs []string) ([]string, error) { - outputs := []string{} - - for _, filename := range inputs { - fullPath, err := filepath.Abs(filename) - if err != nil { - return nil, err - } - dir, base := filepath.Split(fullPath) - - matches, err := bctx.MatchFile(dir, base) - if err != nil { - return nil, err - } - - if matches { - outputs = append(outputs, filename) - } - } - return outputs, nil -} - -func main() { - cgo := flag.Bool("cgo", false, "Sets whether cgo-using files are allowed to pass the filter.") - tags := flag.String("tags", "", "Only pass through files that match these tags.") - flag.Parse() - - bctx := build.Default - bctx.BuildTags = strings.Split(*tags, ",") - bctx.CgoEnabled = *cgo // Worth setting? build.MatchFile ignores this. - - outputs, err := filterFilenames(bctx, flag.Args()) - if err != nil { - log.Fatalf("build_tags error: %v\n", err) - } - - fmt.Println(strings.Join(outputs, " ")) -} diff --git a/tools/build_rules/go/tools/filter_tags/filter_tags_test.go b/tools/build_rules/go/tools/filter_tags/filter_tags_test.go deleted file mode 100644 index 652d3af1d5..0000000000 --- a/tools/build_rules/go/tools/filter_tags/filter_tags_test.go +++ /dev/null @@ -1,119 +0,0 @@ -package main - -import ( - "go/build" - "io/ioutil" - "os" - "path/filepath" - "reflect" - "testing" -) - -var testFileCGO = ` -// This file is not intended to actually build. - -package cgo - -/* -#include <stdio.h> -#include <stdlib.h> - -void myprint(char* s) { - printf("%s", s); -} -*/ - -import "C" - -func main() { - C.myprint("hello") -} -` - -var testFileFILENAMETAG = ` -// This file is not intended to actually compile. - -package filenametag_darwin -` - -var testFileIGNORE = ` -// This file is not intended to actually build. - -//+build ignore - -package ignore -` - -var testFileTAGS = ` -// This file is not intended to actually build. - -//+build arm,darwin linux,mips - -package tags -` - -func TestTags(t *testing.T) { - tempdir, err := ioutil.TempDir("", "goruletest") - if err != nil { - t.Fatalf("Error creating temporary directory: %v", err) - } - defer os.RemoveAll(tempdir) - - for k, v := range map[string]string{ - "cgo.go": testFileCGO, - "darwin.go": testFileFILENAMETAG, - "ignore.go": testFileIGNORE, - "tags.go": testFileTAGS, - } { - p := filepath.Join(tempdir, k) - if err := ioutil.WriteFile(p, []byte(v), 0644); err != nil { - t.Fatalf("WriteFile(%s): %v", p, err) - } - } - - testContext := build.Default - wd, err := os.Getwd() - if err != nil { - t.Fatalf("Getwd: %v", err) - } - - err = os.Chdir(tempdir) - if err != nil { - t.Fatalf("Chdir(%s): %v", tempdir, err) - } - defer os.Chdir(wd) - - // Test tags.go (tags in +build comments) - testContext.BuildTags = []string{"arm", "darwin"} - inputs := []string{"tags.go"} - outputs, err := filterFilenames(testContext, inputs) - if err != nil { - t.Errorf("filterFilenames(%s): %v", inputs, err) - } - - if !reflect.DeepEqual(inputs, outputs) { - t.Error("Output missing an expected file: tags.go") - } - - testContext.BuildTags = []string{"arm, linux"} - outputs, err = filterFilenames(testContext, inputs) - if err != nil { - t.Errorf("filterFilenames(%s): %v", inputs, err) - } - - if !reflect.DeepEqual([]string{}, outputs) { - t.Error("Output contains an unexpected file: tags.go") - } - - // Test ignore.go (should not build a file with +ignore comment) - testContext.BuildTags = []string{} - inputs = []string{"ignore.go"} - outputs, err = filterFilenames(testContext, inputs) - if err != nil { - t.Errorf("filterFilenames(%s): %v", inputs, err) - } - - if !reflect.DeepEqual([]string{}, outputs) { - t.Error("Output contains an unexpected file: ignore.go") - } -} diff --git a/tools/build_rules/go/tools/generate_test_main.go b/tools/build_rules/go/tools/generate_test_main.go deleted file mode 100644 index b87022406d..0000000000 --- a/tools/build_rules/go/tools/generate_test_main.go +++ /dev/null @@ -1,95 +0,0 @@ -// Bare bones Go testing support for Bazel. - -package main - -import ( - "flag" - "go/ast" - "go/parser" - "go/token" - "log" - "os" - "strings" - "text/template" -) - -// Cases holds template data. -type Cases struct { - Package string - RunDir string - Names []string -} - -func main() { - pkg := flag.String("package", "", "package from which to import test methods.") - out := flag.String("output", "", "output file to write. Defaults to stdout.") - flag.Parse() - - if *pkg == "" { - log.Fatal("must set --package.") - } - - outFile := os.Stdout - if *out != "" { - var err error - outFile, err = os.Create(*out) - if err != nil { - log.Fatalf("os.Create(%q): %v", *out, err) - } - defer outFile.Close() - } - - cases := Cases{ - Package: *pkg, - RunDir: os.Getenv("RUNDIR"), - } - testFileSet := token.NewFileSet() - for _, f := range flag.Args() { - parse, err := parser.ParseFile(testFileSet, f, nil, parser.ParseComments) - if err != nil { - log.Fatalf("ParseFile(%q): %v", f, err) - } - - for _, d := range parse.Decls { - fn, ok := d.(*ast.FuncDecl) - if !ok { - continue - } - if fn.Recv != nil { - continue - } - if !strings.HasPrefix(fn.Name.Name, "Test") { - continue - } - cases.Names = append(cases.Names, fn.Name.Name) - } - } - - tpl := template.Must(template.New("source").Parse(` -package main -import ( - "os" - "testing" - - undertest "{{.Package}}" -) - -func everything(pat, str string) (bool, error) { - return true, nil -} - -var tests = []testing.InternalTest{ -{{range .Names}} - {"{{.}}", undertest.{{.}} }, -{{end}} -} - -func main() { - os.Chdir("{{.RunDir}}") - testing.Main(everything, tests, nil, nil) -} -`)) - if err := tpl.Execute(outFile, &cases); err != nil { - log.Fatalf("template.Execute(%v): %v", cases, err) - } -} |