1"""Helper methods to download different python versions"""
2
3load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
4
5limited_api_build_file = """
6cc_library(
7    name = "python_headers",
8    hdrs = glob(["**/Include/**/*.h"]),
9    strip_include_prefix = "Python-{}/Include",
10    visibility = ["//visibility:public"],
11)
12"""
13
14def python_source_archive(name, sha256):
15    """Helper method to create a python_headers target that will work for linux and macos.
16
17    Args:
18      name: The name of the target, should be in the form python_{VERSION}
19      sha256: The sha256 of the python package for the specified version
20    """
21    version = name.split("-")[1]
22    http_archive(
23        name = name,
24        urls = [
25            "https://www.python.org/ftp/python/{0}/Python-{0}.tgz"
26                .format(version),
27        ],
28        sha256 = sha256,
29        build_file_content = limited_api_build_file.format(version),
30        patch_cmds = [
31            "echo '#define SIZEOF_WCHAR_T 4' > Python-{}/Include/pyconfig.h"
32                .format(version),
33        ],
34    )
35
36nuget_build_file = """
37cc_import(
38    name = "python_full_api",
39    hdrs = glob(["**/*.h"]),
40    shared_library = "python{0}.dll",
41    interface_library = "libs/python{0}.lib",
42    visibility = ["@upb//python:__pkg__"],
43)
44
45cc_import(
46    name = "python_limited_api",
47    hdrs = glob(["**/*.h"]),
48    shared_library = "python{1}.dll",
49    interface_library = "libs/python{1}.lib",
50    visibility = ["@upb//python:__pkg__"],
51)
52"""
53
54def python_nuget_package(name, sha256):
55    """Helper method to create full and limited api dependencies for windows using nuget
56
57    Args:
58      name: The name of the target, should be in the form nuget_python_{CPU}_{VERSION}
59      sha256: The sha256 of the nuget package for that version
60    """
61    cpu = name.split("_")[2]
62    version = name.split("_")[3]
63
64    full_api_lib_number = version.split(".")[0] + version.split(".")[1]
65    limited_api_lib_number = version.split(".")[0]
66
67    folder_name_dict = {
68        "i686": "pythonx86",
69        "x86-64": "python",
70    }
71
72    http_archive(
73        name = name,
74        urls = [
75            "https://www.nuget.org/api/v2/package/{}/{}"
76                .format(folder_name_dict[cpu], version),
77        ],
78        sha256 = sha256,
79        strip_prefix = "tools",
80        build_file_content =
81            nuget_build_file.format(full_api_lib_number, limited_api_lib_number),
82        type = "zip",
83        patch_cmds = ["cp -r include/* ."],
84    )
85