Last active
October 22, 2020 23:54
-
-
Save ob/a427154d5583c79004fd807f4b579945 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Rules to run controller-gen | |
""" | |
load("@io_bazel_rules_go//go:def.bzl", "go_context", "go_path") | |
load("@io_bazel_rules_go//go/private:providers.bzl", "GoPath") | |
def _controller_gen_impl(ctx): | |
go_ctx = go_context(ctx) | |
gopath = "$(pwd)/" + ctx.bin_dir.path + "/" + ctx.attr.gopath_dep[GoPath].gopath | |
output = ctx.actions.declare_file("output.go") | |
inputs = (ctx.files.srcs + ctx.attr.gopath_dep.files.to_list() + | |
go_ctx.sdk.srcs + | |
go_ctx.sdk.tools + go_ctx.sdk.headers + go_ctx.stdlib.libs) | |
dirname = ctx.files.srcs[0].dirname | |
ctx.actions.run_shell( | |
outputs = [output], | |
inputs = inputs, | |
env = { | |
"GO111MODULE": "off", # explicitly relying on passed in go_path to not download modules while doing codegen | |
}, | |
command = """ | |
source <($PWD/{godir}/go env) && | |
export PATH=$GOROOT/bin:$PWD/{godir}:$PATH && | |
export GOPATH={gopath} && | |
mkdir -p .gocache && | |
export GOCACHE=$PWD/.gocache && | |
{cmd} {args} && | |
cp {dirname}/zz_generated.deepcopy.go {output} | |
""".format( | |
godir = go_ctx.go.path[:-1 - len(go_ctx.go.basename)], | |
gopath = gopath, | |
cmd = "$(pwd)/" + ctx.file._controller_gen.path, | |
args = "object paths=./{dirname}/...".format(dirname = dirname), | |
mnemonic = "GoControllerGen", | |
dirname = dirname, | |
output = output.path, | |
), | |
tools = [ | |
go_ctx.go, | |
ctx.file._controller_gen, | |
], | |
) | |
return DefaultInfo( | |
files = depset([output]), | |
) | |
_controller_gen = rule( | |
implementation = _controller_gen_impl, | |
attrs = { | |
"srcs": attr.label_list( | |
allow_empty = False, | |
allow_files = True, | |
mandatory = True, | |
), | |
"_controller_gen": attr.label( | |
allow_single_file = True, | |
default = "//:controller-gen", | |
executable = True, | |
cfg = "host", | |
), | |
"gopath_dep": attr.label( | |
providers = [GoPath], | |
mandatory = False, | |
), | |
"_go_context_data": attr.label( | |
default = "@io_bazel_rules_go//:go_context_data", | |
), | |
}, | |
toolchains = ["@io_bazel_rules_go//go:toolchain"], | |
) | |
def controller_gen(name, **kwargs): | |
if kwargs.get("deps", None): | |
gopath_name = name + "_controller_gen" | |
go_path( | |
name = gopath_name, | |
deps = kwargs["deps"], | |
) | |
_controller_gen( | |
name = name, | |
srcs = kwargs["srcs"], | |
gopath_dep = gopath_name, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment