diff --git a/BUILD.bazel b/BUILD.bazel index 9e5c70b732..ae9c87d1bf 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -27,7 +27,8 @@ load("@package_metadata//rules:package_metadata.bzl", "package_metadata") # gazelle:resolve starlark @bazel_tools//tools/build_defs/repo:http.bzl //python/private:bazel_tools # gazelle:resolve starlark @bazel_tools//tools/build_defs/repo:utils.bzl //python/private:bazel_tools -# Prevent Gazelle from incorrectly stripping the .bzl suffix from the toml.bzl repo name +# Prevent Gazelle from incorrectly stripping the .bzl suffix from the repo names +# gazelle:resolve starlark @pypackaging.bzl//:pypackaging.bzl @pypackaging.bzl//:pypackaging # gazelle:resolve starlark @toml.bzl//:toml.bzl @toml.bzl//:toml # Override Gazelle's incorrect default resolution for platforms host constraints Starlark library diff --git a/MODULE.bazel b/MODULE.bazel index 98ae8114b5..2fea2d486c 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -8,6 +8,7 @@ bazel_dep(name = "bazel_features", version = "1.55.0") bazel_dep(name = "bazel_skylib", version = "1.8.2") bazel_dep(name = "package_metadata", version = "0.0.13") bazel_dep(name = "platforms", version = "0.0.11") +bazel_dep(name = "pypackaging.bzl", version = "0.4.0") bazel_dep(name = "rules_cc", version = "0.2.17") bazel_dep(name = "toml.bzl", version = "0.4.1") diff --git a/WORKSPACE b/WORKSPACE index 631b94118d..f282982d82 100644 --- a/WORKSPACE +++ b/WORKSPACE @@ -61,14 +61,17 @@ load("@stardoc_maven//:defs.bzl", stardoc_pinned_maven_install = "pinned_maven_i stardoc_pinned_maven_install() +load("//python:repositories.bzl", "py_repositories", "python_register_multi_toolchains") + +# This needs to be called before the internal setup, because the repository +# rules that it loads use the dependencies defined here. +py_repositories() + load("//:internal_dev_setup.bzl", "rules_python_internal_setup") rules_python_internal_setup() load("@pythons_hub//:versions.bzl", "PYTHON_VERSIONS") -load("//python:repositories.bzl", "py_repositories", "python_register_multi_toolchains") - -py_repositories() python_register_multi_toolchains( name = "python", diff --git a/downloader_config.cfg b/downloader_config.cfg index 8bde140608..d445f15ff1 100644 --- a/downloader_config.cfg +++ b/downloader_config.cfg @@ -20,6 +20,7 @@ rewrite ^github\.com/bazelbuild/rules_swift/(.*) github.com/bazelbuild/rules_swi rewrite ^github\.com/bazelbuild/rules_testing/(.*) github.com/bazelbuild/rules_testing/$1 rewrite ^github\.com/bazelbuild/stardoc/(.*) github.com/bazelbuild/stardoc/$1 rewrite ^github\.com/google/googletest/(.*) github.com/google/googletest/$1 +rewrite ^github\.com/jvolkman/pypackaging\.bzl/(.*) github.com/jvolkman/pypackaging.bzl/$1 rewrite ^github\.com/jvolkman/toml\.bzl/(.*) github.com/jvolkman/toml.bzl/$1 rewrite ^github\.com/protocolbuffers/protobuf/(.*) github.com/protocolbuffers/protobuf/$1 # keep-sorted end @@ -48,6 +49,7 @@ rewrite ^github\.com/bazelbuild/rules_swift/(.*) mirror.bazel.build/github.com/b rewrite ^github\.com/bazelbuild/rules_testing/(.*) mirror.bazel.build/github.com/bazelbuild/rules_testing/$1 rewrite ^github\.com/bazelbuild/stardoc/(.*) mirror.bazel.build/github.com/bazelbuild/stardoc/$1 rewrite ^github\.com/google/googletest/(.*) mirror.bazel.build/github.com/google/googletest/$1 +rewrite ^github\.com/jvolkman/pypackaging\.bzl/(.*) mirror.bazel.build/github.com/jvolkman/pypackaging.bzl/$1 rewrite ^github\.com/jvolkman/toml\.bzl/(.*) mirror.bazel.build/github.com/jvolkman/toml.bzl/$1 rewrite ^github\.com/protocolbuffers/protobuf/(.*) mirror.bazel.build/github.com/protocolbuffers/protobuf/$1 # keep-sorted end diff --git a/gazelle/downloader_config.cfg b/gazelle/downloader_config.cfg index 8bde140608..d445f15ff1 100644 --- a/gazelle/downloader_config.cfg +++ b/gazelle/downloader_config.cfg @@ -20,6 +20,7 @@ rewrite ^github\.com/bazelbuild/rules_swift/(.*) github.com/bazelbuild/rules_swi rewrite ^github\.com/bazelbuild/rules_testing/(.*) github.com/bazelbuild/rules_testing/$1 rewrite ^github\.com/bazelbuild/stardoc/(.*) github.com/bazelbuild/stardoc/$1 rewrite ^github\.com/google/googletest/(.*) github.com/google/googletest/$1 +rewrite ^github\.com/jvolkman/pypackaging\.bzl/(.*) github.com/jvolkman/pypackaging.bzl/$1 rewrite ^github\.com/jvolkman/toml\.bzl/(.*) github.com/jvolkman/toml.bzl/$1 rewrite ^github\.com/protocolbuffers/protobuf/(.*) github.com/protocolbuffers/protobuf/$1 # keep-sorted end @@ -48,6 +49,7 @@ rewrite ^github\.com/bazelbuild/rules_swift/(.*) mirror.bazel.build/github.com/b rewrite ^github\.com/bazelbuild/rules_testing/(.*) mirror.bazel.build/github.com/bazelbuild/rules_testing/$1 rewrite ^github\.com/bazelbuild/stardoc/(.*) mirror.bazel.build/github.com/bazelbuild/stardoc/$1 rewrite ^github\.com/google/googletest/(.*) mirror.bazel.build/github.com/google/googletest/$1 +rewrite ^github\.com/jvolkman/pypackaging\.bzl/(.*) mirror.bazel.build/github.com/jvolkman/pypackaging.bzl/$1 rewrite ^github\.com/jvolkman/toml\.bzl/(.*) mirror.bazel.build/github.com/jvolkman/toml.bzl/$1 rewrite ^github\.com/protocolbuffers/protobuf/(.*) mirror.bazel.build/github.com/protocolbuffers/protobuf/$1 # keep-sorted end diff --git a/news/pypackaging-bzl.changed.md b/news/pypackaging-bzl.changed.md new file mode 100644 index 0000000000..34893956ea --- /dev/null +++ b/news/pypackaging-bzl.changed.md @@ -0,0 +1,3 @@ +(pypi) PEP 508 requirements and environment markers now match +[`packaging`](https://github.com/pypa/packaging) and reject invalid syntax via +[`pypackaging.bzl`](https://github.com/jvolkman/pypackaging.bzl). diff --git a/python/private/py_repositories.bzl b/python/private/py_repositories.bzl index 5353b8b8c5..5eeaf4415f 100644 --- a/python/private/py_repositories.bzl +++ b/python/private/py_repositories.bzl @@ -78,6 +78,12 @@ def py_repositories(transition_settings = []): strip_prefix = "toml.bzl-0.4.0", url = "https://github.com/jvolkman/toml.bzl/releases/download/v0.4.0/toml.bzl-v0.4.0.tar.gz", ) + http_archive( + name = "pypackaging.bzl", + sha256 = "d234430a5425e8b090c0071944036516a3516b41f9c9d005113fff0533f591b3", + strip_prefix = "pypackaging.bzl-0.4.0", + url = "https://github.com/jvolkman/pypackaging.bzl/releases/download/v0.4.0/pypackaging.bzl-v0.4.0.tar.gz", + ) http_archive( name = "package_metadata", sha256 = "755bd6c8a3751982e2555d96c913ec070954ca9d01f935563392255da4ebad72", diff --git a/python/private/pypi/BUILD.bazel b/python/private/pypi/BUILD.bazel index c5331fd899..61f0c9f004 100644 --- a/python/private/pypi/BUILD.bazel +++ b/python/private/pypi/BUILD.bazel @@ -284,7 +284,6 @@ bzl_library( name = "pep508_deps", srcs = ["pep508_deps.bzl"], deps = [ - ":pep508_env", ":pep508_evaluate", ":pep508_requirement", "//python/private:normalize_name", @@ -294,25 +293,22 @@ bzl_library( bzl_library( name = "pep508_env", srcs = ["pep508_env.bzl"], - deps = [ - "//python/private:normalize_name", - "//python/private:version", - ], + deps = ["//python/private:version"], ) bzl_library( name = "pep508_evaluate", srcs = ["pep508_evaluate.bzl"], deps = [ - "//python/private:enum", - "//python/private:version", + "@bazel_skylib//lib:types", + "@pypackaging.bzl//:pypackaging", ], ) 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/env_marker_setting.bzl b/python/private/pypi/env_marker_setting.bzl index 71c6b410ed..15c0ac6ab6 100644 --- a/python/private/pypi/env_marker_setting.bzl +++ b/python/private/pypi/env_marker_setting.bzl @@ -4,7 +4,7 @@ load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo") load("//python/private:common_labels.bzl", "labels") load("//python/private:toolchain_types.bzl", "TARGET_TOOLCHAIN_TYPE") load(":env_marker_info.bzl", "EnvMarkerInfo") -load(":pep508_env.bzl", "create_env", "set_missing_env_defaults") +load(":pep508_env.bzl", "set_missing_env_defaults") load(":pep508_evaluate.bzl", "evaluate") # Use capitals to hint its not an actual boolean type. @@ -38,10 +38,7 @@ def env_marker_setting(*, name, expression, **kwargs): ) def _env_marker_setting_impl(ctx): - env = create_env() - env.update( - ctx.attr._env_marker_config_flag[EnvMarkerInfo].env, - ) + env = dict(ctx.attr._env_marker_config_flag[EnvMarkerInfo].env) runtime = ctx.toolchains[TARGET_TOOLCHAIN_TYPE].py3_runtime diff --git a/python/private/pypi/flags.bzl b/python/private/pypi/flags.bzl index 36cb5373ff..6836209871 100644 --- a/python/private/pypi/flags.bzl +++ b/python/private/pypi/flags.bzl @@ -23,7 +23,6 @@ load("//python/private:common_labels.bzl", "labels") load(":env_marker_info.bzl", "EnvMarkerInfo") load( ":pep508_env.bzl", - "create_env", "os_name_select_map", "platform_machine_select_map", "platform_system_select_map", @@ -54,7 +53,7 @@ def _default_env_marker_config(**kwargs): ) def _env_marker_config_impl(ctx): - env = create_env() + env = {} env["os_name"] = ctx.attr.os_name env["sys_platform"] = ctx.attr.sys_platform env["platform_machine"] = ctx.attr.platform_machine 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_deps.bzl b/python/private/pypi/pep508_deps.bzl index e36ceadbd5..7286dd758b 100644 --- a/python/private/pypi/pep508_deps.bzl +++ b/python/private/pypi/pep508_deps.bzl @@ -16,7 +16,6 @@ """ load("//python/private:normalize_name.bzl", "normalize_name") -load(":pep508_env.bzl", "create_env") load(":pep508_evaluate.bzl", "evaluate") load(":pep508_requirement.bzl", "requirement") @@ -168,9 +167,8 @@ def _resolve_extras(self_name, reqs, extras): return sorted(extras) def _evaluate_any(req, extras): - env = create_env() for extra in extras: - if evaluate(req.marker, env = env | {"extra": extra}): + if evaluate(req.marker, env = {"extra": extra}): return True return False @@ -181,12 +179,11 @@ def _add_reqs(deps, deps_select, dep, reqs, *, extras): _add(deps, deps_select, dep) return - env = create_env() markers = {} found_unconditional = False for req in reqs: for x in extras: - m = evaluate(req.marker, env = env | {"extra": x}, strict = False) + m = evaluate(req.marker, env = {"extra": x}, strict = False) if m == False: continue elif m == True: diff --git a/python/private/pypi/pep508_env.bzl b/python/private/pypi/pep508_env.bzl index 9fe9dcaada..95a9679300 100644 --- a/python/private/pypi/pep508_env.bzl +++ b/python/private/pypi/pep508_env.bzl @@ -15,7 +15,6 @@ """This module is for implementing PEP508 environment definition. """ -load("//python/private:normalize_name.bzl", "normalize_name") load("//python/private:version.bzl", "version") _DEFAULT = "//conditions:default" @@ -31,15 +30,6 @@ _os_aliases = { } # See https://stackoverflow.com/a/45125525 -platform_machine_aliases = { - # These pairs mean the same hardware, but different values may be used - # on different host platforms. - "amd64": "x86_64", - "arm64": "aarch64", - "i386": "x86_32", - "i686": "x86_32", -} - # NOTE: There are many cpus, and unfortunately, the value isn't directly # accessible to Starlark. Using CcToolchain.cpu might work, though. # Some targets are aliases and are omitted below as their value is implied @@ -184,8 +174,7 @@ def env(*, env = None, os, arch, python_version = "", extra = None): Returns: A dict that can be used as `env` in the marker evaluation. """ - env = env or {} - env = env | create_env() + env = dict(env or {}) if extra != None: env["extra"] = extra @@ -214,16 +203,6 @@ def env(*, env = None, os, arch, python_version = "", extra = None): return env -def create_env(): - return { - # Per-variable normalization functions. Each entry maps a marker - # variable name to a function (value) -> normalized_value. - "_aliases": { - "extra": normalize_name, - "platform_machine": lambda x: platform_machine_aliases.get(x, x), - }, - } - def set_missing_env_defaults(env): """Sets defaults based on existing values. diff --git a/python/private/pypi/pep508_evaluate.bzl b/python/private/pypi/pep508_evaluate.bzl index 61e461a54f..9dede95952 100644 --- a/python/private/pypi/pep508_evaluate.bzl +++ b/python/private/pypi/pep508_evaluate.bzl @@ -12,490 +12,135 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""This module is for implementing PEP508 in starlark as FeatureFlagInfo -""" - -load("//python/private:enum.bzl", "enum") -load("//python/private:version.bzl", "version") - -# The expression parsing and resolution for the PEP508 is below -# - -_STATE = enum( - STRING = "string", - VAR = "var", - OP = "op", - NONE = "none", -) -_BRACKETS = "()" -_OPCHARS = "<>!=~" -_QUOTES = "'\"" -_WSP = " \t" -_NON_VERSION_VAR_NAMES = [ - "implementation_name", - "os_name", - "platform_machine", - "platform_python_implementation", - "platform_release", - "platform_system", - "sys_platform", - "extra", -] -_AND = "and" -_OR = "or" -_NOT = "not" -_ENV_ALIASES = "_aliases" +"""Evaluate the PEP 508 environment markers. -def tokenize(marker): - """Tokenize the input string. +The parsing and the evaluation is done by `pypackaging.bzl`, this module adds +what `rules_python` needs on top of it: - The output will have double-quoted values (i.e. the quoting will be normalized) and all of the whitespace will be trimmed. - - Args: - marker: {type}`str` The input to tokenize. - - Returns: - The {type}`str` that is the list of recognized tokens that should be parsed. - """ - if not marker: - return [] - - tokens = [] - token = "" - state = _STATE.NONE - char = "" - - # Due to the `continue` in the loop, we will be processing chars at a slower pace - for _ in range(2 * len(marker)): - if token and (state == _STATE.NONE or not marker): - if tokens and token == "in" and tokens[-1] == _NOT: - tokens[-1] += " " + token - else: - tokens.append(token) - token = "" - - if not marker: - return tokens - - char = marker[0] - if char in _BRACKETS: - state = _STATE.NONE - token = char - elif state == _STATE.STRING and char in _QUOTES: - state = _STATE.NONE - token = '"{}"'.format(token) - elif ( - (state == _STATE.VAR and not char.isalnum() and char != "_") or - (state == _STATE.OP and char not in _OPCHARS) - ): - state = _STATE.NONE - continue # Skip consuming the char below - elif state == _STATE.NONE: - # Transition from _STATE.NONE to something or stay in NONE - if char in _QUOTES: - state = _STATE.STRING - elif char.isalnum(): - state = _STATE.VAR - token += char - elif char in _OPCHARS: - state = _STATE.OP - token += char - elif char in _WSP: - state = _STATE.NONE - else: - fail("BUG: Cannot parse '{}' in {} ({})".format(char, state, marker)) - else: - token += char - - # Consume the char - marker = marker[1:] +* The `platform_machine` aliases, so that e.g. `arm64` and `aarch64` mean the + same thing. +* A single function for the full and the partial evaluation. The latter is + used to evaluate what is known when the repositories are created (e.g. the + `extra`) and to leave the rest for the analysis phase. +""" - return fail("BUG: failed to process the marker in allocated cycles: {}".format(marker)) +load("@bazel_skylib//lib:types.bzl", "types") +load("@pypackaging.bzl", "pypackaging") + +# These pairs mean the same hardware, but different values may be used on +# different host platforms. +_PLATFORM_MACHINE_ALIASES = { + # keep-sorted start + "amd64": "x86_64", + "arm64": "aarch64", + "i386": "x86_32", + "i686": "x86_32", + # keep-sorted end +} -def evaluate(marker, *, env, strict = True, **kwargs): +def evaluate(marker, *, env, strict = True): """Evaluate the marker against a given env. Args: marker: {type}`str` The string marker to evaluate. - env: {type}`dict[str, str]` The environment to evaluate the marker against. + env: {type}`dict[str, str]` The environment to evaluate the marker + against. strict: {type}`bool` A setting to not fail on missing values in the env. - **kwargs: Extra kwargs to be passed to the expression evaluator. Returns: - The {type}`bool | str` If the marker is compatible with the given env. If strict is - `False`, then the output type is `str` which will represent the remaining - expression that has not been evaluated. + The {type}`bool | str` If the marker is compatible with the given env. + If `strict` is `False`, then the output type is `str` if a part of the + marker could not be evaluated and it will represent the remaining + expression. """ - tokens = tokenize(marker) + tree = pypackaging.markers.parse(marker) + if "platform_machine" in marker and "platform_machine" in env: + # The comparisons that are not evaluated are left as they are written. + tree = _with_platform_machine_aliases(tree, max_depth = len(marker)) - ast = _new_expr(marker = marker, **kwargs) - for _ in range(len(tokens) * 2): - if not tokens: - break - - tokens = ast.parse(env = env, tokens = tokens, strict = strict) + # The value in the env may be an alias as well. + machine = env["platform_machine"] + env = env | { + "platform_machine": _PLATFORM_MACHINE_ALIASES.get(machine, machine), + } - if not tokens: - return ast.value() + if strict: + return pypackaging.markers.evaluate(tree, env) - fail("Could not evaluate: {}".format(marker)) + result = pypackaging.markers.evaluate_partial(tree, env) + if types.is_bool(result): + return result -_STRING_REPLACEMENTS = { - "!=": "neq", - "(": "_", - ")": "_", - "<": "lt", - "<=": "lteq", - "==": "eq", - "===": "eeq", - ">": "gt", - ">=": "gteq", - "not in": "not_in", - "~==": "cmp", -} + return pypackaging.markers.to_string(result) -def to_string(marker): - return "_".join([ - _STRING_REPLACEMENTS.get(t, t) - for t in tokenize(marker) - ]).replace("\"", "") +def _with_platform_machine_aliases(tree, *, max_depth): + """Use the canonical names in the comparisons with `platform_machine`. -def _and_fn(x, y): - """Our custom `and` evaluation function. + Args: + tree: {type}`list[tuple | list | str]` the parsed marker. + max_depth: {type}`int` the upper bound for the number of the + parenthesized expressions in the marker. - Allow partial evaluation if one of the values is a string, return the - string value because that means that `marker_expr` was set to - `strict = False` and we are only evaluating what we can. + Returns: + {type}`list[tuple | list | str]` a copy of the parsed marker. """ - if not (x and y): - return False + result = [] - x_is_str = type(x) == type("") - y_is_str = type(y) == type("") - if x_is_str and y_is_str: - return "{} and {}".format(x, y) - elif x_is_str: - return x - else: - return y + # The pairs of the list to copy and the list to copy it to. + todo = [(tree, result)] + for _ in range(max_depth + 1): + if not todo: + break -def _or_fn(x, y): - """Our custom `or` evaluation function. + src, dst = todo.pop() + for item in src: + if types.is_list(item): + nested = [] + dst.append(nested) + todo.append((item, nested)) + elif types.is_tuple(item): + dst.append(_with_platform_machine_alias(item)) + else: + dst.append(item) - Allow partial evaluation if one of the values is a string, return the - string value because that means that `marker_expr` was set to - `strict = False` and we are only evaluating what we can. - """ - x_is_str = type(x) == type("") - y_is_str = type(y) == type("") + return result - if x_is_str and y_is_str: - return "{} or {}".format(x, y) if x and y else "" - elif x_is_str: - return "" if y else x - elif y_is_str: - return "" if x else y - else: - return x or y +def _with_platform_machine_alias(item): + """Normalize literal operands compared against `platform_machine`. -def _not_fn(x): - """Our custom `not` evaluation function. + Args: + item: {type}`tuple[struct, str, struct]` a parsed `(lhs, op, rhs)` + comparison tuple. - Allow partial evaluation if the value is a string. + Returns: + {type}`tuple[struct, str, struct]` the comparison tuple with any + aliased `platform_machine` string operand replaced by its canonical + name. """ - if type(x) == type(""): - return "not {}".format(x) - else: - return not x - -def _new_expr( - *, - marker, - and_fn = _and_fn, - or_fn = _or_fn, - not_fn = _not_fn): - # buildifier: disable=uninitialized - self = struct( - marker = marker, - tree = [], - parse = lambda **kwargs: _parse(self, **kwargs), - value = lambda: _value(self), - # This is a way for us to have a handle to the currently constructed - # expression tree branch. - current = lambda: self._current[-1] if self._current else None, - _current = [], - _and = and_fn, - _or = or_fn, - _not = not_fn, - ) - return self - -def _parse(self, *, env, tokens, strict = False): - """The parse function takes the consumed tokens and returns the remaining.""" - token, remaining = tokens[0], tokens[1:] - - if token == "(": - expr = _open_parenthesis(self) - elif token == ")": - expr = _close_parenthesis(self) - elif token == _AND: - expr = _and_expr(self) - elif token == _OR: - expr = _or_expr(self) - elif token == _NOT: - expr = _not_expr(self) - else: - expr = marker_expr(env = env, strict = strict, *tokens[:3]) - remaining = tokens[3:] - - _append(self, expr) - return remaining - -def _value(self): - """Evaluate the expression tree""" - if not self.tree: - # Basic case where no marker should evaluate to True - return True - - for _ in range(len(self.tree)): - if len(self.tree) == 1: - return self.tree[0] - - # Resolve all of the `or` expressions as it is safe to do now since all - # `and` and `not` expressions have been taken care of by now. - if getattr(self.tree[-2], "op", None) == _OR: - current = self.tree.pop() - self.tree[-1] = self.tree[-1].value(current) - else: - break - - fail("BUG: invalid state: {}".format(self.tree)) + lhs, op, rhs = item + if lhs.type == "variable" and lhs.value == "platform_machine": + return (lhs, op, _platform_machine(rhs)) + if rhs.type == "variable" and rhs.value == "platform_machine": + return (_platform_machine(lhs), op, rhs) + return item -def marker_expr(left, op, right, *, env, strict = True): - """Evaluate a marker expression +def _platform_machine(value): + """Return a copy of a string AST node with its canonical machine name. Args: - left: {type}`str` the env identifier or a value quoted in `"`. - op: {type}`str` the operation to carry out. - right: {type}`str` the env identifier or a value quoted in `"`. - strict: {type}`bool` if false, only evaluates the values that are present - in the environment, otherwise returns the original expression. - env: {type}`dict[str, str]` the `env` to substitute `env` identifiers in - the ` ` expression. Note, if `env` has a key - "_aliases", then we will do normalization so that we can ensure - that e.g. `aarch64` evaluation in the `platform_machine` works the - same way irrespective if the marker uses `arm64` or `aarch64` value - in the expression. + value: {type}`struct` a parsed marker operand node (`type` and + `value`). Returns: - {type}`bool` if the expression evaluation result or {type}`str` if the expression - could not be evaluated. + {type}`struct` the operand node with `value` mapped through + `_PLATFORM_MACHINE_ALIASES` when `value` is a string node. """ - var_name = None - if right not in env and left not in env and not strict: - return "{} {} {}".format(left, op, right) - if left[0] == '"': - var_name = right - right = env[right] - left = left.strip("\"") - - if _ENV_ALIASES in env: - # Normalize the literal value using per-variable normalization - # functions. This handles platform aliases (e.g. arm64 -> aarch64) - # and PEP 685 extra name normalization (e.g. db-backend -> db_backend). - left = env.get(_ENV_ALIASES, {}).get(var_name, lambda x: x)(left) - - else: - var_name = left - left = env[left] - right = right.strip("\"") - - if _ENV_ALIASES in env: - # See the note above on normalization - right = env.get(_ENV_ALIASES, {}).get(var_name, lambda x: x)(right) - - if var_name in _NON_VERSION_VAR_NAMES: - return _env_expr(left, op, right) - elif var_name.endswith("_version"): - return _version_expr(left, op, right) - else: - # Do not fail here, just evaluate the expression to False. - return False - -def _env_expr(left, op, right): - """Evaluate a string comparison expression""" - if op == "==": - return left == right - elif op == "!=": - return left != right - elif op == "in": - return left in right - elif op == "not in": - return left not in right - elif op == "<": - return left < right - elif op == "<=": - return left <= right - elif op == ">": - return left > right - elif op == ">=": - return left >= right - else: - return fail("unsupported op: '{}' {} '{}'".format(left, op, right)) - -def _version_expr(left, op, right): - """Evaluate a version comparison expression""" - _left = version.parse(left) - _right = version.parse(right) - if _left == None or _right == None: - # Per spec, if either can't be normalized to a version, then - # fallback to simple string comparison. Usually this is `platform_version` - # or `platform_release`, which vary depending on platform. - return _env_expr(left, op, right) - - if op == "===": - return version.is_eeq(_left, _right) - elif op == "!=": - return version.is_ne(_left, _right) - elif op == "==": - return version.is_eq(_left, _right) - elif op == "<": - return version.is_lt(_left, _right) - elif op == ">": - return version.is_gt(_left, _right) - elif op == "<=": - return version.is_le(_left, _right) - elif op == ">=": - return version.is_ge(_left, _right) - elif op == "~=": - return version.is_compatible(_left, _right) - else: - return False # Let's just ignore the invalid ops - -# Code to allowing to combine expressions with logical operators - -def _append(self, value): - if value == None: - return - - current = self.current() or self - op = getattr(value, "op", None) - - if op == _NOT: - current.tree.append(value) - elif op in [_AND, _OR]: - value.append(current.tree[-1]) - current.tree[-1] = value - elif not current.tree: - current.tree.append(value) - elif hasattr(current.tree[-1], "append"): - current.tree[-1].append(value) - elif hasattr(current.tree, "_append"): - current.tree._append(value) - else: - fail("Cannot evaluate '{}' in '{}', current: {}".format(value, self.marker, current)) - -def _open_parenthesis(self): - """Add an extra node into the tree to perform evaluate inside parenthesis.""" - self._current.append(_new_expr( - marker = self.marker, - and_fn = self._and, - or_fn = self._or, - not_fn = self._not, - )) - -def _close_parenthesis(self): - """Backtrack and evaluate the expression within parenthesis.""" - value = self._current.pop().value() - if type(value) == type(""): - return "({})".format(value) - else: + if value.type != "string": return value -def _not_expr(self): - """Add an extra node into the tree to perform an 'not' operation.""" - - def _append(value): - """Append a value to the not expression node. - - This codifies `not` precedence over `and` and performs backtracking to - evaluate any `not` statements and forward the value to the first `and` - statement if needed. - """ - - current = self.current() or self - current.tree[-1] = self._not(value) - - for _ in range(len(current.tree)): - if not len(current.tree) > 1: - break - - op = getattr(current.tree[-2], "op", None) - if op == None: - pass - elif op == _NOT: - value = current.tree.pop() - current.tree[-1] = self._not(value) - continue - elif op == _AND: - value = current.tree.pop() - current.tree[-1].append(value) - elif op != _OR: - fail("BUG: '{} not' compound is unsupported".format(current.tree[-1])) - - break - - return struct( - op = _NOT, - append = _append, - ) - -def _and_expr(self): - """Add an extra node into the tree to perform an 'and' operation""" - maybe_value = [None] - - def _append(value): - """Append a value to the and expression node. - - Here we backtrack, but we only evaluate the current `and` statement - - all of the `not` statements will be by now evaluated and `or` - statements need to be evaluated later. - """ - if maybe_value[0] == None: - maybe_value[0] = value - return - - current = self.current() or self - current.tree[-1] = self._and(maybe_value[0], value) - - return struct( - op = _AND, - append = _append, - # private fields that help debugging - _maybe_value = maybe_value, - ) - -def _or_expr(self): - """Add an extra node into the tree to perform an 'or' operation""" - maybe_value = [None] - - def _append(value): - """Append a value to the or expression node. - - Here we just append the extra values to the tree and the `or` - statements will be evaluated in the _value() function. - """ - if maybe_value[0] == None: - maybe_value[0] = value - return - - current = self.current() or self - current.tree.append(value) - return struct( - op = _OR, - value = lambda x: self._or(maybe_value[0], x), - append = _append, - # private fields that help debugging - _maybe_value = maybe_value, + # str: AST node kind ("string"). + type = value.type, + # str: canonicalized machine architecture name. + value = _PLATFORM_MACHINE_ALIASES.get(value.value, value.value), ) 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/sphinxdocs/downloader_config.cfg b/sphinxdocs/downloader_config.cfg index 8bde140608..d445f15ff1 100644 --- a/sphinxdocs/downloader_config.cfg +++ b/sphinxdocs/downloader_config.cfg @@ -20,6 +20,7 @@ rewrite ^github\.com/bazelbuild/rules_swift/(.*) github.com/bazelbuild/rules_swi rewrite ^github\.com/bazelbuild/rules_testing/(.*) github.com/bazelbuild/rules_testing/$1 rewrite ^github\.com/bazelbuild/stardoc/(.*) github.com/bazelbuild/stardoc/$1 rewrite ^github\.com/google/googletest/(.*) github.com/google/googletest/$1 +rewrite ^github\.com/jvolkman/pypackaging\.bzl/(.*) github.com/jvolkman/pypackaging.bzl/$1 rewrite ^github\.com/jvolkman/toml\.bzl/(.*) github.com/jvolkman/toml.bzl/$1 rewrite ^github\.com/protocolbuffers/protobuf/(.*) github.com/protocolbuffers/protobuf/$1 # keep-sorted end @@ -48,6 +49,7 @@ rewrite ^github\.com/bazelbuild/rules_swift/(.*) mirror.bazel.build/github.com/b rewrite ^github\.com/bazelbuild/rules_testing/(.*) mirror.bazel.build/github.com/bazelbuild/rules_testing/$1 rewrite ^github\.com/bazelbuild/stardoc/(.*) mirror.bazel.build/github.com/bazelbuild/stardoc/$1 rewrite ^github\.com/google/googletest/(.*) mirror.bazel.build/github.com/google/googletest/$1 +rewrite ^github\.com/jvolkman/pypackaging\.bzl/(.*) mirror.bazel.build/github.com/jvolkman/pypackaging.bzl/$1 rewrite ^github\.com/jvolkman/toml\.bzl/(.*) mirror.bazel.build/github.com/jvolkman/toml.bzl/$1 rewrite ^github\.com/protocolbuffers/protobuf/(.*) mirror.bazel.build/github.com/protocolbuffers/protobuf/$1 # keep-sorted end diff --git a/tests/integration/bzlmod_lockfile/MODULE.bazel.lock b/tests/integration/bzlmod_lockfile/MODULE.bazel.lock index 2f3c632adb..37e0f8cb6c 100644 --- a/tests/integration/bzlmod_lockfile/MODULE.bazel.lock +++ b/tests/integration/bzlmod_lockfile/MODULE.bazel.lock @@ -93,6 +93,8 @@ "https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/MODULE.bazel": "88af1c246226d87e65be78ed49ecd1e6f5e98648558c14ce99176da041dc378e", "https://bcr.bazel.build/modules/pybind11_bazel/2.12.0/MODULE.bazel": "e6f4c20442eaa7c90d7190d8dc539d0ab422f95c65a57cc59562170c58ae3d34", "https://bcr.bazel.build/modules/pybind11_bazel/2.12.0/source.json": "6900fdc8a9e95866b8c0d4ad4aba4d4236317b5c1cd04c502df3f0d33afed680", + "https://bcr.bazel.build/modules/pypackaging.bzl/0.4.0/MODULE.bazel": "5fd3c92b01d18cb6ac6fb9581b633d75e094c63b5673935b26182439a6e30a5e", + "https://bcr.bazel.build/modules/pypackaging.bzl/0.4.0/source.json": "3d3aaa5de7e63fb1ab9953a60ddf7ade2183947003d37c1d5cc861b4f3278c5d", "https://bcr.bazel.build/modules/re2/2023-09-01/MODULE.bazel": "cb3d511531b16cfc78a225a9e2136007a48cf8a677e4264baeab57fe78a80206", "https://bcr.bazel.build/modules/re2/2024-07-02.bcr.1/MODULE.bazel": "b4963dda9b31080be1905ef085ecd7dd6cd47c05c79b9cdf83ade83ab2ab271a", "https://bcr.bazel.build/modules/re2/2024-07-02.bcr.1/source.json": "2ff292be6ef3340325ce8a045ecc326e92cbfab47c7cbab4bd85d28971b97ac4", diff --git a/tests/pypi/pep508/env_tests.bzl b/tests/pypi/pep508/env_tests.bzl index cfd94a1b01..97524c47f2 100644 --- a/tests/pypi/pep508/env_tests.bzl +++ b/tests/pypi/pep508/env_tests.bzl @@ -7,7 +7,6 @@ _tests = [] def _test_env_defaults(env): got = pep508_env(os = "exotic", arch = "exotic", python_version = "3.1.1") - got.pop("_aliases") env.expect.that_dict(got).contains_exactly({ "implementation_name": "cpython", "implementation_version": "3.1.1", @@ -26,7 +25,6 @@ _tests.append(_test_env_defaults) def _test_env_freebsd(env): got = pep508_env(os = "freebsd", arch = "arm64", python_version = "3.1.1") - got.pop("_aliases") env.expect.that_dict(got).contains_exactly({ "implementation_name": "cpython", "implementation_version": "3.1.1", @@ -45,7 +43,6 @@ _tests.append(_test_env_freebsd) def _test_env_macos(env): got = pep508_env(os = "macos", arch = "arm64", python_version = "3.1.1") - got.pop("_aliases") env.expect.that_dict(got).contains_exactly({ "implementation_name": "cpython", "implementation_version": "3.1.1", diff --git a/tests/pypi/pep508/evaluate_tests.bzl b/tests/pypi/pep508/evaluate_tests.bzl index 7c7b5d8173..3b62cac715 100644 --- a/tests/pypi/pep508/evaluate_tests.bzl +++ b/tests/pypi/pep508/evaluate_tests.bzl @@ -15,7 +15,7 @@ load("@rules_testing//lib:test_suite.bzl", "test_suite") load("//python/private/pypi:pep508_env.bzl", pep508_env = "env") # buildifier: disable=bzl-visibility -load("//python/private/pypi:pep508_evaluate.bzl", "evaluate", "tokenize") # buildifier: disable=bzl-visibility +load("//python/private/pypi:pep508_evaluate.bzl", "evaluate") # buildifier: disable=bzl-visibility _tests = [] @@ -25,39 +25,6 @@ def _check_evaluate(env, expr, expected, values, strict = True): values = values, ).that_bool(evaluate(expr, env = values, strict = strict)).equals(expected) -def _tokenize_tests(env): - for input, want in { - "": [], - "'osx' == os_name": ['"osx"', "==", "os_name"], - "'x' not in os_name": ['"x"', "not in", "os_name"], - "()": ["(", ")"], - "(os_name == 'osx' and not os_name == 'posix') or os_name == \"win\"": [ - "(", - "os_name", - "==", - '"osx"', - "and", - "not", - "os_name", - "==", - '"posix"', - ")", - "or", - "os_name", - "==", - '"win"', - ], - "os_name\t==\t'osx'": ["os_name", "==", '"osx"'], - "os_name == 'osx'": ["os_name", "==", '"osx"'], - "python_version <= \"1.0\"": ["python_version", "<=", '"1.0"'], - "python_version>='1.0.0'": ["python_version", ">=", '"1.0.0"'], - "python_version~='1.0.0'": ["python_version", "~=", '"1.0.0"'], - }.items(): - got = tokenize(input) - env.expect.that_collection(got).contains_exactly(want).in_order() - -_tests.append(_tokenize_tests) - def _evaluate_non_version_env_tests(env): for var_name in [ "implementation_name", @@ -100,7 +67,7 @@ def _evaluate_version_env_tests(env): for var_name in [ "python_version", "implementation_version", - "platform_version", + "platform_release", "python_full_version", ]: # Given @@ -124,7 +91,7 @@ def _evaluate_version_env_tests(env): "{} ~= '3.8.0'".format(var_name): False, "{} === '3.7.9+rc2'".format(var_name): False, "{} === '3.7.9'".format(var_name): True, - "{} == '3.7.9+rc2'".format(var_name): True, + "{} == '3.7.9+rc2'".format(var_name): False, }.items(): # buildifier: @unsorted-dict-items _check_evaluate(env, input, want, marker_env) @@ -156,28 +123,19 @@ def _logical_expression_tests(env): for input, want in { # Basic "": True, - "(())": True, - "()": True, # expr "os_name == 'fo'": False, "(os_name == 'fo')": False, "((os_name == 'fo'))": False, "((os_name == 'foo'))": True, - "not (os_name == 'fo')": True, # and "os_name == 'fo' and os_name == 'foo'": False, - # and not - "os_name == 'fo' and not os_name == 'foo'": False, - # or "os_name == 'oo' or os_name == 'foo'": True, - # or not - "os_name == 'foo' or not os_name == 'foo'": True, - # multiple or "os_name == 'oo' or os_name == 'fo' or os_name == 'foo'": True, "os_name == 'oo' or os_name == 'foo' or os_name == 'fo'": True, @@ -185,30 +143,25 @@ def _logical_expression_tests(env): # multiple and "os_name == 'foo' and os_name == 'foo' and os_name == 'fo'": False, - # x or not y and z != (x or not y), but is instead evaluated as x or (not y and z) - "os_name == 'foo' or not os_name == 'fo' and os_name == 'fo'": True, - # x or y and z != (x or y) and z, but is instead evaluated as x or (y and z) "os_name == 'foo' or os_name == 'fo' and os_name == 'fo'": True, - "not (os_name == 'foo' or os_name == 'fo' and os_name == 'fo')": False, + "(os_name == 'foo' or os_name == 'fo') and os_name == 'fo'": False, # x or y and z and w != (x or y and z) and w, but is instead evaluated as x or (y and z and w) "os_name == 'foo' or os_name == 'fo' and os_name == 'fo' and os_name == 'fo'": True, - - # not not True - "not not os_name == 'foo'": True, - "not not not os_name == 'foo'": False, }.items(): # buildifier: @unsorted-dict-items _check_evaluate(env, input, want, {"os_name": "foo"}) - if not input.strip("()"): - # These cases will just return True, because they will be evaluated - # and the brackets will be processed. + if not input: continue # Check that the non-strict eval gives us back the input when no env # is supplied. - _check_evaluate(env, input, input.replace("'", '"'), {}, strict = False) + want = input.replace("'", '"') + if " and " not in want and " or " not in want: + # The redundant parentheses are dropped + want = want.strip("()") + _check_evaluate(env, input, want, {}, strict = False) _tests.append(_logical_expression_tests) @@ -223,11 +176,11 @@ def _evaluate_partial_only_extra(env): "platform_system == 'aarch64' and os_name == 'osx' and extra == 'foo'": "platform_system == \"aarch64\" and os_name == \"osx\"", "platform_system == 'aarch64' and extra == 'foo' and os_name == 'osx'": "platform_system == \"aarch64\" and os_name == \"osx\"", "os_name == 'osx' or extra == 'bar'": "os_name == \"osx\"", - "os_name == 'osx' or extra == 'foo'": "", + "os_name == 'osx' or extra == 'foo'": True, "extra == 'bar' or os_name == 'osx'": "os_name == \"osx\"", - "extra == 'foo' or os_name == 'osx'": "", + "extra == 'foo' or os_name == 'osx'": True, "os_name == 'win' or extra == 'bar' or os_name == 'osx'": "os_name == \"win\" or os_name == \"osx\"", - "os_name == 'win' or extra == 'foo' or os_name == 'osx'": "", + "os_name == 'win' or extra == 'foo' or os_name == 'osx'": True, }.items(): # buildifier: @unsorted-dict-items got = evaluate( input, @@ -277,6 +230,38 @@ def _evaluate_with_aliases(env): _tests.append(_evaluate_with_aliases) +def _evaluate_with_aliases_in_env(env): + # The `platform_machine` of the env may be an alias as well, e.g. when it + # comes from the host platform. + for machine, tests in { + "amd64": { + "platform_machine != 'amd64'": False, + "platform_machine == 'amd64'": True, + "platform_machine == 'arm64'": False, + "platform_machine == 'x86_64'": True, + }, + "arm64": { + "'arm64' == platform_machine": True, + "platform_machine != 'arm64'": False, + "platform_machine == 'aarch64'": True, + "platform_machine == 'arm64'": True, + "platform_machine == 'x86_64'": False, + }, + }.items(): + for input, want in tests.items(): + _check_evaluate(env, input, want, {"platform_machine": machine}) + + # The partial evaluation gives the same result. + _check_evaluate( + env, + input, + want, + {"platform_machine": machine}, + strict = False, + ) + +_tests.append(_evaluate_with_aliases_in_env) + def _expr_case(expr, want, env): return struct(expr = expr.strip(), want = want, env = env) @@ -294,8 +279,13 @@ _MISC_EXPRESSIONS = [ _expr_case('python_version > "1.7.post2"', True, {"python_version": "1.7.1"}), _expr_case('python_version > "1.7.post2"', True, {"python_version": "1.7.post3"}), _expr_case('python_version > "1.7.post2"', False, {"python_version": "1.7.0"}), + # The local versions cannot be used with the ordered comparisons _expr_case('python_version > "1.7.1+local"', False, {"python_version": "1.7.1"}), - _expr_case('python_version > "1.7.1+local"', True, {"python_version": "1.7.2"}), + _expr_case( + 'python_version > "1.7.1+local"', + False, + {"python_version": "1.7.2"}, + ), # Extra cases for the '<' operator _expr_case('python_version < "1.7.1"', False, {"python_version": "1.7.2"}), _expr_case('python_version < "1.7.3"', True, {"python_version": "1.7.2"}), 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)