xref: /aosp_15_r20/external/bazelbuild-rules_python/examples/pip_parse_vendored/BUILD.bazel (revision 60517a1edbc8ecf509223e9af94a7adec7d736b8)
1load("@bazel_skylib//rules:build_test.bzl", "build_test")
2load("@bazel_skylib//rules:diff_test.bzl", "diff_test")
3load("@bazel_skylib//rules:write_file.bzl", "write_file")
4load("@rules_python//python:defs.bzl", "py_test")
5load("@rules_python//python:pip.bzl", "compile_pip_requirements")
6load("//:requirements.bzl", "all_data_requirements", "all_requirements", "all_whl_requirements", "requirement")
7
8# This rule adds a convenient way to update the requirements.txt
9# lockfile based on the requirements.in.
10compile_pip_requirements(
11    name = "requirements",
12    src = "requirements.in",
13)
14
15# The requirements.bzl file is using the hub repo to access packages via the
16# `requirement` macro and when the requirements.bzl is vendored, the hub
17# repo won't be present. As a result, we have to adjust the label scheme in
18# the requirements.bzl to make sure that they continue to work.
19genrule(
20    name = "requirement_bzl",
21    srcs = ["@pip_deps_to_be_vendored//:requirements.bzl"],
22    outs = ["requirements.clean.bzl"],
23    cmd = " | ".join([
24        "cat $<",
25        # Substitute the name of the hub to ensure that the dependencies do
26        # not require the hub repo initialized in the WORKSPACE.
27        "sed -e 's/pip_deps_to_be_vendored/my_project_pip_deps_vendored/g'",
28        # Change the labels from using the hub repo to using the spoke repos
29        # directly.
30        "sed -e 's|//\\([^:]*\\):pkg|_\\1//:pkg|g'",
31        "sed -e 's|//\\([^:]*\\):whl|_\\1//:whl|g'",
32        "sed -e 's|//\\([^:]*\\):data|_\\1//:data|g'",
33        # Change the convenience macros to use the same naming.
34        "sed -e 's|//{}:{}|_{}//:{}|g' >$@",
35    ]),
36)
37
38write_file(
39    name = "gen_update",
40    out = "update.sh",
41    content = [
42        # This depends on bash, would need tweaks for Windows
43        "#!/usr/bin/env bash",
44        # Bazel gives us a way to access the source folder!
45        "cd $BUILD_WORKSPACE_DIRECTORY",
46        "cp -fv bazel-bin/requirements.clean.bzl requirements.bzl",
47    ],
48)
49
50sh_binary(
51    name = "vendor_requirements",
52    srcs = ["update.sh"],
53    data = [":requirement_bzl"],
54)
55
56# Similarly ensures that the requirements.bzl file is updated
57# based on the requirements.txt lockfile.
58diff_test(
59    name = "test_vendored",
60    failure_message = "Please run:  bazel run //:vendor_requirements",
61    file1 = "requirements.bzl",
62    file2 = "requirement_bzl",
63)
64
65py_test(
66    name = "test_dependency_usage",
67    srcs = ["test_dependency_usage.py"],
68    deps = [
69        requirement("requests"),
70    ],
71)
72
73build_test(
74    name = "test_requirement_lists",
75    targets = all_requirements + all_whl_requirements + all_data_requirements,
76)
77