From c8b1d07485f69fe3097092b79b92037236f03519 Mon Sep 17 00:00:00 2001 From: Ignas Anikevicius <240938+aignas@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:36:14 +0900 Subject: [PATCH 1/2] refactor: remove version.bzl All of the users have been migrated to `pypackaging.bzl`, so the hand written PEP 440 implementation and its tests can be removed. --- python/private/BUILD.bazel | 6 - python/private/version.bzl | 908 --------------------------------- tests/version/BUILD.bazel | 3 - tests/version/version_test.bzl | 165 ------ 4 files changed, 1082 deletions(-) delete mode 100644 python/private/version.bzl delete mode 100644 tests/version/BUILD.bazel delete mode 100644 tests/version/version_test.bzl diff --git a/python/private/BUILD.bazel b/python/private/BUILD.bazel index ba71c9f180..0821c4ae3e 100644 --- a/python/private/BUILD.bazel +++ b/python/private/BUILD.bazel @@ -81,7 +81,6 @@ exports_files( "coverage.patch", "py_package.bzl", "py_wheel.bzl", - "version.bzl", "reexports.bzl", "stamp_impl.bzl", "util.bzl", @@ -1057,11 +1056,6 @@ bzl_library( srcs = ["toolchain_types.bzl"], ) -bzl_library( - name = "version", - srcs = ["version.bzl"], -) - bzl_library( name = "version_label", srcs = ["version_label.bzl"], diff --git a/python/private/version.bzl b/python/private/version.bzl deleted file mode 100644 index b13327841b..0000000000 --- a/python/private/version.bzl +++ /dev/null @@ -1,908 +0,0 @@ -# Copyright 2023 The Bazel Authors. All rights reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"Implementation of PEP440 version string normalization" - -def mkmethod(self, method): - """Bind a struct as the first arg to a function. - - This is loosely equivalent to creating a bound method of a class. - """ - return lambda *args, **kwargs: method(self, *args, **kwargs) - -def _isdigit(token): - return token.isdigit() - -def _isalnum(token): - return token.isalnum() - -def _lower(token): - # PEP 440: Case sensitivity - return token.lower() - -def _is(reference): - """Predicate testing a token for equality with `reference`.""" - return lambda token: token == reference - -def _is_not(reference): - """Predicate testing a token for inequality with `reference`.""" - return lambda token: token != reference - -def _in(reference): - """Predicate testing if a token is in the list `reference`.""" - return lambda token: token in reference - -def _ctx(start): - """Creates a context, which is state for parsing (or sub-parsing).""" - return { - # The result value from parsing - "norm": "", - # Where in the parser's input string this context starts. - "start": start, - } - -def _open_context(self): - """Open an new parsing ctx. - - If the current parsing step succeeds, call self.accept(). - If the current parsing step fails, call self.discard() to - go back to how it was before we opened a new ctx. - - Args: - self: The normalizer. - """ - self.contexts.append(_ctx(_context(self)["start"])) - return self.contexts[-1] - -def _accept(self, key = None): - """Close the current ctx successfully and merge the results. - - Args: - self: {type}`Parser} - key: {type}`str | None` the key to store the result in - the most recent context. If not set, the key is "norm". - - Returns: - {type}`bool` always True - """ - finished = self.contexts.pop() - self.contexts[-1]["norm"] += finished["norm"] - if key: - self.contexts[-1][key] = finished["norm"] - - self.contexts[-1]["start"] = finished["start"] - return True - -def _context(self): - return self.contexts[-1] - -def _discard(self, key = None): - self.contexts.pop() - if key: - self.contexts[-1][key] = "" - return False - -def _new(input): - """Create a new parser - - Args: - input: {type}`str` input to parse - - Returns: - {type}`Parser` a struct for a parser object. - """ - self = struct( - input = input, - contexts = [_ctx(0)], - ) - - public = struct( - # methods: keep sorted - accept = mkmethod(self, _accept), - context = mkmethod(self, _context), - discard = mkmethod(self, _discard), - open_context = mkmethod(self, _open_context), - - # attributes: keep sorted - input = self.input, - ) - return public - -def accept(parser, predicate, value): - """If `predicate` matches the next token, accept the token. - - Accepting the token means adding it (according to `value`) to - the running results maintained in ctx["norm"] and - advancing the cursor in ctx["start"] to the next token in - `version`. - - Args: - parser: The normalizer. - predicate: function taking a token and returning a boolean - saying if we want to accept the token. - value: the string to add if there's a match, or, if `value` - is a function, the function to apply to the current token - to get the string to add. - - Returns: - whether a token was accepted. - """ - - ctx = parser.context() - - if ctx["start"] >= len(parser.input): - return False - - token = parser.input[ctx["start"]] - - if predicate(token): - if type(value) in ["function", "builtin_function_or_method"]: - value = value(token) - - ctx["norm"] += value - ctx["start"] += 1 - return True - - return False - -def accept_placeholder(parser): - """Accept a Bazel placeholder. - - Placeholders aren't actually part of PEP 440, but are used for - stamping purposes. A placeholder might be - ``{BUILD_TIMESTAMP}``, for instance. We'll accept these as - they are, assuming they will expand to something that makes - sense where they appear. Before the stamping has happened, a - resulting wheel file name containing a placeholder will not - actually be valid. - - Args: - parser: The normalizer. - - Returns: - whether a placeholder was accepted. - """ - ctx = parser.open_context() - - if not accept(parser, _is("{"), str): - return parser.discard() - - start = ctx["start"] - for _ in range(start, len(parser.input) + 1): - if not accept(parser, _is_not("}"), str): - break - - if not accept(parser, _is("}"), str): - return parser.discard() - - return parser.accept() - -def accept_digits(parser): - """Accept multiple digits (or placeholders), up to a non-digit/placeholder. - - Args: - parser: The normalizer. - - Returns: - whether some digits (or placeholders) were accepted. - """ - - ctx = parser.open_context() - start = ctx["start"] - - for i in range(start, len(parser.input) + 1): - if not accept(parser, _isdigit, str) and not accept_placeholder(parser): - if i - start >= 1: - if ctx["norm"].isdigit(): - # PEP 440: Integer Normalization - ctx["norm"] = str(int(ctx["norm"])) - return parser.accept() - break - - return parser.discard() - -def accept_string(parser, string, replacement): - """Accept a `string` in the input. Output `replacement`. - - Args: - parser: The normalizer. - string: The string to search for in the parser input. - replacement: The normalized string to use if the string was found. - - Returns: - whether the string was accepted. - """ - ctx = parser.open_context() - - for character in string.elems(): - if not accept(parser, _in([character, character.upper()]), ""): - return parser.discard() - - ctx["norm"] = replacement - - return parser.accept() - -def accept_alnum(parser): - """Accept an alphanumeric sequence. - - Args: - parser: The normalizer. - - Returns: - whether an alphanumeric sequence was accepted. - """ - - ctx = parser.open_context() - start = ctx["start"] - - for i in range(start, len(parser.input) + 1): - if not accept(parser, _isalnum, _lower) and not accept_placeholder(parser): - if i - start >= 1: - return parser.accept() - break - - return parser.discard() - -def accept_dot_number(parser): - """Accept a dot followed by digits. - - Args: - parser: The normalizer. - - Returns: - whether a dot+digits pair was accepted. - """ - parser.open_context() - - if accept(parser, _is("."), ".") and accept_digits(parser): - return parser.accept() - else: - return parser.discard() - -def accept_dot_number_sequence(parser): - """Accept a sequence of dot+digits. - - Args: - parser: The normalizer. - - Returns: - whether a sequence of dot+digits pairs was accepted. - """ - ctx = parser.context() - start = ctx["start"] - i = start - - for i in range(start, len(parser.input) + 1): - if not accept_dot_number(parser): - break - return i - start >= 1 - -def accept_separator_alnum(parser): - """Accept a separator followed by an alphanumeric string. - - Args: - parser: The normalizer. - - Returns: - whether a separator and an alphanumeric string were accepted. - """ - ctx = parser.open_context() - - # PEP 440: Local version segments - if not accept(parser, _in([".", "-", "_"]), "."): - return parser.discard() - - if accept_alnum(parser): - # First character is separator; skip it. - value = ctx["norm"][1:] - - # PEP 440: Integer Normalization - if value.isdigit(): - value = str(int(value)) - ctx["norm"] = ctx["norm"][0] + value - return parser.accept() - - return parser.discard() - -def accept_separator_alnum_sequence(parser): - """Accept a sequence of separator+alphanumeric. - - Args: - parser: The normalizer. - - Returns: - whether a sequence of separator+alphanumerics was accepted. - """ - ctx = parser.context() - start = ctx["start"] - i = start - - for i in range(start, len(parser.input) + 1): - if not accept_separator_alnum(parser): - break - - return i - start >= 1 - -def accept_epoch(parser): - """PEP 440: Version epochs. - - Args: - parser: The normalizer. - - Returns: - whether a PEP 440 epoch identifier was accepted. - """ - ctx = parser.open_context() - if accept_digits(parser) and accept(parser, _is("!"), "!"): - if ctx["norm"] == "0!": - ctx["norm"] = "" - return parser.accept("epoch") - else: - return parser.discard("epoch") - -def accept_release(parser): - """Accept the release segment, numbers separated by dots. - - Args: - parser: The normalizer. - - Returns: - whether a release segment was accepted. - """ - parser.open_context() - - if not accept_digits(parser): - return parser.discard("release") - - accept_dot_number_sequence(parser) - return parser.accept("release") - -def accept_pre_l(parser): - """PEP 440: Pre-release spelling. - - Args: - parser: The normalizer. - - Returns: - whether a prerelease keyword was accepted. - """ - parser.open_context() - - if ( - accept_string(parser, "alpha", "a") or - accept_string(parser, "a", "a") or - accept_string(parser, "beta", "b") or - accept_string(parser, "b", "b") or - accept_string(parser, "c", "rc") or - accept_string(parser, "preview", "rc") or - accept_string(parser, "pre", "rc") or - accept_string(parser, "rc", "rc") - ): - return parser.accept() - else: - return parser.discard() - -def accept_prerelease(parser): - """PEP 440: Pre-releases. - - Args: - parser: The normalizer. - - Returns: - whether a prerelease identifier was accepted. - """ - ctx = parser.open_context() - - # PEP 440: Pre-release separators - accept(parser, _in(["-", "_", "."]), "") - - if not accept_pre_l(parser): - return parser.discard("pre") - - accept(parser, _in(["-", "_", "."]), "") - - if not accept_digits(parser): - # PEP 440: Implicit pre-release number - ctx["norm"] += "0" - - return parser.accept("pre") - -def accept_implicit_postrelease(parser): - """PEP 440: Implicit post releases. - - Args: - parser: The normalizer. - - Returns: - whether an implicit postrelease identifier was accepted. - """ - ctx = parser.open_context() - - if accept(parser, _is("-"), "") and accept_digits(parser): - ctx["norm"] = ".post" + ctx["norm"] - return parser.accept() - - return parser.discard() - -def accept_explicit_postrelease(parser): - """PEP 440: Post-releases. - - Args: - parser: The normalizer. - - Returns: - whether an explicit postrelease identifier was accepted. - """ - ctx = parser.open_context() - - # PEP 440: Post release separators - if not accept(parser, _in(["-", "_", "."]), "."): - ctx["norm"] += "." - - # PEP 440: Post release spelling - if ( - accept_string(parser, "post", "post") or - accept_string(parser, "rev", "post") or - accept_string(parser, "r", "post") - ): - accept(parser, _in(["-", "_", "."]), "") - - if not accept_digits(parser): - # PEP 440: Implicit post release number - ctx["norm"] += "0" - - return parser.accept() - - return parser.discard() - -def accept_postrelease(parser): - """PEP 440: Post-releases. - - Args: - parser: The normalizer. - - Returns: - whether a postrelease identifier was accepted. - """ - parser.open_context() - - if accept_implicit_postrelease(parser) or accept_explicit_postrelease(parser): - return parser.accept("post") - - return parser.discard("post") - -def accept_devrelease(parser): - """PEP 440: Developmental releases. - - Args: - parser: The normalizer. - - Returns: - whether a developmental release identifier was accepted. - """ - ctx = parser.open_context() - - # PEP 440: Development release separators - if not accept(parser, _in(["-", "_", "."]), "."): - ctx["norm"] += "." - - if accept_string(parser, "dev", "dev"): - accept(parser, _in(["-", "_", "."]), "") - - if not accept_digits(parser): - # PEP 440: Implicit development release number - ctx["norm"] += "0" - - return parser.accept("dev") - - return parser.discard("dev") - -def accept_local(parser): - """PEP 440: Local version identifiers. - - Args: - parser: The normalizer. - - Returns: - whether a local version identifier was accepted. - """ - parser.open_context() - - if accept(parser, _is("+"), "+") and accept_alnum(parser): - accept_separator_alnum_sequence(parser) - return parser.accept("local") - - return parser.discard("local") - -def normalize_pep440(version): - """Escape the version component of a filename. - - See https://packaging.python.org/en/latest/specifications/binary-distribution-format/#escaping-and-unicode - and https://peps.python.org/pep-0440/ - - Args: - version: version string to be normalized according to PEP 440. - - Returns: - string containing the normalized version. - """ - return _parse(version, strict = True)["norm"] - -def _parse(version_str, strict = True, _fail = fail): - """Escape the version component of a filename. - - See https://packaging.python.org/en/latest/specifications/binary-distribution-format/#escaping-and-unicode - and https://peps.python.org/pep-0440/ - - Args: - version_str: version string to be normalized according to PEP 440. - strict: fail if the version is invalid, defaults to True. - _fail: Used for tests - - Returns: - string containing the normalized version. - """ - - # https://packaging.python.org/en/latest/specifications/version-specifiers/#leading-and-trailing-whitespace - version = version_str.strip() - is_prefix = False - - if not strict: - is_prefix = version.endswith(".*") - version = version.strip(" .*") # PEP 440: Leading and Trailing Whitespace and ".*" - - parser = _new(version) - accept(parser, _is("v"), "") # PEP 440: Preceding v character - accept_epoch(parser) - accept_release(parser) - accept_prerelease(parser) - accept_postrelease(parser) - accept_devrelease(parser) - accept_local(parser) - - parser_ctx = parser.context() - if parser.input[parser_ctx["start"]:]: - if strict: - _fail( - "Failed to parse PEP 440 version identifier '%s'." % parser.input, - "Parse error at '%s'" % parser.input[parser_ctx["start"]:], - ) - - return None - - parser_ctx["is_prefix"] = is_prefix - return parser_ctx - -def parse(version_str, strict = False, _fail = fail): - """Parse a PEP4408 compliant version. - - This is similar to `normalize_pep440`, but it parses individual components to - comparable types. - - Args: - version_str: version string to be normalized according to PEP 440. - strict: fail if the version is invalid. - _fail: used for tests - - Returns: - a struct with individual components of a version: - * `epoch` {type}`int`, defaults to `0` - * `release` {type}`tuple[int]` an n-tuple of ints - * `pre` {type}`tuple[str, int] | None` a tuple of a string and an int, - e.g. ("a", 1) - * `post` {type}`tuple[str, int] | None` a tuple of a string and an int, - e.g. ("~", 1) - * `dev` {type}`tuple[str, int] | None` a tuple of a string and an int, - e.g. ("", 1) - * `local` {type}`tuple[str, int] | None` a tuple of components in the local - version, e.g. ("abc", 123). - * `is_prefix` {type}`bool` whether the version_str ends with `.*`. - * `string` {type}`str` normalized value of the input. - """ - - parts = _parse(version_str, strict = strict, _fail = _fail) - if not parts: - return None - - if parts["is_prefix"] and (parts["local"] or parts["post"] or parts["dev"] or parts["pre"]): - if strict: - _fail("local version part has been obtained, but only public segments can have prefix matches") - - # https://peps.python.org/pep-0440/#public-version-identifiers - return None - - # buildifier: disable=uninitialized - self = struct( - epoch = _parse_epoch(parts["epoch"], _fail), - release = _parse_release(parts["release"]), - pre = _parse_pre(parts["pre"]), - post = _parse_post(parts["post"], _fail), - dev = _parse_dev(parts["dev"], _fail), - local = _parse_local(parts["local"], _fail), - string = parts["norm"], - is_prefix = parts["is_prefix"], - key = lambda *a, **k: _version_key(self, *a, **k), - ) - return self - -def _parse_epoch(value, fail): - if not value: - return 0 - - if not value.endswith("!"): - fail("epoch string segment needs to end with '!', got: {}".format(value)) - - return int(value[:-1]) - -def _parse_release(value): - return tuple([int(d) for d in value.split(".")]) - -def _parse_local(value, fail): - if not value: - return None - - if not value.startswith("+"): - fail("local release identifier must start with '+', got: {}".format(value)) - - # If the part is numerical, handle it as a number - return tuple([int(part) if part.isdigit() else part for part in value[1:].split(".")]) - -def _parse_dev(value, fail): - if not value: - return None - - if not value.startswith(".dev"): - fail("dev release identifier must start with '.dev', got: {}".format(value)) - dev = int(value[len(".dev"):]) - - # Empty string goes first when comparing - return ("", dev) - -def _parse_pre(value): - if not value: - return None - - if value.startswith("rc"): - prefix = "rc" - else: - prefix = value[0] - - return (prefix, int(value[len(prefix):])) - -def _parse_post(value, fail): - if not value: - return None - - if not value.startswith(".post"): - fail("post release identifier must start with '.post', got: {}".format(value)) - post = int(value[len(".post"):]) - - # We choose `~` since almost all of the ASCII characters will be before - # it. Use `ord` and `chr` functions to find a good value. - return ("~", post) - -def _pad_zeros(release, n): - padding = n - len(release) - if padding <= 0: - return release - - release = list(release) + [0] * padding - return tuple(release) - -def _prefix_err(left, op, right): - if left.is_prefix or right.is_prefix: - fail("PEP440: only '==' and '!=' operators can use prefix matching: {} {} {}".format( - left.string, - op, - right.string, - )) - -def _version_eeq(left, right): - """=== operator""" - if left.is_prefix or right.is_prefix: - fail(_prefix_err(left, "===", right)) - - # https://peps.python.org/pep-0440/#arbitrary-equality - # > simple string equality operations - return left.string == right.string - -def _version_eq(left, right): - """== operator""" - is_prefix = _is_prefix(left, right) - if is_prefix != None: - return is_prefix - - if left.epoch != right.epoch: - return False - - release_len = max(len(left.release), len(right.release)) - left_release = _pad_zeros(left.release, release_len) - right_release = _pad_zeros(right.release, release_len) - - if left_release != right_release: - return False - - return ( - left.pre == right.pre and - left.post == right.post and - left.dev == right.dev - # local is ignored for == checks - ) - -def _is_prefix(left, right): - if left.is_prefix and right.is_prefix: - fail("Invalid comparison: both versions cannot be prefix matching") - if left.is_prefix: - return _left_is_prefix(left, right) - if right.is_prefix: - return _left_is_prefix(right, left) - - return None - -def _left_is_prefix(left, right): - if right.string.startswith("{}.".format(left.string)): - return True - - # There is a chance that we are comparing 1.3 ~= 1.3.0 - # - # In that case the logic would be to normalize 1.3 to 1.3.0 and then - # the above would work, but we end up comparing 1.3 with 1.3. above - # and it fails. - return _version_key(left) == _version_key(right) - -def _version_compatible(left, right): - """~= operator""" - if left.is_prefix or right.is_prefix: - fail(_prefix_err(left, "~=", right)) - - # https://peps.python.org/pep-0440/#compatible-release - # Note, the ~= operator can be also expressed as: - # >= V.N, == V.* - - right_star = ".".join([str(d) for d in right.release[:-1]]) - if right.epoch: - right_star = "{}!{}.*".format(right.epoch, right_star) - else: - right_star = "{}.*".format(right_star) - - return _version_ge(left, right) and _is_prefix(left, parse(right_star, strict = False)) - -def _version_ne(left, right): - """!= operator""" - return not _version_eq(left, right) - -def _version_lt(left, right): - """< operator""" - if left.is_prefix or right.is_prefix: - fail(_prefix_err(left, "<", right)) - - if left.epoch > right.epoch: - return False - elif left.epoch < right.epoch: - return True - - release_len = max(len(left.release), len(right.release)) - left_release = _pad_zeros(left.release, release_len) - right_release = _pad_zeros(right.release, release_len) - - if left_release > right_release: - return False - elif left_release < right_release: - return True - - # From PEP440, this is not a simple ordering check and we need to check the version - # semantically: - # * The exclusive ordered comparison operator""" - if left.is_prefix or right.is_prefix: - fail(_prefix_err(left, ">", right)) - - if left.epoch > right.epoch: - return True - elif left.epoch < right.epoch: - return False - - release_len = max(len(left.release), len(right.release)) - left_release = _pad_zeros(left.release, release_len) - right_release = _pad_zeros(right.release, release_len) - - if left_release > right_release: - return True - elif left_release < right_release: - return False - - # From PEP440, this is not a simple ordering check and we need to check the version - # semantically: - # * The exclusive ordered comparison >V MUST NOT allow a post-release of the given version - # unless V itself is a post release. - # - # * The exclusive ordered comparison >V MUST NOT match a local version of the specified - # version. - - if left.post and right.post: - return left.post > right.post - else: - # ignore the left.post if right is not a post if right is a post, then this evaluates to - # False anyway. - return False - -def _version_le(left, right): - """<= operator""" - if left.is_prefix or right.is_prefix: - fail(_prefix_err(left, "<=", right)) - - # PEP440: simple order check - # https://peps.python.org/pep-0440/#inclusive-ordered-comparison - _left = _version_key(left, local = False) - _right = _version_key(right, local = False) - return _left < _right or _version_eq(left, right) - -def _version_ge(left, right): - """>= operator""" - if left.is_prefix or right.is_prefix: - fail(_prefix_err(left, ">=", right)) - - # PEP440: simple order check - # https://peps.python.org/pep-0440/#inclusive-ordered-comparison - _left = _version_key(left, local = False) - _right = _version_key(right, local = False) - return _left > _right or _version_eq(left, right) - -def _version_key(self, *, local = True): - """This function returns a tuple that can be used in 'sorted' calls. - - This implements the PEP440 version sorting. - """ - release_key = ("z",) - local = self.local if local else [] - local = local or [] - - return ( - self.epoch, - self.release, - # PEP440 Within a pre-release, post-release or development release segment with - # a shared prefix, ordering MUST be by the value of the numeric component. - # PEP440 release ordering: .devN, aN, bN, rcN, , .postN - # We choose to first match the pre-release, then post release, then dev and - # then stable - self.pre or self.post or self.dev or release_key, - # PEP440 local versions go before post versions - tuple([(type(item) == "int", item) for item in local]), - # PEP440 - pre-release ordering: .devN, , .postN - self.post or self.dev or release_key, - # PEP440 - post release ordering: .devN, - self.dev or release_key, - ) - -version = struct( - normalize = normalize_pep440, - parse = parse, - # methods, keep sorted - key = _version_key, - is_compatible = _version_compatible, - is_eq = _version_eq, - is_eeq = _version_eeq, - is_ge = _version_ge, - is_gt = _version_gt, - is_le = _version_le, - is_lt = _version_lt, - is_ne = _version_ne, -) diff --git a/tests/version/BUILD.bazel b/tests/version/BUILD.bazel deleted file mode 100644 index d6fdecd4cf..0000000000 --- a/tests/version/BUILD.bazel +++ /dev/null @@ -1,3 +0,0 @@ -load(":version_test.bzl", "version_test_suite") - -version_test_suite(name = "version_tests") diff --git a/tests/version/version_test.bzl b/tests/version/version_test.bzl deleted file mode 100644 index 7ddb6cc851..0000000000 --- a/tests/version/version_test.bzl +++ /dev/null @@ -1,165 +0,0 @@ -"" - -load("@rules_testing//lib:analysis_test.bzl", "test_suite") -load("//python/private:version.bzl", "version") # buildifier: disable=bzl-visibility - -_tests = [] - -def _test_normalization(env): - prefixes = ["v", " v", " \t\r\nv"] - epochs = { - "": ["", "0!", "00!"], - "1!": ["1!", "001!"], - "200!": ["200!", "00200!"], - } - releases = { - "0.1": ["0.1", "0.01"], - "2023.7.19": ["2023.7.19", "2023.07.19"], - } - pres = { - "": [""], - "a0": ["a", ".a", "-ALPHA0", "_alpha0", ".a0"], - "a4": ["alpha4", ".a04"], - "b0": ["b", ".b", "-BETA0", "_beta0", ".b0"], - "b5": ["beta05", ".b5"], - "rc0": ["C", "_c0", "RC", "_rc0", "-preview_0"], - } - explicit_posts = { - "": [""], - ".post0": [], - ".post1": [".post1", "-r1", "_rev1"], - } - implicit_posts = [[".post1", "-1"], [".post2", "-2"]] - devs = { - "": [""], - ".dev0": ["dev", "-DEV", "_Dev-0"], - ".dev9": ["DEV9", ".dev09", ".dev9"], - ".dev{BUILD_TIMESTAMP}": [ - "-DEV{BUILD_TIMESTAMP}", - "_dev_{BUILD_TIMESTAMP}", - ], - } - locals = { - "": [""], - "+ubuntu.7": ["+Ubuntu_7", "+ubuntu-007"], - "+ubuntu.r007": ["+Ubuntu_R007"], - } - epochs = [ - [normalized_epoch, input_epoch] - for normalized_epoch, input_epochs in epochs.items() - for input_epoch in input_epochs - ] - releases = [ - [normalized_release, input_release] - for normalized_release, input_releases in releases.items() - for input_release in input_releases - ] - pres = [ - [normalized_pre, input_pre] - for normalized_pre, input_pres in pres.items() - for input_pre in input_pres - ] - explicit_posts = [ - [normalized_post, input_post] - for normalized_post, input_posts in explicit_posts.items() - for input_post in input_posts - ] - pres_and_posts = [ - [normalized_pre + normalized_post, input_pre + input_post] - for normalized_pre, input_pre in pres - for normalized_post, input_post in explicit_posts - ] + [ - [normalized_pre + normalized_post, input_pre + input_post] - for normalized_pre, input_pre in pres - for normalized_post, input_post in implicit_posts - if input_pre == "" or input_pre[-1].isdigit() - ] - devs = [ - [normalized_dev, input_dev] - for normalized_dev, input_devs in devs.items() - for input_dev in input_devs - ] - locals = [ - [normalized_local, input_local] - for normalized_local, input_locals in locals.items() - for input_local in input_locals - ] - postfixes = ["", " ", " \t\r\n"] - i = 0 - for nepoch, iepoch in epochs: - for nrelease, irelease in releases: - for nprepost, iprepost in pres_and_posts: - for ndev, idev in devs: - for nlocal, ilocal in locals: - prefix = prefixes[i % len(prefixes)] - postfix = postfixes[(i // len(prefixes)) % len(postfixes)] - env.expect.that_str( - version.normalize( - prefix + iepoch + irelease + iprepost + - idev + ilocal + postfix, - ), - ).equals( - nepoch + nrelease + nprepost + ndev + nlocal, - ) - i += 1 - -_tests.append(_test_normalization) - -def _test_normalize_local(env): - # Verify a local with a [digit][non-digit] sequence parses ok - in_str = "0.1.0+brt.9e" - actual = version.normalize(in_str) - env.expect.that_str(actual).equals(in_str) - -_tests.append(_test_normalize_local) - -def _test_ordering(env): - want = [ - # Taken from https://peps.python.org/pep-0440/#summary-of-permitted-suffixes-and-relative-ordering - "1.dev0", - "1.0.dev456", - "1.0a1", - "1.0a2.dev456", - "1.0a12.dev456", - "1.0a12", - "1.0b1.dev456", - "1.0b1.dev457", - "1.0b2", - "1.0b2.post345.dev456", - "1.0b2.post345.dev457", - "1.0b2.post345", - "1.0rc1.dev456", - "1.0rc1", - "1.0", - "1.0+abc.5", - "1.0+abc.7", - "1.0+5", - "1.0.post456.dev34", - "1.0.post456", - "1.0.15", - "1.1.dev1", - "1!0.1", - ] - - for lower, higher in zip(want[:-1], want[1:]): - lower = version.parse(lower, strict = True) - higher = version.parse(higher, strict = True) - - lower_key = version.key(lower) - higher_key = version.key(higher) - - if not lower_key < higher_key: - env.fail("Expected '{}'.key() to be smaller than '{}'.key(), but got otherwise: {} > {}".format( - lower.string, - higher.string, - lower_key, - higher_key, - )) - -_tests.append(_test_ordering) - -def version_test_suite(name): - test_suite( - name = name, - basic_tests = _tests, - ) From 2cba4dd718c89f9d0a754dedd319b7a7b07efdb0 Mon Sep 17 00:00:00 2001 From: Ignas Anikevicius <240938+aignas@users.noreply.github.com> Date: Sun, 22 Nov 2026 10:40:19 +0900 Subject: [PATCH 2/2] refactor: do not parse the versions in the files autoloaded by Bazel 8 Bazel 8 autoloads the Python rules and providers from `rules_python` and the files that it loads for that can only load `.bzl` files from a fixed list of repositories, otherwise the build fails with `Cycle caused by autoloads`. This means that `py_library.bzl` and `py_runtime_rule.bzl` cannot use a version parser from a different repository, e.g. `pypackaging.bzl`, and they are the reason why `version.bzl` cannot be replaced with it. Neither of them needs a full PEP 440 parser: - `py_runtime` only needs the release numbers from the value of the `python_version` flag. - `py_library` only compares the versions of the same distribution for equality, so it now uses the version as it is spelled in the name of the `.dist-info` directory, which the installers already normalize. Add a test that checks that the autoloaded files only load from the repositories that Bazel allows. --- ...ist-info-version-not-normalized.changed.md | 3 + python/private/BUILD.bazel | 2 - python/private/py_info.bzl | 9 +- python/private/py_library.bzl | 7 +- python/private/py_runtime_rule.bzl | 17 ++-- tests/bazel_autoloads/BUILD.bazel | 3 + .../bazel_autoloads/bazel_autoloads_tests.bzl | 95 +++++++++++++++++++ tests/py_runtime/py_runtime_tests.bzl | 25 +++++ 8 files changed, 146 insertions(+), 15 deletions(-) create mode 100644 news/dist-info-version-not-normalized.changed.md create mode 100644 tests/bazel_autoloads/BUILD.bazel create mode 100644 tests/bazel_autoloads/bazel_autoloads_tests.bzl diff --git a/news/dist-info-version-not-normalized.changed.md b/news/dist-info-version-not-normalized.changed.md new file mode 100644 index 0000000000..8fa23f215e --- /dev/null +++ b/news/dist-info-version-not-normalized.changed.md @@ -0,0 +1,3 @@ +(rules) {obj}`VenvSymlinkEntry.version` is the version as it is spelled in the +name of the `.dist-info` directory and is no longer normalized by +`rules_python`. diff --git a/python/private/BUILD.bazel b/python/private/BUILD.bazel index 78e4c48cd2..8f43b08a51 100644 --- a/python/private/BUILD.bazel +++ b/python/private/BUILD.bazel @@ -627,7 +627,6 @@ bzl_library( ":rule_builders", ":toolchain_types", ":venv_runfiles", - ":version", "@bazel_skylib//lib:dicts", "@bazel_skylib//lib:paths", "@bazel_skylib//rules:common_settings", @@ -700,7 +699,6 @@ bzl_library( ":py_internal", ":py_runtime_info", ":reexports", - ":version", "@bazel_skylib//lib:dicts", "@bazel_skylib//lib:paths", "@bazel_skylib//rules:common_settings", diff --git a/python/private/py_info.bzl b/python/private/py_info.bzl index ead24ec978..c04cb26083 100644 --- a/python/private/py_info.bzl +++ b/python/private/py_info.bzl @@ -146,8 +146,13 @@ A path relative to the `kind` directory within the venv. "version": """ :type: str | None -Represents the PyPI package version that the code originates from. It is normalized according to the -PEP440 standard. +Represents the PyPI package version that the code originates from. It is the +version as it is spelled in the name of the `.dist-info` directory, which the +installers normalize according to the PEP440 standard. + +:::{versionchanged} VERSION_NEXT_PATCH +The version is no longer normalized by `rules_python`. +::: """, }, ) diff --git a/python/private/py_library.bzl b/python/private/py_library.bzl index 9b1e064853..b92402b8bf 100644 --- a/python/private/py_library.bzl +++ b/python/private/py_library.bzl @@ -51,7 +51,6 @@ load( TOOLCHAIN_TYPE = "TARGET_TOOLCHAIN_TYPE", ) load(":venv_runfiles.bzl", "get_venv_symlinks") -load(":version.bzl", "version") LIBRARY_ATTRS = dicts.add( COMMON_ATTRS, @@ -236,8 +235,8 @@ def get_package_and_version(data_files): Returns: {type}`tuple[str | None, str | None]` the distribution name, lowercased with runs of `-`, `_` and `.` turned into `_` (e.g. `google_cloud_storage`), - and the normalized version; `(None, None)` without a - `.dist-info/METADATA` file. + and the version as it is spelled in the name of the `.dist-info` + directory; `(None, None)` without a `.dist-info/METADATA` file. """ dist_info_metadata = None for d in data_files: @@ -260,7 +259,7 @@ def get_package_and_version(data_files): package, _, version_str = package.rpartition("-") return ( normalize_name(package), # will have no dashes - version.normalize(version_str), # will have no dashes either + version_str, # will have no dashes either ) def _get_imports_and_venv_symlinks(ctx): diff --git a/python/private/py_runtime_rule.bzl b/python/private/py_runtime_rule.bzl index 4f450c4c9b..6099d99848 100644 --- a/python/private/py_runtime_rule.bzl +++ b/python/private/py_runtime_rule.bzl @@ -21,7 +21,6 @@ load(":flags.bzl", "FreeThreadedFlag") load(":py_internal.bzl", "py_internal") load(":py_runtime_info.bzl", "DEFAULT_STUB_SHEBANG", "PyRuntimeInfo") load(":reexports.bzl", "BuiltinPyRuntimeInfo") -load(":version.bzl", "version") _py_builtins = py_internal @@ -467,11 +466,15 @@ def _is_singleton_depset(files): return _py_builtins.is_singleton_depset(files) def _interpreter_version_info_from_version_str(version_str): - v = version.parse(version_str) + # We only need the release numbers, e.g. `3.15.0` from `3.15.0rc1`. version_info = {} - parts = list(v.release) - for key in ("major", "minor", "micro"): - if not parts: - break - version_info[key] = parts.pop(0) + for key, part in zip(("major", "minor", "micro"), version_str.split(".")): + digits = "" + for c in part.elems(): + if not c.isdigit(): + break + digits += c + if not digits: + fail("Expected the Python version to be '[.[.]]', got: '{}'".format(version_str)) + version_info[key] = int(digits) return version_info diff --git a/tests/bazel_autoloads/BUILD.bazel b/tests/bazel_autoloads/BUILD.bazel new file mode 100644 index 0000000000..a7f2a95789 --- /dev/null +++ b/tests/bazel_autoloads/BUILD.bazel @@ -0,0 +1,3 @@ +load(":bazel_autoloads_tests.bzl", "bazel_autoloads_test_suite") + +bazel_autoloads_test_suite(name = "bazel_autoloads_tests") diff --git a/tests/bazel_autoloads/bazel_autoloads_tests.bzl b/tests/bazel_autoloads/bazel_autoloads_tests.bzl new file mode 100644 index 0000000000..bcd5ac068c --- /dev/null +++ b/tests/bazel_autoloads/bazel_autoloads_tests.bzl @@ -0,0 +1,95 @@ +"""Tests for the `.bzl` files that Bazel 8 autoloads from `rules_python`.""" + +load("@bazel_skylib//:bzl_library.bzl", "StarlarkLibraryInfo") +load("@rules_testing//lib:analysis_test.bzl", "analysis_test") +load("@rules_testing//lib:test_suite.bzl", "test_suite") + +# The `bzl_library` targets in `//python` of the files that Bazel 8 loads in +# order to autoload the Python rules and providers, see `AUTOLOAD_CONFIG` in +# https://github.com/bazelbuild/bazel/blob/release-8.9.0/src/main/java/com/google/devtools/build/lib/packages/AutoloadSymbols.java +_AUTOLOADED = [ + "py_binary", + "py_cc_link_params_info", + "py_info", + "py_library", + "py_runtime", + "py_runtime_info", + "py_test", +] + +# The repositories where Bazel 8 does not use the autoloads, see +# `PREDECLARED_REPOS_DISALLOWING_AUTOLOADS` in the file above. The repositories +# created by the module extensions of these modules are included, because +# only the part of the canonical name that is before the first `+` is used. +# +# A `.bzl` file from any other repository cannot be loaded by the autoloaded +# files, because Bazel would need the autoloaded symbols in order to load it, +# which is reported as `Cycle caused by autoloads`. The users can only work +# this around with the `--repositories_without_autoloads` flag. +_REPOS_WITHOUT_AUTOLOADS = { + # The main repository, i.e. `rules_python` itself + "": None, + "apple_support": None, + "bazel_features": None, + "bazel_features_globals": None, + "bazel_features_version": None, + "bazel_skylib": None, + "bazel_tools": None, + "build_bazel_apple_support": None, + "cc_compatibility_proxy": None, + "com_google_protobuf": None, + "compatibility_proxy": None, + "proto_bazel_features": None, + "protobuf": None, + "rules_android": None, + "rules_cc": None, + "rules_java": None, + "rules_java_builtin": None, + "rules_python": None, + "rules_python_internal": None, + "rules_shell": None, +} + +_tests = [] + +# NOTE: This is why the autoloaded files, e.g. `py_library.bzl` and +# `py_runtime_rule.bzl`, do not use `@pypackaging.bzl` to parse and normalize +# the versions. If we want to fully use it in those files, `pypackaging.bzl` +# first needs to be added to the list of repositories without autoloads in +# Bazel. +def _test_autoloaded_files_only_load_from_repos_without_autoloads(name): + analysis_test( + name = name, + impl = _test_autoloaded_files_only_load_from_repos_without_autoloads_impl, + targets = { + lib: "//python:" + lib + for lib in _AUTOLOADED + }, + ) + +def _test_autoloaded_files_only_load_from_repos_without_autoloads_impl(env, targets): + for lib in _AUTOLOADED: + target = getattr(targets, lib) + got = [] + for src in target[StarlarkLibraryInfo].transitive_srcs.to_list(): + repo = src.owner.workspace_name + + # Bzlmod uses `+` (`~` before Bazel 8) to separate the module name + # from the rest of the canonical repository name. + repo, _, _ = repo.partition("+") + repo, _, _ = repo.partition("~") + if repo not in _REPOS_WITHOUT_AUTOLOADS: + got.append(str(src.owner)) + + env.expect.that_collection( + got, + expr = "files loaded by {} from repos with autoloads".format(target.label), + ).contains_exactly([]) + +_tests.append(_test_autoloaded_files_only_load_from_repos_without_autoloads) + +def bazel_autoloads_test_suite(name): + test_suite( + name = name, + tests = _tests, + ) diff --git a/tests/py_runtime/py_runtime_tests.bzl b/tests/py_runtime/py_runtime_tests.bzl index 47cd97f142..ca16fe3390 100644 --- a/tests/py_runtime/py_runtime_tests.bzl +++ b/tests/py_runtime/py_runtime_tests.bzl @@ -594,6 +594,31 @@ def _test_version_info_from_flag_impl(env, target): _tests.append(_test_version_info_from_flag) +def _test_version_info_from_flag_with_prerelease(name): + py_runtime( + name = name + "_subject", + interpreter_version_info = None, + interpreter_path = "/bogus", + ) + analysis_test( + name = name, + target = name + "_subject", + impl = _test_version_info_from_flag_with_prerelease_impl, + config_settings = { + labels.PYTHON_VERSION: "3.15.0rc1", + }, + ) + +def _test_version_info_from_flag_with_prerelease_impl(env, target): + version_info = env.expect.that_target(target).provider(PyRuntimeInfo, factory = py_runtime_info_subject).interpreter_version_info() + version_info.major().equals(3) + version_info.minor().equals(15) + version_info.micro().equals(0) + version_info.releaselevel().equals(None) + version_info.serial().equals(None) + +_tests.append(_test_version_info_from_flag_with_prerelease) + def py_runtime_test_suite(name): test_suite( name = name,