...
1"""Defines rules for starting a process in the workspace root.
2
3This technique was inspired by the gazelle rule implementation in bazelbuild/rules_go:
4https://github.com/bazelbuild/rules_go/blob/86ade29284ca11deeead86c061e9ba9bd0d157e0/go/private/tools/gazelle.bzl
5
6Forked from https://github.com/kubernetes/repo-infra/blob/master/defs/run_in_workspace.bzl to avoid
7bringing in the entire kubernetes/repo-infra repository
8"""
9
10def _workspace_binary_script_impl(ctx):
11 content = """#!/usr/bin/env bash
12set -o errexit
13set -o nounset
14set -o pipefail
15
16if [[ -n "${{BUILD_WORKSPACE_DIRECTORY:-}}" ]]; then
17 # Running from inside bazel
18 cd "${{BUILD_WORKSPACE_DIRECTORY}}"
19else
20 # Running from bazel-bin
21 cd "$(git rev-parse --show-toplevel)"
22fi
23# bazel-repo-infra will handle both external and local binaries, aka
24# bazel-repo-infra/external/go_sdk/bin/go
25# bazel-repo-infra/bazel-out/k8-fastbuild/bin/cmd/kazel/linux_amd64_stripped/kazel
26"bazel-${{PWD##*/}}/{cmd}" "$@"
27""".format(
28 cmd = ctx.file.cmd.path,
29 )
30 ctx.actions.write(
31 output = ctx.outputs.executable,
32 content = content,
33 is_executable = True,
34 )
35 runfiles = ctx.runfiles(
36 files = [
37 ctx.file.cmd,
38 ],
39 )
40 return [DefaultInfo(runfiles = runfiles)]
41
42_workspace_binary_script = rule(
43 attrs = {
44 "cmd": attr.label(
45 mandatory = True,
46 allow_single_file = True,
47 ),
48 },
49 executable = True,
50 implementation = _workspace_binary_script_impl,
51)
52
53def workspace_binary(
54 name,
55 cmd,
56 args = None,
57 visibility = None):
58 """Wraps a binary to be run in the workspace root via bazel run.
59
60 For example, one might do something like
61
62 workspace_binary(
63 name = "dep",
64 cmd = "//vendor/github.com/golang/dep/cmd/dep",
65 )
66 which would allow running dep with bazel run.
67 """
68 script_name = name + "_script"
69 _workspace_binary_script(
70 name = script_name,
71 cmd = cmd,
72 tags = ["manual"],
73 )
74 native.sh_binary(
75 name = name,
76 srcs = [":" + script_name],
77 args = args,
78 visibility = visibility,
79 tags = ["manual"],
80 )
View as plain text