1"""Repository rule for Python autoconfiguration.
2
3`python_configure` depends on the following environment variables:
4
5  * `PYTHON_BIN_PATH`: location of python binary.
6"""
7
8_PYTHON_BIN_PATH = "PYTHON_BIN_PATH"
9
10def _tpl(repository_ctx, tpl, substitutions = {}, out = None):
11    if not out:
12        out = tpl
13    repository_ctx.template(
14        out,
15        Label("//third_party/py:%s.tpl" % tpl),
16        substitutions,
17    )
18
19def _fail(msg):
20    """Output failure message when auto configuration fails."""
21    red = "\033[0;31m"
22    no_color = "\033[0m"
23    fail("%sPython Configuration Error:%s %s\n" % (red, no_color, msg))
24
25def _get_python_bin(repository_ctx):
26    """Gets the python bin path."""
27    python_bin = repository_ctx.os.environ.get(_PYTHON_BIN_PATH)
28    if python_bin != None:
29        return python_bin
30    python_bin_path = repository_ctx.which("python")
31    if python_bin_path != None:
32        return str(python_bin_path)
33    _fail("Cannot find python in PATH, please make sure " +
34          "python is installed and add its directory in PATH, or --define " +
35          "%s='/something/else'.\nPATH=%s" % (
36              _PYTHON_BIN_PATH,
37              repository_ctx.os.environ.get("PATH", ""),
38          ))
39
40def _create_local_python_repository(repository_ctx):
41    """Creates the repository containing files set up to build with Python."""
42    python_bin = _get_python_bin(repository_ctx)
43    _tpl(repository_ctx, "BUILD", {
44        "%{PYTHON_BIN_PATH}": python_bin,
45    })
46
47def _python_autoconf_impl(repository_ctx):
48    """Implementation of the python_autoconf repository rule."""
49    _create_local_python_repository(repository_ctx)
50
51python_configure = repository_rule(
52    implementation = _python_autoconf_impl,
53    environ = [
54        _PYTHON_BIN_PATH,
55    ],
56)
57"""Detects and configures the local Python toolchain.
58
59Add the following to your WORKSPACE FILE:
60
61```python
62load("//third_party/py:python_configure.bzl", "python_configure")
63
64python_configure(name = "local_config_py_toolchain")
65
66register_toolchains("@local_config_py_toolchain//:py_toolchain")
67```
68
69Args:
70  name: A unique name for this workspace rule.
71"""
72