Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 1 | From e9002bef44df84370649b995b8c9e6a89d4d37e9 Mon Sep 17 00:00:00 2001 |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 2 | From: Philipp Schrader <philipp.schrader@gmail.com> |
| 3 | Date: Sat, 24 Sep 2022 15:56:33 -0700 |
| 4 | Subject: [PATCH] Allow user to patch wheels |
| 5 | |
| 6 | There are two parts here. First we need to let the user inject patches |
| 7 | to specific wheels. We do that via a new JSON file that can be |
| 8 | specified in the WORKSPACE via the `patch_spec` attribute. |
| 9 | The second part is to allow the user to inject `deps` in the specific |
| 10 | wheels. This is important because the patches for the wheels may want |
| 11 | to pull in other libraries that the wheel normally does not depend on. |
| 12 | The `deps` injection is done via a new attribute on the annotation. |
| 13 | |
| 14 | I submitted a PR to rules_python for the `deps` injection part here: |
| 15 | https://github.com/bazelbuild/rules_python/pull/853 |
| 16 | However, the maintainers would like to take a different approach for |
| 17 | which I will write a proposal. The approach here will not be what's |
| 18 | eventually upstreamed. |
| 19 | --- |
| 20 | .../pip_install/extract_wheels/annotation.py | 5 +++ |
| 21 | python/pip_install/extract_wheels/bazel.py | 13 +++++++- |
| 22 | .../extract_wheels/extract_single_wheel.py | 29 +++++++++++++++++ |
| 23 | .../parse_requirements_to_bzl.py | 25 ++++++++++++++- |
| 24 | python/pip_install/pip_repository.bzl | 31 ++++++++++++++++++- |
| 25 | 5 files changed, 100 insertions(+), 3 deletions(-) |
| 26 | |
| 27 | diff --git a/python/pip_install/extract_wheels/annotation.py b/python/pip_install/extract_wheels/annotation.py |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 28 | index 48aaa802..fe8b4dc5 100644 |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 29 | --- a/python/pip_install/extract_wheels/annotation.py |
| 30 | +++ b/python/pip_install/extract_wheels/annotation.py |
| 31 | @@ -19,6 +19,7 @@ class Annotation(OrderedDict): |
| 32 | "data", |
| 33 | "data_exclude_glob", |
| 34 | "srcs_exclude_glob", |
| 35 | + "deps", |
| 36 | ): |
| 37 | if field not in content: |
| 38 | missing.append(field) |
| 39 | @@ -61,6 +62,10 @@ class Annotation(OrderedDict): |
| 40 | def srcs_exclude_glob(self) -> List[str]: |
| 41 | return self["srcs_exclude_glob"] |
| 42 | |
| 43 | + @property |
| 44 | + def deps(self) -> List[str]: |
| 45 | + return self["deps"] |
| 46 | + |
| 47 | |
| 48 | class AnnotationsMap: |
| 49 | """A mapping of python package names to [Annotation]""" |
| 50 | diff --git a/python/pip_install/extract_wheels/bazel.py b/python/pip_install/extract_wheels/bazel.py |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 51 | index 8f442c93..f4b7f26a 100644 |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 52 | --- a/python/pip_install/extract_wheels/bazel.py |
| 53 | +++ b/python/pip_install/extract_wheels/bazel.py |
| 54 | @@ -2,6 +2,7 @@ |
| 55 | import json |
| 56 | import os |
| 57 | import shutil |
| 58 | +import subprocess |
| 59 | import textwrap |
| 60 | from pathlib import Path |
| 61 | from typing import Dict, Iterable, List, Optional, Set |
| 62 | @@ -335,6 +336,9 @@ def extract_wheel( |
| 63 | incremental: bool = False, |
| 64 | incremental_dir: Path = Path("."), |
| 65 | annotation: Optional[annotation.Annotation] = None, |
| 66 | + patches: Optional[List[os.PathLike]] = None, |
| 67 | + patch_args: Optional[List[os.PathLike]] = None, |
| 68 | + patch_tool: Optional[str] = "patch", |
| 69 | ) -> Optional[str]: |
| 70 | """Extracts wheel into given directory and creates py_library and filegroup targets. |
| 71 | |
| 72 | @@ -415,6 +419,7 @@ def extract_wheel( |
| 73 | data = [] |
| 74 | data_exclude = pip_data_exclude |
| 75 | srcs_exclude = [] |
| 76 | + deps = [] |
| 77 | if annotation: |
| 78 | for src, dest in annotation.copy_files.items(): |
| 79 | data.append(dest) |
| 80 | @@ -427,6 +432,7 @@ def extract_wheel( |
| 81 | data.extend(annotation.data) |
| 82 | data_exclude.extend(annotation.data_exclude_glob) |
| 83 | srcs_exclude.extend(annotation.srcs_exclude_glob) |
| 84 | + deps.extend('"%s"' % dep for dep in annotation.deps) |
| 85 | if annotation.additive_build_content: |
| 86 | additional_content.append(annotation.additive_build_content) |
| 87 | |
| 88 | @@ -434,7 +440,7 @@ def extract_wheel( |
| 89 | name=PY_LIBRARY_LABEL |
| 90 | if incremental |
| 91 | else sanitise_name(whl.name, repo_prefix), |
| 92 | - dependencies=sanitised_dependencies, |
| 93 | + dependencies=sanitised_dependencies + deps, |
| 94 | whl_file_deps=sanitised_wheel_file_dependencies, |
| 95 | data_exclude=data_exclude, |
| 96 | data=data, |
| 97 | @@ -444,6 +450,11 @@ def extract_wheel( |
| 98 | ) |
| 99 | build_file.write(contents) |
| 100 | |
| 101 | + if patches: |
| 102 | + base_cmd = [patch_tool] + (patch_args or []) + ["--input"] |
| 103 | + for patch in patches: |
| 104 | + subprocess.run(base_cmd + [patch], check=True, cwd=directory) |
| 105 | + |
| 106 | if not incremental: |
| 107 | os.remove(whl.path) |
| 108 | return f"//{directory}" |
| 109 | diff --git a/python/pip_install/extract_wheels/extract_single_wheel.py b/python/pip_install/extract_wheels/extract_single_wheel.py |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 110 | index 8742d250..50a1243e 100644 |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 111 | --- a/python/pip_install/extract_wheels/extract_single_wheel.py |
| 112 | +++ b/python/pip_install/extract_wheels/extract_single_wheel.py |
| 113 | @@ -1,4 +1,5 @@ |
| 114 | import argparse |
| 115 | +import contextlib |
| 116 | import errno |
| 117 | import glob |
| 118 | import os |
| 119 | @@ -35,6 +36,16 @@ def configure_reproducible_wheels() -> None: |
| 120 | os.environ["PYTHONHASHSEED"] = "0" |
| 121 | |
| 122 | |
| 123 | +@contextlib.contextmanager |
| 124 | +def chdir_context(new_cwd: os.PathLike) -> None: |
| 125 | + old_cwd = os.getcwd() |
| 126 | + try: |
| 127 | + os.chdir(new_cwd) |
| 128 | + yield |
| 129 | + finally: |
| 130 | + os.chdir(old_cwd) |
| 131 | + |
| 132 | + |
| 133 | def main() -> None: |
| 134 | parser = argparse.ArgumentParser( |
| 135 | description="Build and/or fetch a single wheel based on the requirement passed in" |
| 136 | @@ -55,6 +66,21 @@ def main() -> None: |
| 137 | action="store_true", |
| 138 | help="If set, skips the pip download step. The .whl file is assumbed to be downloaded by bazel.", |
| 139 | ) |
| 140 | + parser.add_argument( |
| 141 | + "--patch-file", |
| 142 | + action="append", |
| 143 | + help="The patch files to apply. Can be repeated for multiple patches.", |
| 144 | + ) |
| 145 | + parser.add_argument( |
| 146 | + "--patch-arg", |
| 147 | + action="append", |
| 148 | + help="Arguments to pass to the patch tool. Can be repeated for multiple arguments.", |
| 149 | + ) |
| 150 | + parser.add_argument( |
| 151 | + "--patch-tool", |
| 152 | + type=str, |
| 153 | + help="Path of the patch tool to execute for applying patches.", |
| 154 | + ) |
| 155 | arguments.parse_common_args(parser) |
| 156 | args = parser.parse_args() |
| 157 | deserialized_args = dict(vars(args)) |
| 158 | @@ -104,6 +130,9 @@ def main() -> None: |
| 159 | incremental=True, |
| 160 | repo_prefix=args.repo_prefix, |
| 161 | annotation=args.annotation, |
| 162 | + patches=args.patch_file, |
| 163 | + patch_args=args.patch_arg, |
| 164 | + patch_tool=args.patch_tool, |
| 165 | ) |
| 166 | |
| 167 | |
| 168 | diff --git a/python/pip_install/extract_wheels/parse_requirements_to_bzl.py b/python/pip_install/extract_wheels/parse_requirements_to_bzl.py |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 169 | index 002e6857..fc7fe780 100644 |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 170 | --- a/python/pip_install/extract_wheels/parse_requirements_to_bzl.py |
| 171 | +++ b/python/pip_install/extract_wheels/parse_requirements_to_bzl.py |
| 172 | @@ -88,6 +88,7 @@ def parse_whl_library_args(args: argparse.Namespace) -> Dict[str, Any]: |
| 173 | "bzlmod", |
| 174 | "overrides", |
| 175 | "require_overrides", |
| 176 | + "patch_spec", |
| 177 | ): |
| 178 | if arg in whl_library_args: |
| 179 | whl_library_args.pop(arg) |
| 180 | @@ -104,6 +105,7 @@ def generate_parsed_requirements_contents( |
| 181 | bzlmod: bool = False, |
| 182 | overrides: Optional[Dict[str, Dict[str, str]]] = None, |
| 183 | require_overrides: bool = False, |
| 184 | + patch_spec: Optional[Dict[str, Dict[str, str]]] = None, |
| 185 | ) -> str: |
| 186 | """ |
| 187 | Parse each requirement from the requirements_lock file, and prepare arguments for each |
| 188 | @@ -147,13 +149,19 @@ def generate_parsed_requirements_contents( |
| 189 | else: |
| 190 | override = _NOP_OVERRIDE |
| 191 | |
| 192 | + clean_name = _clean_name(override_name.split("=")[0]) |
| 193 | + patch_attributes = _patch_spec.get(clean_name, {{}}) |
| 194 | + |
| 195 | whl_library( |
| 196 | name = name, |
| 197 | requirement = requirement, |
| 198 | annotation = _get_annotation(requirement), |
| 199 | url = override["url"], |
| 200 | sha256 = override["sha256"], |
| 201 | - **whl_config |
| 202 | + **dict( |
| 203 | + patch_attributes.items() + |
| 204 | + _config.items(), |
| 205 | + ) |
| 206 | ) |
| 207 | """ |
| 208 | return textwrap.dedent( |
| 209 | @@ -172,6 +180,7 @@ def generate_parsed_requirements_contents( |
| 210 | _bzlmod = {bzlmod} |
| 211 | _overrides = {overrides} |
| 212 | _require_overrides = {require_overrides} |
| 213 | + _patch_spec = {patch_spec} |
| 214 | |
| 215 | _NOP_OVERRIDE = {{ |
| 216 | "url": None, |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 217 | @@ -236,6 +245,7 @@ def generate_parsed_requirements_contents( |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 218 | bzlmod=bzlmod, |
| 219 | overrides=overrides or {}, |
| 220 | require_overrides=require_overrides, |
| 221 | + patch_spec=patch_spec or {}, |
| 222 | ) |
| 223 | ) |
| 224 | |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 225 | @@ -308,6 +318,13 @@ If set, it will take precedence over python_interpreter.", |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 226 | action="store_true", |
| 227 | help="If set, requires that every requirement has a URL override in the --overrides JSON file.", |
| 228 | ) |
| 229 | + parser.add_argument( |
| 230 | + "--patch_spec", |
| 231 | + type=Path, |
| 232 | + help=("A json encoded file containing patch specifications for packages. " |
| 233 | + "Keys are the normalized names of packages. " |
| 234 | + "Values are objects with keys 'patches', 'patch_args', and 'patch_tool'."), |
| 235 | + ) |
| 236 | arguments.parse_common_args(parser) |
| 237 | args = parser.parse_args() |
| 238 | |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 239 | @@ -338,6 +355,11 @@ If set, it will take precedence over python_interpreter.", |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 240 | else: |
| 241 | overrides = None |
| 242 | |
| 243 | + if args.patch_spec: |
| 244 | + patch_spec = json.loads(args.patch_spec.read_text()) |
| 245 | + else: |
| 246 | + patch_spec = None |
| 247 | + |
| 248 | output.write( |
| 249 | textwrap.dedent( |
| 250 | """\ |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 251 | @@ -362,6 +384,7 @@ If set, it will take precedence over python_interpreter.", |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 252 | bzlmod=args.bzlmod, |
| 253 | overrides=overrides, |
| 254 | require_overrides=args.require_overrides, |
| 255 | + patch_spec=patch_spec, |
| 256 | ) |
| 257 | ) |
| 258 | |
| 259 | diff --git a/python/pip_install/pip_repository.bzl b/python/pip_install/pip_repository.bzl |
Philipp Schrader | 32f57d7 | 2024-09-02 19:59:11 -0700 | [diff] [blame] | 260 | index 5af07315..bf7f99a8 100644 |
Philipp Schrader | 7520ee6 | 2022-12-10 14:04:40 -0800 | [diff] [blame] | 261 | --- a/python/pip_install/pip_repository.bzl |
| 262 | +++ b/python/pip_install/pip_repository.bzl |
| 263 | @@ -327,6 +327,9 @@ def _pip_repository_impl(rctx): |
| 264 | args += ["--overrides", overrides_file] |
| 265 | if rctx.attr.require_overrides: |
| 266 | args += ["--require-overrides"] |
| 267 | + if rctx.attr.patch_spec: |
| 268 | + patch_spec_file = rctx.path(rctx.attr.patch_spec).realpath |
| 269 | + args += ["--patch_spec", patch_spec_file] |
| 270 | progress_message = "Parsing requirements to starlark" |
| 271 | |
| 272 | args += ["--repo", rctx.attr.name, "--repo-prefix", rctx.attr.repo_prefix] |
| 273 | @@ -460,6 +463,10 @@ we do not create the install_deps() macro. |
| 274 | default = False, |
| 275 | doc = "If True, every requirement must have an entry in the \"overrides\" JSON file.", |
| 276 | ), |
| 277 | + "patch_spec": attr.label( |
| 278 | + allow_single_file = True, |
| 279 | + doc = "A JSON file containing patches for various modules. TBD", |
| 280 | + ), |
| 281 | "requirements": attr.label( |
| 282 | allow_single_file = True, |
| 283 | doc = "A 'requirements.txt' pip requirements file.", |
| 284 | @@ -562,6 +569,12 @@ def _whl_library_impl(rctx): |
| 285 | if not download_result.success: |
| 286 | fail("Failed to download {}".format(rctx.attr.url)) |
| 287 | args.append("--pre-downloaded") |
| 288 | + if rctx.attr.patches: |
| 289 | + patch_files = [str(rctx.path(path).realpath) for path in rctx.attr.patches] |
| 290 | + args.extend(["--patch-file=" + file for file in patch_files] + [ |
| 291 | + "--patch-tool", |
| 292 | + rctx.attr.patch_tool, |
| 293 | + ] + ["--patch-arg=" + arg for arg in rctx.attr.patch_args]) |
| 294 | |
| 295 | args = _parse_optional_attrs(rctx, args) |
| 296 | |
| 297 | @@ -604,6 +617,20 @@ whl_library_attrs = { |
| 298 | "Optionally set this when using the 'url' parameter. " + |
| 299 | "Must be the expected checksum of the downloaded file." |
| 300 | ), |
| 301 | + ), |
| 302 | + "patches": attr.label_list( |
| 303 | + doc = ( |
| 304 | + "The patch files to apply. List of strings, Labels, or paths. " + |
| 305 | + "The paths within the files are relative to the 'site-packages' directory " + |
| 306 | + "into which the wheel is extracted." |
| 307 | + ), |
| 308 | + ), |
| 309 | + "patch_args": attr.string_list( |
| 310 | + doc = "Arguments to pass to the patch tool. List of strings.", |
| 311 | + ), |
| 312 | + "patch_tool": attr.string( |
| 313 | + doc = "Path of the patch tool to execute for applying patches. String.", |
| 314 | + default = "patch", |
| 315 | ) |
| 316 | } |
| 317 | |
| 318 | @@ -624,7 +651,8 @@ def package_annotation( |
| 319 | copy_executables = {}, |
| 320 | data = [], |
| 321 | data_exclude_glob = [], |
| 322 | - srcs_exclude_glob = []): |
| 323 | + srcs_exclude_glob = [], |
| 324 | + deps = []): |
| 325 | """Annotations to apply to the BUILD file content from package generated from a `pip_repository` rule. |
| 326 | |
| 327 | [cf]: https://github.com/bazelbuild/bazel-skylib/blob/main/docs/copy_file_doc.md |
| 328 | @@ -650,4 +678,5 @@ def package_annotation( |
| 329 | data = data, |
| 330 | data_exclude_glob = data_exclude_glob, |
| 331 | srcs_exclude_glob = srcs_exclude_glob, |
| 332 | + deps = deps, |
| 333 | )) |