aboutsummaryrefslogtreecommitdiffhomepage
path: root/docs/macros.md
blob: 9b2e1adce30bf92d71043d34e4466fcfdcf109a7 (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
Macros
======

**Status: Stable**

Macro creation
--------------

A macro is a function called from the BUILD file. It can instantiate native
or Skylark rules. By the end of the loading phase, macros don't exist
anymore: Bazel sees only the set of rules they created.

Native rules can be instantiated from the `native` module, e.g.

```python
native.cc_library(name = x)
```

If you need to know the package name (i.e. which BUILD file is calling the
macro), use the constant `PACKAGE_NAME`.

Examples
--------

* [Macro creating native rules](cookbook.md#macro_native).

* [Macro creating Skylark rules](cookbook.md#macro_skylark).

Debugging
---------

* `bazel query --output=build ///my/path:all` will show you how the BUILD
file looks like after evaluation. All macros, globs, loops are expanded.

* You can also use `print` for debugging. It displays the message as a
warning during the loading phase. Except in rare cases, remove your `print`
calls before submitting the code to the depot.

Errors
------

If you want to throw an error, use the `fail` function. Explain clearly to
the user what went wrong and how to fix their BUILD file. It is not possible
to catch an error.

Conventions
-----------

* All public functions (functions that don't start with underscore) that
instantiate rules must have a `name` argument. This argument should not be
optional (don't give a default value).

* Public functions should use a docstring following [Python
  conventions](https://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Comments#Comments).

* In BUILD files, the `name` argument of the macros must a be a keyword
  argument (not a positional argument).

* The `name` attribute of rules generated by a macro should include the name
  argument as a prefix. For example, `macro(name = "foo")` can generate a
  cc_library `foo` and a genrule `foo_gen`.

* Macros should have an optional `visibility` argument.