diff --git a/WORKSPACE b/WORKSPACE index f8e0adcd91..bc6d660187 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -34,6 +34,13 @@ load("@io_bazel_skydoc//skylark:skylark.bzl", "skydoc_repositories") skydoc_repositories() +# Python +load("//:python/def.bzl", "python_toolchain_repository") +python_toolchain_repository( + name = "python2", + path = "/usr/bin/python2", +) + # Requirements for building our piptool. load("//python:pip.bzl", "pip_import") @@ -166,9 +173,11 @@ pip_import( }, remove_runtime_deps = { # https://github.com/keras-team/keras/issues/10505 - "keras-applications": ["keras"], - "keras-preprocessing": ["keras"], + "keras-applications": ["keras", "keras-applications"], + "keras-preprocessing": ["keras", "keras-preprocessing"], + "keras": ["keras"], }, + python = "@python2//:bin/python", ) load( diff --git a/docs/index.html b/docs/index.html index f3487d21bd..0faa7a0a16 100644 --- a/docs/index.html +++ b/docs/index.html @@ -37,13 +37,11 @@
pip_version_proxy
+
+ A rule for proxying requirements between different python runtimes.
+ +whl_library
+
+ download_or_build_wheel
+
+ extract_wheels
pip_version_proxy
+
+ A rule for proxying requirements between different python runtimes.
+ +whl_library
+
+ download_or_build_wheel
+
+ extract_wheels
pip_import(name, requirements)+
pip_import(name, additional_buildtime_deps, additional_runtime_deps, pip_args, python, remove_runtime_deps, requirements, requirements_bzl)
A rule for importing <code>requirements.txt</code> dependencies into Bazel.
This rule imports a <code>requirements.txt</code> file and generates a new @@ -133,13 +132,143 @@
A unique name for this rule.
additional_buildtime_depsDictionary mapping strings to lists of strings; Optional; Default is {}
additional_runtime_depsDictionary mapping strings to lists of strings; Optional; Default is {}
pip_argsList of strings; Optional; Default is []
pythonLabel; Optional
remove_runtime_depsDictionary mapping strings to lists of strings; Optional; Default is {}
requirementsLabel; Required
List of labels; Required
The label of a requirements.txt file.
requirements_bzlLabel; Optional
pip_version_proxy(name, define, python, values)+ +
A rule for proxying requirements between different python runtimes.
+This rule generates a <code>requirements.bzl</code> file that provides +a <code>requirements()</code> function that resolves to the correct version +of python dependencies depending on the current python runtime. +This is used via the <code>WORKSPACE</code> pattern:
+<pre><code>pip_import( + name = "pip_deps2", + requirements = ["//:requirements-pip.txt"], + python = "@python2//:bin/python", +) +pip_import( + name = "pip_deps3", + requirements = ["//:requirements-pip.txt"], + python = "@python3//:bin/python", +) +load("@pip_deps2//:requirements.bzl", pip_install2 = "pip_install") +pip_install2() +load("@pip_deps3//:requirements.bzl", pip_install3 = "pip_install") +pip_install3() + +pip_version_proxy( + name = "pip_deps", + define = "python", + values = { + "py2": "@pip_deps2", + "py3": "@pip_deps3", + }, +) +</code></pre>When importing dependencies from a <code>BUILD</code> file with
+<pre><code>load("@pip_deps//:requirements.bzl", "requirement") +py_library( + name = "bar", + ... + deps = [ + requirement("mock"), + ], +) +</code></pre>the <code>requirement</code> macro will resolve to <code>pip_deps2</code> when +building with <code>--define python=py2</code>, and to <code>pip_deps3</code> when +building with <code>--define python=py3</code>.
+ + +name |
+
+
A unique name for this rule. + |
+
define |
+
+
The key of the <code>--define</code> that selects the python version. + |
+
python |
+
+
|
+
values |
+
+
For each item in the dict, the key is the value of the <code>--define</code> to match, +and the value is the name of the pip_import repository rule that provides +the pip dependencies for that python runtime. + |
+
-pip_import(name, requirements) +pip_import(name, additional_buildtime_deps, additional_runtime_deps, pip_args, python, remove_runtime_deps, requirements, requirements_bzl)A rule for importing
requirements.txt dependencies into Bazel.
@@ -90,12 +91,152 @@ py_binary(
A unique name for this rule.
+additional_buildtime_depsDictionary mapping strings to lists of strings; Optional; Default is {}
additional_runtime_depsDictionary mapping strings to lists of strings; Optional; Default is {}
pip_argsList of strings; Optional; Default is []
pythonLabel; Optional
remove_runtime_depsDictionary mapping strings to lists of strings; Optional; Default is {}
requirementsLabel; Required
List of labels; Required
The label of a requirements.txt file.
requirements_bzlLabel; Optional
+pip_version_proxy(name, define, python, values) ++ +A rule for proxying requirements between different python runtimes. + +This rule generates a
requirements.bzl file that provides
+a requirements() function that resolves to the correct version
+of python dependencies depending on the current python runtime.
+This is used via the WORKSPACE pattern:
+
+pip_import(
+ name = "pip_deps2",
+ requirements = ["//:requirements-pip.txt"],
+ python = "@python2//:bin/python",
+)
+pip_import(
+ name = "pip_deps3",
+ requirements = ["//:requirements-pip.txt"],
+ python = "@python3//:bin/python",
+)
+load("@pip_deps2//:requirements.bzl", pip_install2 = "pip_install")
+pip_install2()
+load("@pip_deps3//:requirements.bzl", pip_install3 = "pip_install")
+pip_install3()
+
+pip_version_proxy(
+ name = "pip_deps",
+ define = "python",
+ values = {
+ "py2": "@pip_deps2",
+ "py3": "@pip_deps3",
+ },
+)
+
+
+When importing dependencies from a BUILD file with
+
+load("@pip_deps//:requirements.bzl", "requirement")
+py_library(
+ name = "bar",
+ ...
+ deps = [
+ requirement("mock"),
+ ],
+)
+
+
+the requirement macro will resolve to pip_deps2 when
+building with --define python=py2, and to pip_deps3 when
+building with --define python=py3.
+
+
+
+### Attributes
+
+
+name |
+
+
A unique name for this rule. + |
+
define |
+
+
The key of the <code>--define</code> that selects the python version. + |
+
python |
+
+
|
+
values |
+
+
For each item in the dict, the key is the value of the <code>--define</code> to match, +and the value is the name of the pip_import repository rule that provides +the pip dependencies for that python runtime. + |
+
download_or_build_wheel(name, buildtime_deps, pip_args, python, requirement, urls, wheel_name)+ + + +
name |
+
+
A unique name for this rule. + |
+
buildtime_deps |
+
+
|
+
pip_args |
+
+
|
+
python |
+
+
|
+
requirement |
+
+
|
+
urls |
+
+
|
+
wheel_name |
+
+
|
+
whl_library(name, requirements, whl)+
extract_wheels(name, additional_runtime_deps, extras, python, remove_runtime_deps, repository, wheels)
A rule for importing <code>.whl</code> dependencies into Bazel.
<b>This rule is currently used to implement <code>pip_import</code>, @@ -78,12 +144,12 @@
This rule defines a <code>@foo//:pkg</code> <code>py_library</code> target.
-name |
A unique name for this rule. |
requirements |
+ |
additional_runtime_deps |
+
+
|
+
extras |
+
+
A subset of the "extras" available from this <code>.whl</code> for which +<code>requirements</code> has the dependencies. + |
+
python |
+
+
|
+
remove_runtime_deps |
+
+
|
+
repository |
The name of the pip_import repository rule from which to -load this .whl's dependencies. + |
whl |
+ |
wheels |
-
The path to the .whl file (the name is expected to follow this -convention) +
|
name |
+
+
A unique name for this rule. + |
+
buildtime_deps |
+
+
|
+
pip_args |
+
+
|
+
python |
+
+
|
+
requirement |
+
+
|
+
urls |
+
+
|
+
wheel_name |
+
+
|
+
+extract_wheels(name, additional_runtime_deps, extras, python, remove_runtime_deps, repository, wheels)A rule for importing
.whl dependencies into Bazel.
@@ -28,14 +100,14 @@ This rule imports a .whl file as a py_library:
whl_library(
name = "foo",
whl = ":my-whl-file",
- requirements = "name of pip_import rule",
+ repository = "name of pip_import rule",
)
This rule defines a @foo//:pkg py_library target.
-
+
### Attributes
@@ -45,27 +117,54 @@ This rule defines a @foo//:pkg py_library target.
nameName; Required
A unique name for this rule.
requirementsadditional_runtime_depsList of strings; Optional; Default is []
extrasList of strings; Optional; Default is []
A subset of the "extras" available from this <code>.whl</code> for which +<code>requirements</code> has the dependencies.
+pythonLabel; Optional
remove_runtime_depsList of strings; Optional; Default is []
repositoryString; Optional; Default is ''
The name of the pip_import repository rule from which to -load this .whl's dependencies.
+whlwheelsLabel; Required
The path to the .whl file (the name is expected to follow this -convention)
+List of labels; Optional; Default is []
requirements.bzl file that provides
+a requirements() function that resolves to the correct version
+of python dependencies depending on the current python runtime.
+This is used via the WORKSPACE pattern:
+
+pip_import(
+ name = "pip_deps2",
+ requirements = ["//:requirements-pip.txt"],
+ python = "@python2//:bin/python",
+)
+pip_import(
+ name = "pip_deps3",
+ requirements = ["//:requirements-pip.txt"],
+ python = "@python3//:bin/python",
+)
+load("@pip_deps2//:requirements.bzl", pip_install2 = "pip_install")
+pip_install2()
+load("@pip_deps3//:requirements.bzl", pip_install3 = "pip_install")
+pip_install3()
+
+pip_version_proxy(
+ name = "pip_deps",
+ define = "python",
+ values = {
+ "py2": "@pip_deps2",
+ "py3": "@pip_deps3",
+ },
+)
+
+
+When importing dependencies from a BUILD file with
+
+load("@pip_deps//:requirements.bzl", "requirement")
+py_library(
+ name = "bar",
+ ...
+ deps = [
+ requirement("mock"),
+ ],
+)
+
+
+the requirement macro will resolve to pip_deps2 when
+building with --define python=py2, and to pip_deps3 when
+building with --define python=py3.
+
+Args:
+ define: The key of the --define that selects the python version.
+ values: For each item in the dict, the key is the value of the --define to match,
+ and the value is the name of the pip_import repository rule that provides
+ the pip dependencies for that python runtime.
+"""
+
+
def pip_repositories():
"""Pull in dependencies needed for pulling in pip dependencies.
diff --git a/python/whl.bzl b/python/whl.bzl
index 5a62027b3c..8f8288601c 100644
--- a/python/whl.bzl
+++ b/python/whl.bzl
@@ -20,8 +20,9 @@ load(
)
def _extract_wheels(ctx, wheels):
+ python = ctx.path(ctx.attr.python) if ctx.attr.python else "python"
args = [
- "python",
+ python,
ctx.path(ctx.attr._piptool),
"extract",
"--directory", str(ctx.path("")),
@@ -39,6 +40,7 @@ def _extract_wheels(ctx, wheels):
def _build_wheel(ctx):
env = {}
+ python = ctx.path(ctx.attr.python) if ctx.attr.python else "python"
# Resolve the paths to the dependency wheels to force them to be created.
# This may cause re-starting this repository rule, see:
@@ -47,11 +49,22 @@ def _build_wheel(ctx):
# wheel has been extracted (see below).
paths = [ctx.path(d) for d in ctx.attr.buildtime_deps]
+ # Check that python headers are installed. Otherwise some wheels may be built
+ # differently depending on the machine..
+ result = ctx.execute(["/bin/sh", "-c", "\n".join([
+ "INCLUDEPY=$(%s -c \"import sysconfig; print(sysconfig.get_config_vars()['INCLUDEPY'])\")" % python,
+ "ls \"$INCLUDEPY/Python.h\""
+ ])])
+ if result.return_code:
+ fail(("Python headers not installed: %s" +
+ "If you are using host machine's python interpreter, you may need to install headers from your OS vendor " +
+ "(e.g. \"apt-get install python-dev python3-dev\" on Ubuntu).") % result.stderr)
+
# Compute a hash from the build time dependencies, and use that in the cache
# key. The idea is that if any buildtime dependency changes versions, we will
# no longer use the same cached wheel.
hash_input = ':'.join([dep.name for dep in ctx.attr.buildtime_deps])
- cmd = ["python", "-c", "import hashlib; print(hashlib.sha256('%s'.encode('utf-8')).hexdigest())" % hash_input]
+ cmd = [python, "-c", "import hashlib; print(hashlib.sha256('%s'.encode('utf-8')).hexdigest())" % hash_input]
result = ctx.execute(cmd)
if result.return_code:
fail("failed to compute checksum: %s (%s)" % (result.stdout, result.stderr))
@@ -73,7 +86,7 @@ allow_hosts = ''
env["PYTHONPATH"] = ':'.join([root + dep.workspace_root for dep in ctx.attr.buildtime_deps])
cmd = [
- "python",
+ python,
ctx.path(ctx.attr._piptool),
"build",
"--directory", ctx.path(""),
@@ -112,6 +125,10 @@ download_or_build_wheel = repository_rule(
),
"wheel_name": attr.string(),
"pip_args": attr.string_list(),
+ "python": attr.label(
+ executable = True,
+ cfg = "host",
+ ),
"_piptool": attr.label(
executable = True,
default = Label("//tools:piptool.par"),
@@ -138,6 +155,10 @@ extract_wheels = repository_rule(
"remove_runtime_deps": attr.string_list(),
"repository": attr.string(),
"extras": attr.string_list(),
+ "python": attr.label(
+ executable = True,
+ cfg = "host",
+ ),
"_piptool": attr.label(
executable = True,
default = Label("//tools:piptool.par"),
diff --git a/rules_python/piptool.py b/rules_python/piptool.py
index c2650f56b3..6897ca5f10 100644
--- a/rules_python/piptool.py
+++ b/rules_python/piptool.py
@@ -175,6 +175,10 @@ def extract(args):
for w in whls:
w.expand(args.directory)
+ for root, dirs, files in os.walk(args.directory):
+ if root != args.directory and '__init__.py' not in files:
+ open(os.path.join(root, '__init__.py'), 'a').close()
+
imports = ['.']
purelib_path = os.path.join('%s-%s.data' % (whl.distribution(), whl.version()), 'purelib')
if os.path.isdir(os.path.join(args.directory, purelib_path)):
@@ -393,14 +397,14 @@ def whl_library(wheel):
attrs += [("urls", '[{}]'.format(quote(url)))]
if args.output_format != 'download':
attrs += [("whl", '"@{}//:{}"'.format(args.name, wheel.basename()))]
- extras = ', '.join([quote(extra) for extra in possible_extras.get(wheel, [])])
+ extras = ', '.join([quote(extra) for extra in sorted(possible_extras.get(wheel, []))])
if extras != '':
attrs += [("extras", '[{}]'.format(extras))]
runtime_deps = ', '.join([quote(dep) for dep in wheel.dependencies()])
#if runtime_deps != '':
# attrs["runtime_deps"] = '[{}]'.format(runtime_deps)
transitive_runtime_deps = set([split_extra(dep)[0] for dep in transitive_deps(wheel)])
- transitive_runtime_deps = ', '.join([quote(dep) for dep in transitive_runtime_deps])
+ transitive_runtime_deps = ', '.join([quote(dep) for dep in sorted(transitive_runtime_deps)])
if transitive_runtime_deps != '':
attrs += [("transitive_runtime_deps", '[{}]'.format(transitive_runtime_deps))]
@@ -418,7 +422,7 @@ def whl_library(wheel):
# For every extra that is possible from this requirements.txt
'"{name}[{extra_lower}]": "@{repo}//:{extra}",\n "{name}:dirty[{extra_lower}]": "@{repo}_dirty//:{extra}"'.format(
name=whl.name(), repo=lib_repo(whl), extra=extra, extra_lower=extra.lower())
- for extra in possible_extras.get(whl, [])
+ for extra in sorted(possible_extras.get(whl, []))
])
for whl in whls
])
@@ -451,14 +455,15 @@ def pip_install():
for key, attributes in all_libs.items():
whl_library(
key = key,
- all_libs = all_libs,
+ all_libs = all_libs,{python}
**attributes
)
""".format(comment='\n'.join(['# Generated from ' + i for i in args.input]),
name=args.name,
all_libs='\n '.join(map(whl_library, whls)),
- requirements_map=requirements_map))
+ requirements_map=requirements_map,
+ python='\n python = "{}",'.format(args.python) if args.python else ''))
parser = subparsers.add_parser('resolve', help='Resolve requirements.bzl from requirements.txt')
parser.set_defaults(func=resolve)
@@ -478,6 +483,9 @@ def pip_install():
parser.add_argument('--directory', action='store', default='.',
help=('The directory into which to put .whl files.'))
+parser.add_argument('--python', action='store',
+ help=('The python interpreter to use for building wheels.'))
+
parser.add_argument('args', nargs=argparse.REMAINDER,
help=('Extra arguments to send to pip.'))
diff --git a/rules_python/update.sh.tpl b/rules_python/update.sh.tpl
index d63fc66a71..58d6ec57b6 100644
--- a/rules_python/update.sh.tpl
+++ b/rules_python/update.sh.tpl
@@ -9,12 +9,13 @@ PIP_CACHE="%{directory}/pip-cache"
REQUIREMENTS_BZL_TEMP="requirements.bzl.tmp"
echo "Generating $REQUIREMENTS_BZL from ${REQUIREMENTS_TXT[@]}..."
-python "%{piptool}" resolve \
+"%{python}" "%{piptool}" resolve \
--name "%{name}" \
"${REQUIREMENTS_TXT[@]/#/--input=}" \
--output "$REQUIREMENTS_BZL_TEMP" \
--output-format download \
--directory $BUILD_AREA \
+ --python "%{python_label}" \
-- %{pip_args} \
--cache-dir "$PIP_CACHE" \
"$@"
diff --git a/rules_python/whl.bzl.tpl b/rules_python/whl.bzl.tpl
index 88dc96b97d..d82904502b 100644
--- a/rules_python/whl.bzl.tpl
+++ b/rules_python/whl.bzl.tpl
@@ -16,7 +16,7 @@ def _wheel(all_libs, key):
def _extracted_wheel(all_libs, key):
return "@%s//:%s" % (all_libs[key]["name"], all_libs[key]["wheel_name"])
-def whl_library(key, all_libs, name, wheel_name, version=None, urls=None, whl=None, transitive_runtime_deps=[], runtime_deps=[], extras=[]):
+def whl_library(key, all_libs, name, wheel_name, version=None, urls=None, whl=None, transitive_runtime_deps=[], runtime_deps=[], extras=[], python=None):
repository = "%{repo}"
dirty_repo_name = "%s_dirty" % name
wheel_repo_name = "%s_wheel" % name
@@ -35,6 +35,7 @@ def whl_library(key, all_libs, name, wheel_name, version=None, urls=None, whl=No
remove_runtime_deps = remove_runtime_deps,
repository = repository,
extras = extras,
+ python = python,
)
else:
download_or_build_wheel(
@@ -44,6 +45,7 @@ def whl_library(key, all_libs, name, wheel_name, version=None, urls=None, whl=No
wheel_name = wheel_name,
buildtime_deps = [_extracted_wheel(all_libs, d) for d in buildtime_deps],
pip_args = [%{pip_args}],
+ python = python,
)
extract_wheels(
name = name,
@@ -52,15 +54,21 @@ def whl_library(key, all_libs, name, wheel_name, version=None, urls=None, whl=No
remove_runtime_deps = remove_runtime_deps,
repository = repository,
extras = extras,
+ python = python,
)
if dirty_repo_name not in native.existing_rules():
- dep_keys = {d.split("[")[0]: None for d in transitive_runtime_deps}
- dep_keys[key] = None
+ # Make sure the current package's wheel is the first element in the "wheels" list,
+ # since piptool will generate the BUILD file based on that. The remaining wheels
+ # on the list should be all transitive runtime dependencies (unless explicitly
+ # dropped at pip_import rule level).
+ dep_keys = {d.split("[")[0]: None for d in transitive_runtime_deps if d not in remove_runtime_deps}
if whl:
- wheels = ["@%s//:%s" % (repository, all_libs[key]["wheel_name"]) for key in dep_keys]
+ wheels = ["@%s//:%s" % (repository, all_libs[key]["wheel_name"])] + \
+ ["@%s//:%s" % (repository, all_libs[key]["wheel_name"]) for key in dep_keys]
else:
- wheels = [_wheel(all_libs, d) for d in dep_keys]
+ wheels = [_wheel(all_libs, key)] + \
+ [_wheel(all_libs, d) for d in dep_keys]
extract_wheels(
name = dirty_repo_name,
wheels = wheels,
@@ -68,4 +76,5 @@ def whl_library(key, all_libs, name, wheel_name, version=None, urls=None, whl=No
remove_runtime_deps = remove_runtime_deps,
repository = repository,
extras = extras,
+ python = python,
)
diff --git a/tools/piptool.par b/tools/piptool.par
index 31d0dc6575..2fed7f6a7e 100755
Binary files a/tools/piptool.par and b/tools/piptool.par differ