• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2018 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#    http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Public API for for building wheels."""
16
17load("//python/private:py_package.bzl", "py_package_lib")
18load("//python/private:py_wheel.bzl", _PyWheelInfo = "PyWheelInfo", _py_wheel = "py_wheel")
19load("//python/private:util.bzl", "copy_propagating_kwargs")
20
21# Re-export as public API
22PyWheelInfo = _PyWheelInfo
23
24py_package = rule(
25    implementation = py_package_lib.implementation,
26    doc = """\
27A rule to select all files in transitive dependencies of deps which
28belong to given set of Python packages.
29
30This rule is intended to be used as data dependency to py_wheel rule.
31""",
32    attrs = py_package_lib.attrs,
33)
34
35# Based on https://github.com/aspect-build/bazel-lib/tree/main/lib/private/copy_to_directory.bzl
36# Avoiding a bazelbuild -> aspect-build dependency :(
37def _py_wheel_dist_impl(ctx):
38    dir = ctx.actions.declare_directory(ctx.attr.out)
39    name_file = ctx.attr.wheel[PyWheelInfo].name_file
40    cmds = [
41        "mkdir -p \"%s\"" % dir.path,
42        """cp "{}" "{}/$(cat "{}")" """.format(ctx.files.wheel[0].path, dir.path, name_file.path),
43    ]
44    ctx.actions.run_shell(
45        inputs = ctx.files.wheel + [name_file],
46        outputs = [dir],
47        command = "\n".join(cmds),
48        mnemonic = "CopyToDirectory",
49        progress_message = "Copying files to directory",
50        use_default_shell_env = True,
51    )
52    return [
53        DefaultInfo(files = depset([dir]), runfiles = ctx.runfiles([dir])),
54    ]
55
56py_wheel_dist = rule(
57    doc = """\
58Prepare a dist/ folder, following Python's packaging standard practice.
59
60See https://packaging.python.org/en/latest/tutorials/packaging-projects/#generating-distribution-archives
61which recommends a dist/ folder containing the wheel file(s), source distributions, etc.
62
63This also has the advantage that stamping information is included in the wheel's filename.
64""",
65    implementation = _py_wheel_dist_impl,
66    attrs = {
67        "out": attr.string(doc = "name of the resulting directory", mandatory = True),
68        "wheel": attr.label(doc = "a [py_wheel rule](/docs/packaging.md#py_wheel_rule)", providers = [PyWheelInfo]),
69    },
70)
71
72def py_wheel(name, twine = None, publish_args = [], **kwargs):
73    """Builds a Python Wheel.
74
75    Wheels are Python distribution format defined in https://www.python.org/dev/peps/pep-0427/.
76
77    This macro packages a set of targets into a single wheel.
78    It wraps the [py_wheel rule](#py_wheel_rule).
79
80    Currently only pure-python wheels are supported.
81
82    Examples:
83
84    ```python
85    # Package some specific py_library targets, without their dependencies
86    py_wheel(
87        name = "minimal_with_py_library",
88        # Package data. We're building "example_minimal_library-0.0.1-py3-none-any.whl"
89        distribution = "example_minimal_library",
90        python_tag = "py3",
91        version = "0.0.1",
92        deps = [
93            "//examples/wheel/lib:module_with_data",
94            "//examples/wheel/lib:simple_module",
95        ],
96    )
97
98    # Use py_package to collect all transitive dependencies of a target,
99    # selecting just the files within a specific python package.
100    py_package(
101        name = "example_pkg",
102        # Only include these Python packages.
103        packages = ["examples.wheel"],
104        deps = [":main"],
105    )
106
107    py_wheel(
108        name = "minimal_with_py_package",
109        # Package data. We're building "example_minimal_package-0.0.1-py3-none-any.whl"
110        distribution = "example_minimal_package",
111        python_tag = "py3",
112        version = "0.0.1",
113        deps = [":example_pkg"],
114    )
115    ```
116
117    To publish the wheel to Pypi, the twine package is required.
118    rules_python doesn't provide twine itself, see https://github.com/bazelbuild/rules_python/issues/1016
119    However you can install it with pip_parse, just like we do in the WORKSPACE file in rules_python.
120
121    Once you've installed twine, you can pass its label to the `twine` attribute of this macro,
122    to get a "[name].publish" target.
123
124    Example:
125
126    ```python
127    py_wheel(
128        name = "my_wheel",
129        twine = "@publish_deps_twine//:pkg",
130        ...
131    )
132    ```
133
134    Now you can run a command like the following, which publishes to https://test.pypi.org/
135
136    ```sh
137    % TWINE_USERNAME=__token__ TWINE_PASSWORD=pypi-*** \\
138        bazel run --stamp --embed_label=1.2.4 -- \\
139        //path/to:my_wheel.publish --repository testpypi
140    ```
141
142    Args:
143        name:  A unique name for this target.
144        twine: A label of the external location of the py_library target for twine
145        publish_args: arguments passed to twine, e.g. ["--repository-url", "https://pypi.my.org/simple/"].
146            These are subject to make var expansion, as with the `args` attribute.
147            Note that you can also pass additional args to the bazel run command as in the example above.
148        **kwargs: other named parameters passed to the underlying [py_wheel rule](#py_wheel_rule)
149    """
150    _dist_target = "{}.dist".format(name)
151    py_wheel_dist(
152        name = _dist_target,
153        wheel = name,
154        out = kwargs.pop("dist_folder", "{}_dist".format(name)),
155        **copy_propagating_kwargs(kwargs)
156    )
157
158    _py_wheel(name = name, **kwargs)
159
160    if twine:
161        if not twine.endswith(":pkg"):
162            fail("twine label should look like @my_twine_repo//:pkg")
163        twine_main = twine.replace(":pkg", ":rules_python_wheel_entry_point_twine.py")
164        twine_args = ["upload"]
165        twine_args.extend(publish_args)
166        twine_args.append("$(rootpath :{})/*".format(_dist_target))
167
168        # TODO: use py_binary from //python:defs.bzl after our stardoc setup is less brittle
169        # buildifier: disable=native-py
170        native.py_binary(
171            name = "{}.publish".format(name),
172            srcs = [twine_main],
173            args = twine_args,
174            data = [_dist_target],
175            imports = ["."],
176            main = twine_main,
177            deps = [twine],
178            visibility = kwargs.get("visibility"),
179            **copy_propagating_kwargs(kwargs)
180        )
181
182py_wheel_rule = _py_wheel
183