xref: /aosp_15_r20/external/bazelbuild-rules_python/python/private/pypi/index_sources.bzl (revision 60517a1edbc8ecf509223e9af94a7adec7d736b8)
1# Copyright 2024 The Bazel Authors. All rights reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""
16A file that houses private functions used in the `bzlmod` extension with the same name.
17"""
18
19def index_sources(line):
20    """Get PyPI sources from a requirements.txt line.
21
22    We interpret the spec described in
23    https://pip.pypa.io/en/stable/reference/requirement-specifiers/#requirement-specifiers
24
25    Args:
26        line(str): The requirements.txt entry.
27
28    Returns:
29        A struct with shas attribute containing a list of shas to download from pypi_index.
30    """
31    head, _, maybe_hashes = line.partition(";")
32    _, _, version = head.partition("==")
33    version = version.partition(" ")[0].strip()
34
35    if "@" in head:
36        shas = []
37    else:
38        maybe_hashes = maybe_hashes or line
39        shas = [
40            sha.strip()
41            for sha in maybe_hashes.split("--hash=sha256:")[1:]
42        ]
43
44    if head == line:
45        head = line.partition("--hash=")[0].strip()
46    else:
47        head = head + ";" + maybe_hashes.partition("--hash=")[0].strip()
48
49    return struct(
50        requirement = line if not shas else head,
51        version = version,
52        shas = sorted(shas),
53    )
54