aboutsummaryrefslogtreecommitdiff
path: root/extras
diff options
context:
space:
mode:
Diffstat (limited to 'extras')
-rw-r--r--extras/BUILD.bazel51
-rw-r--r--extras/bindata.bzl87
-rw-r--r--extras/embed_data.bzl146
-rw-r--r--extras/embed_data_deps.bzl35
-rw-r--r--extras/gomock.bzl386
-rw-r--r--extras/gomock/BUILD.bazel17
6 files changed, 722 insertions, 0 deletions
diff --git a/extras/BUILD.bazel b/extras/BUILD.bazel
new file mode 100644
index 00000000..9bdca7f8
--- /dev/null
+++ b/extras/BUILD.bazel
@@ -0,0 +1,51 @@
+load("@bazel_skylib//:bzl_library.bzl", "bzl_library")
+
+filegroup(
+ name = "all_rules",
+ srcs = glob(["*.bzl"]) + ["//go/private:all_rules"],
+ visibility = ["//visibility:public"],
+)
+
+filegroup(
+ name = "all_files",
+ testonly = True,
+ srcs = glob(["**"]),
+ visibility = ["//visibility:public"],
+)
+
+bzl_library(
+ name = "bindata",
+ srcs = ["bindata.bzl"],
+ visibility = ["//visibility:public"],
+ deps = ["@io_bazel_rules_go//go:def"],
+)
+
+bzl_library(
+ name = "embed_data",
+ srcs = ["embed_data.bzl"],
+ visibility = ["//visibility:public"],
+ deps = [
+ "//go/private:context",
+ "//go/private:go_toolchain",
+ ],
+)
+
+bzl_library(
+ name = "embed_data_deps",
+ srcs = ["embed_data_deps.bzl"],
+ visibility = ["//visibility:public"],
+ # Don't list dependency on @bazel_tools//tools/build_defs/repo.bzl
+ deps = [], # keep
+)
+
+bzl_library(
+ name = "gomock",
+ srcs = ["gomock.bzl"],
+ visibility = ["//visibility:public"],
+ deps = [
+ "//go/private:context",
+ "//go/private:go_toolchain",
+ "//go/private:providers",
+ "//go/private/rules:wrappers",
+ ],
+)
diff --git a/extras/bindata.bzl b/extras/bindata.bzl
new file mode 100644
index 00000000..40c119f9
--- /dev/null
+++ b/extras/bindata.bzl
@@ -0,0 +1,87 @@
+# Copyright 2018 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.
+
+"""bindata.bzl provides the bindata rule for embedding data in .go files"""
+
+load(
+ "//go:def.bzl",
+ "go_context",
+)
+load(
+ "//go/private:go_toolchain.bzl",
+ "GO_TOOLCHAIN",
+)
+
+def _bindata_impl(ctx):
+ print("Embedding is now better handled by using rules_go's built-in embedding functionality (https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/rules.md#go_library-embedsrcs). The `bindata` rule is deprecated and will be removed in rules_go version 0.39.")
+ go = go_context(ctx)
+ out = go.declare_file(go, ext = ".go")
+ arguments = ctx.actions.args()
+ arguments.add_all([
+ "-o",
+ out,
+ "-pkg",
+ ctx.attr.package,
+ "-prefix",
+ ctx.label.package,
+ ])
+ if not ctx.attr.compress:
+ arguments.add("-nocompress")
+ if not ctx.attr.metadata:
+ arguments.add("-nometadata")
+ if not ctx.attr.memcopy:
+ arguments.add("-nomemcopy")
+ if not ctx.attr.modtime:
+ arguments.add_all(["-modtime", "0"])
+ if ctx.attr.extra_args:
+ arguments.add_all(ctx.attr.extra_args)
+ srcs = [f.path for f in ctx.files.srcs]
+ if ctx.attr.strip_external and any([f.startswith("external/") for f in srcs]):
+ arguments.add("-prefix", ctx.label.workspace_root + "/" + ctx.label.package)
+ arguments.add_all(srcs)
+ ctx.actions.run(
+ inputs = ctx.files.srcs,
+ outputs = [out],
+ mnemonic = "GoBindata",
+ executable = ctx.executable._bindata,
+ arguments = [arguments],
+ )
+ return [
+ DefaultInfo(
+ files = depset([out]),
+ ),
+ ]
+
+bindata = rule(
+ implementation = _bindata_impl,
+ attrs = {
+ "srcs": attr.label_list(allow_files = True),
+ "package": attr.string(mandatory = True),
+ "compress": attr.bool(default = True),
+ "metadata": attr.bool(default = False),
+ "memcopy": attr.bool(default = True),
+ "modtime": attr.bool(default = False),
+ "strip_external": attr.bool(default = False),
+ "extra_args": attr.string_list(),
+ "_bindata": attr.label(
+ executable = True,
+ cfg = "exec",
+ default = "@com_github_kevinburke_go_bindata//go-bindata:go-bindata",
+ ),
+ "_go_context_data": attr.label(
+ default = "//:go_context_data",
+ ),
+ },
+ toolchains = [GO_TOOLCHAIN],
+)
diff --git a/extras/embed_data.bzl b/extras/embed_data.bzl
new file mode 100644
index 00000000..fb3519e2
--- /dev/null
+++ b/extras/embed_data.bzl
@@ -0,0 +1,146 @@
+# Copyright 2017 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.
+
+load(
+ "//go/private:context.bzl", #TODO: This ought to be def
+ "go_context",
+)
+load(
+ "//go/private:go_toolchain.bzl",
+ "GO_TOOLCHAIN",
+)
+
+_DOC = """**Deprecated**: Will be removed in rules_go 0.39.
+
+`go_embed_data` generates a .go file that contains data from a file or a
+list of files. It should be consumed in the srcs list of one of the
+[core go rules].
+
+Before using `go_embed_data`, you must add the following snippet to your
+WORKSPACE:
+
+``` bzl
+load("@io_bazel_rules_go//extras:embed_data_deps.bzl", "go_embed_data_dependencies")
+
+go_embed_data_dependencies()
+```
+
+`go_embed_data` accepts the attributes listed below.
+"""
+
+def _go_embed_data_impl(ctx):
+ print("Embedding is now better handled by using rules_go's built-in embedding functionality (https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/rules.md#go_library-embedsrcs). The `go_embed_data` rule is deprecated and will be removed in rules_go version 0.39.")
+
+ go = go_context(ctx)
+ if ctx.attr.src and ctx.attr.srcs:
+ fail("%s: src and srcs attributes cannot both be specified" % ctx.label)
+ if ctx.attr.src and ctx.attr.flatten:
+ fail("%s: src and flatten attributes cannot both be specified" % ctx.label)
+
+ args = ctx.actions.args()
+ if ctx.attr.src:
+ srcs = [ctx.file.src]
+ else:
+ srcs = ctx.files.srcs
+ args.add("-multi")
+
+ if ctx.attr.package:
+ package = ctx.attr.package
+ else:
+ _, _, package = ctx.label.package.rpartition("/")
+ if package == "":
+ fail("%s: must provide package attribute for go_embed_data rules in the repository root directory" % ctx.label)
+
+ out = go.declare_file(go, ext = ".go")
+ args.add_all([
+ "-workspace",
+ ctx.workspace_name,
+ "-label",
+ str(ctx.label),
+ "-out",
+ out,
+ "-package",
+ package,
+ "-var",
+ ctx.attr.var,
+ ])
+ if ctx.attr.flatten:
+ args.add("-flatten")
+ if ctx.attr.string:
+ args.add("-string")
+ if ctx.attr.unpack:
+ args.add("-unpack")
+ args.add("-multi")
+ args.add_all(srcs)
+
+ library = go.new_library(go, srcs = [out])
+ source = go.library_to_source(go, {}, library, ctx.coverage_instrumented())
+
+ ctx.actions.run(
+ outputs = [out],
+ inputs = srcs,
+ executable = ctx.executable._embed,
+ arguments = [args],
+ mnemonic = "GoSourcesData",
+ )
+ return [
+ DefaultInfo(files = depset([out])),
+ library,
+ source,
+ ]
+
+go_embed_data = rule(
+ implementation = _go_embed_data_impl,
+ doc = _DOC,
+ attrs = {
+ "package": attr.string(
+ doc = "Go package name for the generated .go file.",
+ ),
+ "var": attr.string(
+ default = "Data",
+ doc = "Name of the variable that will contain the embedded data.",
+ ),
+ "src": attr.label(
+ allow_single_file = True,
+ doc = """A single file to embed. This cannot be used at the same time as `srcs`.
+ The generated file will have a variable of type `[]byte` or `string` with the contents of this file.""",
+ ),
+ "srcs": attr.label_list(
+ allow_files = True,
+ doc = """A list of files to embed. This cannot be used at the same time as `src`.
+ The generated file will have a variable of type `map[string][]byte` or `map[string]string` with the contents
+ of each file. The map keys are relative paths of the files from the repository root. Keys for files in external
+ repositories will be prefixed with `"external/repo/"` where "repo" is the name of the external repository.""",
+ ),
+ "flatten": attr.bool(
+ doc = "If `True` and `srcs` is used, map keys are file base names instead of relative paths.",
+ ),
+ "unpack": attr.bool(
+ doc = "If `True`, sources are treated as archives and their contents will be stored. Supported formats are `.zip` and `.tar`",
+ ),
+ "string": attr.bool(
+ doc = "If `True`, the embedded data will be stored as `string` instead of `[]byte`.",
+ ),
+ "_embed": attr.label(
+ default = "//go/tools/builders:embed",
+ executable = True,
+ cfg = "exec",
+ ),
+ "_go_context_data": attr.label(
+ default = "//:go_context_data",
+ ),
+ },
+ toolchains = [GO_TOOLCHAIN],
+)
+# See /docs/go/extras/extras.md#go_embed_data for full documentation.
diff --git a/extras/embed_data_deps.bzl b/extras/embed_data_deps.bzl
new file mode 100644
index 00000000..1e2d6e88
--- /dev/null
+++ b/extras/embed_data_deps.bzl
@@ -0,0 +1,35 @@
+# Copyright 2019 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.
+
+"""Repository dependencies for embed_data.bzl"""
+
+load(
+ "@bazel_tools//tools/build_defs/repo:git.bzl",
+ "git_repository",
+)
+
+def go_embed_data_dependencies():
+ print("Embedding is now better handled by using rules_go's built-in embedding functionality (https://github.com/bazelbuild/rules_go/blob/master/docs/go/core/rules.md#go_library-embedsrcs). The `go_embed_data_dependencies` macro is deprecated and will be removed in rules_go version 0.39.")
+
+ if "com_github_kevinburke_go_bindata" not in native.existing_rules():
+ git_repository(
+ name = "com_github_kevinburke_go_bindata",
+ remote = "https://github.com/kevinburke/go-bindata",
+ # v3.13.0+incompatible, "latest" as of 2019-07-08
+ commit = "53d73b98acf3bd9f56d7f9136ed8e1be64756e1d",
+ patches = [Label("//third_party:com_github_kevinburke_go_bindata-gazelle.patch")],
+ patch_args = ["-p1"],
+ shallow_since = "1545009224 +0000",
+ # gazelle args: -go_prefix github.com/kevinburke/go-bindata
+ )
diff --git a/extras/gomock.bzl b/extras/gomock.bzl
new file mode 100644
index 00000000..7e960eae
--- /dev/null
+++ b/extras/gomock.bzl
@@ -0,0 +1,386 @@
+# The MIT License (MIT)
+# Copyright © 2018 Jeff Hodges <jeff@somethingsimilar.com>
+
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the “Software”), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+
+# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+
+# The rules in this files are still under development. Breaking changes are planned.
+# DO NOT USE IT.
+
+load("//go/private:context.bzl", "go_context")
+load("//go/private:go_toolchain.bzl", "GO_TOOLCHAIN")
+load("//go/private/rules:wrappers.bzl", go_binary = "go_binary_macro")
+load("//go/private:providers.bzl", "GoLibrary")
+load("@bazel_skylib//lib:paths.bzl", "paths")
+
+_MOCKGEN_TOOL = Label("//extras/gomock:mockgen")
+_MOCKGEN_MODEL_LIB = Label("//extras/gomock:mockgen_model")
+
+def _gomock_source_impl(ctx):
+ go_ctx = go_context(ctx)
+
+ # create GOPATH and copy source into GOPATH
+ source_relative_path = paths.join("src", ctx.attr.library[GoLibrary].importmap, ctx.file.source.basename)
+ source = ctx.actions.declare_file(paths.join("gopath", source_relative_path))
+
+ # trim the relative path of source to get GOPATH
+ gopath = source.path[:-len(source_relative_path)]
+ ctx.actions.run_shell(
+ outputs = [source],
+ inputs = [ctx.file.source],
+ command = "mkdir -p {0} && cp -L {1} {0}".format(source.dirname, ctx.file.source.path),
+ )
+
+ # passed in source needs to be in gopath to not trigger module mode
+ args = ["-source", source.path]
+
+ args, needed_files = _handle_shared_args(ctx, args)
+
+ if len(ctx.attr.aux_files) > 0:
+ aux_files = []
+ for target, pkg in ctx.attr.aux_files.items():
+ f = target.files.to_list()[0]
+ aux = ctx.actions.declare_file(paths.join(gopath, "src", pkg, f.basename))
+ ctx.actions.run_shell(
+ outputs = [aux],
+ inputs = [f],
+ command = "mkdir -p {0} && cp -L {1} {0}".format(aux.dirname, f.path),
+ )
+ aux_files.append("{0}={1}".format(pkg, aux.path))
+ needed_files.append(f)
+ args += ["-aux_files", ",".join(aux_files)]
+
+ inputs = (
+ needed_files +
+ go_ctx.sdk.headers + go_ctx.sdk.srcs + go_ctx.sdk.tools
+ ) + [source]
+
+ # We can use the go binary from the stdlib for most of the environment
+ # variables, but our GOPATH is specific to the library target we were given.
+ ctx.actions.run_shell(
+ outputs = [ctx.outputs.out],
+ inputs = inputs,
+ tools = [
+ ctx.file.mockgen_tool,
+ go_ctx.go,
+ ],
+ command = """
+ export GOPATH=$(pwd)/{gopath} &&
+ {cmd} {args} > {out}
+ """.format(
+ gopath = gopath,
+ cmd = "$(pwd)/" + ctx.file.mockgen_tool.path,
+ args = " ".join(args),
+ out = ctx.outputs.out.path,
+ mnemonic = "GoMockSourceGen",
+ ),
+ env = {
+ # GOCACHE is required starting in Go 1.12
+ "GOCACHE": "./.gocache",
+ },
+ )
+
+_gomock_source = rule(
+ _gomock_source_impl,
+ attrs = {
+ "library": attr.label(
+ doc = "The target the Go library where this source file belongs",
+ providers = [GoLibrary],
+ mandatory = True,
+ ),
+ "source": attr.label(
+ doc = "A Go source file to find all the interfaces to generate mocks for. See also the docs for library.",
+ mandatory = False,
+ allow_single_file = True,
+ ),
+ "out": attr.output(
+ doc = "The new Go file to emit the generated mocks into",
+ mandatory = True,
+ ),
+ "aux_files": attr.label_keyed_string_dict(
+ default = {},
+ doc = "A map from auxilliary Go source files to their packages.",
+ allow_files = True,
+ ),
+ "package": attr.string(
+ doc = "The name of the package the generated mocks should be in. If not specified, uses mockgen's default.",
+ ),
+ "self_package": attr.string(
+ doc = "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.",
+ ),
+ "imports": attr.string_dict(
+ doc = "Dictionary of name-path pairs of explicit imports to use.",
+ ),
+ "mock_names": attr.string_dict(
+ doc = "Dictionary of interface name to mock name pairs to change the output names of the mock objects. Mock names default to 'Mock' prepended to the name of the interface.",
+ default = {},
+ ),
+ "copyright_file": attr.label(
+ doc = "Optional file containing copyright to prepend to the generated contents.",
+ allow_single_file = True,
+ mandatory = False,
+ ),
+ "mockgen_tool": attr.label(
+ doc = "The mockgen tool to run",
+ default = _MOCKGEN_TOOL,
+ allow_single_file = True,
+ executable = True,
+ cfg = "exec",
+ mandatory = False,
+ ),
+ "_go_context_data": attr.label(
+ default = "//:go_context_data",
+ ),
+ },
+ toolchains = [GO_TOOLCHAIN],
+)
+
+def gomock(name, library, out, source = None, interfaces = [], package = "", self_package = "", aux_files = {}, mockgen_tool = _MOCKGEN_TOOL, imports = {}, copyright_file = None, mock_names = {}, **kwargs):
+ """Calls [mockgen](https://github.com/golang/mock) to generates a Go file containing mocks from the given library.
+
+ If `source` is given, the mocks are generated in source mode; otherwise in reflective mode.
+
+ Args:
+ name: the target name.
+ library: the Go library to took for the interfaces (reflecitve mode) or source (source mode).
+ out: the output Go file name.
+ source: a Go file in the given `library`. If this is given, `gomock` will call mockgen in source mode to mock all interfaces in the file.
+ interfaces: a list of interfaces in the given `library` to be mocked in reflective mode.
+ package: the name of the package the generated mocks should be in. If not specified, uses mockgen's default. See [mockgen's -package](https://github.com/golang/mock#flags) for more information.
+ self_package: the full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. See [mockgen's -self_package](https://github.com/golang/mock#flags) for more information.
+ aux_files: a map from source files to their package path. This only needed when `source` is provided. See [mockgen's -aux_files](https://github.com/golang/mock#flags) for more information.
+ mockgen_tool: the mockgen tool to run.
+ imports: dictionary of name-path pairs of explicit imports to use. See [mockgen's -imports](https://github.com/golang/mock#flags) for more information.
+ copyright_file: optional file containing copyright to prepend to the generated contents. See [mockgen's -copyright_file](https://github.com/golang/mock#flags) for more information.
+ mock_names: dictionary of interface name to mock name pairs to change the output names of the mock objects. Mock names default to 'Mock' prepended to the name of the interface. See [mockgen's -mock_names](https://github.com/golang/mock#flags) for more information.
+ kwargs: common attributes](https://bazel.build/reference/be/common-definitions#common-attributes) to all Bazel rules.
+ """
+ if source:
+ _gomock_source(
+ name = name,
+ library = library,
+ out = out,
+ source = source,
+ package = package,
+ self_package = self_package,
+ aux_files = aux_files,
+ mockgen_tool = mockgen_tool,
+ imports = imports,
+ copyright_file = copyright_file,
+ mock_names = mock_names,
+ **kwargs
+ )
+ else:
+ _gomock_reflect(
+ name = name,
+ library = library,
+ out = out,
+ interfaces = interfaces,
+ package = package,
+ self_package = self_package,
+ mockgen_tool = mockgen_tool,
+ imports = imports,
+ copyright_file = copyright_file,
+ mock_names = mock_names,
+ **kwargs
+ )
+
+def _gomock_reflect(name, library, out, mockgen_tool, **kwargs):
+ interfaces = kwargs.pop("interfaces", None)
+
+ mockgen_model_lib = _MOCKGEN_MODEL_LIB
+ if kwargs.get("mockgen_model_library", None):
+ mockgen_model_lib = kwargs["mockgen_model_library"]
+
+ prog_src = name + "_gomock_prog"
+ prog_src_out = prog_src + ".go"
+ _gomock_prog_gen(
+ name = prog_src,
+ interfaces = interfaces,
+ library = library,
+ out = prog_src_out,
+ mockgen_tool = mockgen_tool,
+ )
+ prog_bin = name + "_gomock_prog_bin"
+ go_binary(
+ name = prog_bin,
+ srcs = [prog_src_out],
+ deps = [library, mockgen_model_lib],
+ )
+ _gomock_prog_exec(
+ name = name,
+ interfaces = interfaces,
+ library = library,
+ out = out,
+ prog_bin = prog_bin,
+ mockgen_tool = mockgen_tool,
+ **kwargs
+ )
+
+def _gomock_prog_gen_impl(ctx):
+ args = ["-prog_only"]
+ args.append(ctx.attr.library[GoLibrary].importpath)
+ args.append(",".join(ctx.attr.interfaces))
+
+ cmd = ctx.file.mockgen_tool
+ out = ctx.outputs.out
+ ctx.actions.run_shell(
+ outputs = [out],
+ tools = [cmd],
+ command = """
+ {cmd} {args} > {out}
+ """.format(
+ cmd = "$(pwd)/" + cmd.path,
+ args = " ".join(args),
+ out = out.path,
+ ),
+ mnemonic = "GoMockReflectProgOnlyGen",
+ )
+
+_gomock_prog_gen = rule(
+ _gomock_prog_gen_impl,
+ attrs = {
+ "library": attr.label(
+ doc = "The target the Go library is at to look for the interfaces in. When this is set and source is not set, mockgen will use its reflect code to generate the mocks. If source is set, its dependencies will be included in the GOPATH that mockgen will be run in.",
+ providers = [GoLibrary],
+ mandatory = True,
+ ),
+ "out": attr.output(
+ doc = "The new Go source file put the mock generator code",
+ mandatory = True,
+ ),
+ "interfaces": attr.string_list(
+ allow_empty = False,
+ doc = "The names of the Go interfaces to generate mocks for. If not set, all of the interfaces in the library or source file will have mocks generated for them.",
+ mandatory = True,
+ ),
+ "mockgen_tool": attr.label(
+ doc = "The mockgen tool to run",
+ default = _MOCKGEN_TOOL,
+ allow_single_file = True,
+ executable = True,
+ cfg = "exec",
+ mandatory = False,
+ ),
+ "_go_context_data": attr.label(
+ default = "//:go_context_data",
+ ),
+ },
+ toolchains = [GO_TOOLCHAIN],
+)
+
+def _gomock_prog_exec_impl(ctx):
+ args = ["-exec_only", ctx.file.prog_bin.path]
+ args, needed_files = _handle_shared_args(ctx, args)
+
+ # annoyingly, the interfaces join has to go after the importpath so we can't
+ # share those.
+ args.append(ctx.attr.library[GoLibrary].importpath)
+ args.append(",".join(ctx.attr.interfaces))
+
+ ctx.actions.run_shell(
+ outputs = [ctx.outputs.out],
+ inputs = [ctx.file.prog_bin] + needed_files,
+ tools = [ctx.file.mockgen_tool],
+ command = """{cmd} {args} > {out}""".format(
+ cmd = "$(pwd)/" + ctx.file.mockgen_tool.path,
+ args = " ".join(args),
+ out = ctx.outputs.out.path,
+ ),
+ env = {
+ # GOCACHE is required starting in Go 1.12
+ "GOCACHE": "./.gocache",
+ },
+ mnemonic = "GoMockReflectExecOnlyGen",
+ )
+
+_gomock_prog_exec = rule(
+ _gomock_prog_exec_impl,
+ attrs = {
+ "library": attr.label(
+ doc = "The target the Go library is at to look for the interfaces in. When this is set and source is not set, mockgen will use its reflect code to generate the mocks. If source is set, its dependencies will be included in the GOPATH that mockgen will be run in.",
+ providers = [GoLibrary],
+ mandatory = True,
+ ),
+ "out": attr.output(
+ doc = "The new Go source file to put the generated mock code",
+ mandatory = True,
+ ),
+ "interfaces": attr.string_list(
+ allow_empty = False,
+ doc = "The names of the Go interfaces to generate mocks for. If not set, all of the interfaces in the library or source file will have mocks generated for them.",
+ mandatory = True,
+ ),
+ "package": attr.string(
+ doc = "The name of the package the generated mocks should be in. If not specified, uses mockgen's default.",
+ ),
+ "self_package": attr.string(
+ doc = "The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.",
+ ),
+ "imports": attr.string_dict(
+ doc = "Dictionary of name-path pairs of explicit imports to use.",
+ ),
+ "mock_names": attr.string_dict(
+ doc = "Dictionary of interfaceName-mockName pairs of explicit mock names to use. Mock names default to 'Mock'+ interfaceName suffix.",
+ default = {},
+ ),
+ "copyright_file": attr.label(
+ doc = "Optional file containing copyright to prepend to the generated contents.",
+ allow_single_file = True,
+ mandatory = False,
+ ),
+ "prog_bin": attr.label(
+ doc = "The program binary generated by mockgen's -prog_only and compiled by bazel.",
+ allow_single_file = True,
+ executable = True,
+ cfg = "exec",
+ mandatory = True,
+ ),
+ "mockgen_tool": attr.label(
+ doc = "The mockgen tool to run",
+ default = _MOCKGEN_TOOL,
+ allow_single_file = True,
+ executable = True,
+ cfg = "exec",
+ mandatory = False,
+ ),
+ "_go_context_data": attr.label(
+ default = "//:go_context_data",
+ ),
+ },
+ toolchains = [GO_TOOLCHAIN],
+)
+
+def _handle_shared_args(ctx, args):
+ needed_files = []
+
+ if ctx.attr.package != "":
+ args += ["-package", ctx.attr.package]
+ if ctx.attr.self_package != "":
+ args += ["-self_package", ctx.attr.self_package]
+ if len(ctx.attr.imports) > 0:
+ imports = ",".join(["{0}={1}".format(name, pkg) for name, pkg in ctx.attr.imports.items()])
+ args += ["-imports", imports]
+ if ctx.file.copyright_file != None:
+ args += ["-copyright_file", ctx.file.copyright_file.path]
+ needed_files.append(ctx.file.copyright_file)
+ if len(ctx.attr.mock_names) > 0:
+ mock_names = ",".join(["{0}={1}".format(name, pkg) for name, pkg in ctx.attr.mock_names.items()])
+ args += ["-mock_names", mock_names]
+
+ return args, needed_files
diff --git a/extras/gomock/BUILD.bazel b/extras/gomock/BUILD.bazel
new file mode 100644
index 00000000..5eb1e087
--- /dev/null
+++ b/extras/gomock/BUILD.bazel
@@ -0,0 +1,17 @@
+alias(
+ name = "gomock",
+ actual = "@com_github_golang_mock//gomock",
+ visibility = ["//visibility:public"],
+)
+
+alias(
+ name = "mockgen",
+ actual = "@com_github_golang_mock//mockgen",
+ visibility = ["//visibility:public"],
+)
+
+alias(
+ name = "mockgen_model",
+ actual = "@com_github_golang_mock//mockgen/model",
+ visibility = ["//visibility:public"],
+)