aboutsummaryrefslogtreecommitdiff
path: root/extras/gomock.bzl
blob: 7e960eae70d0f499cc08a619d9af9468f8428a2f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
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