diff --git a/news/pypackaging-bzl.changed.md b/news/pypackaging-bzl.changed.md new file mode 100644 index 0000000000..5248d98ad0 --- /dev/null +++ b/news/pypackaging-bzl.changed.md @@ -0,0 +1,5 @@ +(pypi) Invalid PEP 508 requirements now fail instead of being silently accepted, +as requirements are now parsed by +[`pypackaging.bzl`](https://github.com/jvolkman/pypackaging.bzl) (a Starlark +port of [`packaging`](https://github.com/pypa/packaging)). `WORKSPACE` users +get `pypackaging.bzl` from {obj}`py_repositories`. diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index c5331fd899..a8050dcef2 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -312,7 +312,7 @@ bzl_library( bzl_library( name = "pep508_requirement", srcs = ["pep508_requirement.bzl"], - deps = ["//python/private:normalize_name"], + deps = ["@pypackaging.bzl//:pypackaging"], ) bzl_library( diff --git a/python/private/pypi/parse_requirements.bzl b/python/private/pypi/parse_requirements.bzl index 2d8c4b4774..dfc4501c76 100644 --- a/python/private/pypi/parse_requirements.bzl +++ b/python/private/pypi/parse_requirements.bzl @@ -462,6 +462,9 @@ def _parse_requirements_from_req_files( all_files_parsed = {} index_url = None extra_index_urls = [] + + # The same lines are used on many platforms, so parse them once. + parsed_reqs = {} for file, plats in requirements_by_platform.items(): logger.trace(lambda: "Using {} for {}".format(file, plats)) contents = ctx.read(file) @@ -489,17 +492,21 @@ def _parse_requirements_from_req_files( # (3.0). get_index_urls = None - # Pre-parse requirements once per file to avoid redundant parsing in loops - parsed_reqs = [(entry, requirement(entry[1])) for entry in parse_result.requirements] + for _, req_line in parse_result.requirements: + if req_line not in parsed_reqs: + parsed_reqs[req_line] = requirement(req_line) for plat in plats: plat_env = platforms.get(plat) - requirements[plat] = [ - entry - for entry, req in parsed_reqs - if not req.marker or (plat_env and evaluate(req.marker, env = plat_env.env)) - ] + plat_reqs = [] + for entry in parse_result.requirements: + marker = parsed_reqs[entry[1]].marker + if not marker or ( + plat_env and evaluate(marker, env = plat_env.env) + ): + plat_reqs.append(entry) + requirements[plat] = plat_reqs options[plat] = pip_args @@ -511,16 +518,14 @@ def _parse_requirements_from_req_files( reqs_by_name = {} requirements_by_platform = {} + for plat, parse_results in requirements.items(): requirements_dict = {} for entry in sorted( parse_results, key = lambda x: (len(x[1].partition("==")[0]), x), ): - req_line = entry[1] - req = requirement(req_line) - - requirements_dict[req.name] = entry + requirements_dict[parsed_reqs[entry[1]].name] = entry extra_pip_args_for_plat = options[plat] diff --git a/python/private/pypi/pep508_requirement.bzl b/python/private/pypi/pep508_requirement.bzl index 7552642572..6798e06bd6 100644 --- a/python/private/pypi/pep508_requirement.bzl +++ b/python/private/pypi/pep508_requirement.bzl @@ -15,44 +15,68 @@ """This module is for parsing PEP508 requires-dist and requirements lines. """ -load("//python/private:normalize_name.bzl", "normalize_name") - -_STRIP = ["(", " ", ">", "=", "<", "~", "!", "@"] +load("@pypackaging.bzl", "pypackaging") def requirement(spec): """Parse a PEP508 requirement line Args: - spec: {type}`str` requirement line that will be parsed. + spec: {type}`str` requirement line that will be parsed. The options + of a `requirements.txt` line, e.g. `--hash`, are ignored. Returns: A struct with the information. """ - spec = spec.strip() - requires, _, maybe_hashes = spec.partition(";") - - version_start = requires.find("==") - version = None - if version_start != -1: - # Extract everything after '==' until the next space or end of the string - version, _, _ = requires[version_start + 2:].partition(" ") - - # Remove any trailing characters from the version string - version = version.strip(" ") - - marker, _, _ = maybe_hashes.partition("--hash") - requires, _, extras_unparsed = requires.partition("[") - extras_unparsed, _, _ = extras_unparsed.partition("]") - for char in _STRIP: - requires, _, _ = requires.partition(char) - extras = [normalize_name(e) for e in extras_unparsed.replace(" ", "").split(",") if e] - name = requires.strip(" ") - name = normalize_name(name) + + spec = _strip_options(spec) + + head, semicolon, marker = spec.partition(";") + name, at, url = head.partition("@") + if at: + # PEP 508 does not allow a version for the direct URL requirements, + # but `name==version @ url` has always been accepted here, so that + # the version of the distribution is known. + name, _, _ = name.partition("==") + + # PEP 508 needs a whitespace between the URL and the marker, but + # `name @ url; marker` is accepted by `pip` in the requirements files. + spec = name + at + url.rstrip() + if semicolon: + spec += " ;" + marker + + req = pypackaging.requirements.parse(spec) return struct( - name = name.replace("_", "-"), - name_ = name, - marker = marker.strip(" "), - extras = extras, - version = version, + # str: normalized PEP 503 package name using `-` separators. + name = req.name, + # str: normalized package name using `_` separators for Bazel labels. + name_ = req.name.replace("-", "_"), + # str: PEP 508 environment marker expression, or `""` if absent. + marker = req.marker_str or "", + # list[str]: sorted normalized extra names using `_` separators. + extras = [e.replace("-", "_") for e in req.extras], ) + +def _strip_options(line): + """Remove the `requirements.txt` options, which are not a part of PEP 508. + + The options, e.g. `--hash=sha256:...` or `-C key=value`, start with a `-` + that follows a whitespace. The quoted strings of the markers are skipped, + because they may have such text as well. + """ + if " -" not in line and "\t-" not in line: + return line + + quote = None + prev = "" + for i, c in enumerate(line.elems()): + if quote: + if c == quote: + quote = None + elif c in ("\"", "'"): + quote = c + elif c == "-" and prev in (" ", "\t"): + return line[:i] + prev = c + + return line diff --git a/tests/pypi/pep508/requirement_tests.bzl b/tests/pypi/pep508/requirement_tests.bzl index 2ce45922da..fd81a321cb 100644 --- a/tests/pypi/pep508/requirement_tests.bzl +++ b/tests/pypi/pep508/requirement_tests.bzl @@ -20,24 +20,37 @@ _tests = [] def _test_requirement_line_parsing(env): want = { - " name1[ foo ] ": ("name1", ["foo"], None, ""), - "Name[foo]": ("name", ["foo"], None, ""), - "name [fred,bar] @ http://foo.com ; python_version=='2.7'": ("name", ["fred", "bar"], None, "python_version=='2.7'"), - "name; (os_name=='a' or os_name=='b') and os_name=='c'": ("name", [], None, "(os_name=='a' or os_name=='b') and os_name=='c'"), - "name@http://foo.com": ("name", [], None, ""), - "name[ Foo123 ]": ("name", ["foo123"], None, ""), - "name[extra-one,extra-two.three]==1.0": ("name", ["extra_one", "extra_two_three"], "1.0", ""), - "name[extra]@http://foo.com": ("name", ["extra"], None, ""), - "name[foo]": ("name", ["foo"], None, ""), - "name[quux, strange];python_version<'2.7' and platform_version=='2'": ("name", ["quux", "strange"], None, "python_version<'2.7' and platform_version=='2'"), - "name_foo[bar]": ("name-foo", ["bar"], None, ""), - "name_foo[bar]==0.25": ("name-foo", ["bar"], "0.25", ""), + " name1[ foo ] ": ("name1", ["foo"], ""), + "Name[foo]": ("name", ["foo"], ""), + # No whitespace between the URL and the marker + "foo @ https://example.org/foo-1.0-py3-none-any.whl; os_name == 'a'": ("foo", [], "os_name == 'a'"), + "name [fred,bar] @ http://foo.com ; python_version=='2.7'": ("name", ["bar", "fred"], "python_version=='2.7'"), + "name; (os_name=='a' or os_name=='b') and os_name=='c'": ("name", [], "(os_name=='a' or os_name=='b') and os_name=='c'"), + "name@http://foo.com": ("name", [], ""), + "name[ Foo123 ]": ("name", ["foo123"], ""), + "name[extra-one,extra-two.three]==1.0": ("name", ["extra_one", "extra_two_three"], ""), + "name[extra]@http://foo.com": ("name", ["extra"], ""), + "name[foo]": ("name", ["foo"], ""), + "name[quux, strange];python_version<'2.7' and platform_version=='2'": ("name", ["quux", "strange"], "python_version<'2.7' and platform_version=='2'"), + "name_foo; platform_release != \"custom -x\"": ("name-foo", [], "platform_release != \"custom -x\""), + # The text that looks like an option in a quoted marker value is kept + "name_foo; platform_release != 'custom -- kernel' --hash=sha256:deadbeef": ("name-foo", [], "platform_release != 'custom -- kernel'"), + "name_foo==0.25\t--hash=sha256:deadbeef": ("name-foo", [], ""), + # The options may be indented with tabs in the requirements files + "name_foo==0.25 \t--hash=sha256:deadbeef": ("name-foo", [], ""), + # The short options, e.g. `-C` for `--config-settings` + "name_foo==0.25 -Ckey=value --hash=sha256:deadbeef": ("name-foo", [], ""), + "name_foo==0.25 ; os_name=='a' --hash=sha256:deadbeef": ("name-foo", [], "os_name=='a'"), + "name_foo[bar]": ("name-foo", ["bar"], ""), + "name_foo[bar]==0.25": ("name-foo", ["bar"], ""), + "name_foo[bar]==0.25 --hash=sha256:deadbeef": ("name-foo", ["bar"], ""), + "name_foo[bar]==0.25 @ http://foo.com ; os_name=='a'": ("name-foo", ["bar"], "os_name=='a'"), } - got = { - i: (parsed.name, parsed.extras, parsed.version, parsed.marker) - for i, parsed in {case: requirement(case) for case in want}.items() - } + got = {} + for case in want: + parsed = requirement(case) + got[case] = (parsed.name, parsed.extras, parsed.marker) env.expect.that_dict(got).contains_exactly(want) _tests.append(_test_requirement_line_parsing)