1# Copyright 2023 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"""Definitions for the modules_mapping.json generation. 16 17The modules_mapping.json file is a mapping from Python modules to the wheel 18names that provide those modules. It is used for determining which wheel 19distribution should be used in the `deps` attribute of `py_*` targets. 20 21This mapping is necessary when reading Python import statements and determining 22if they are provided by third-party dependencies. Most importantly, when the 23module name doesn't match the wheel distribution name. 24""" 25 26def _modules_mapping_impl(ctx): 27 modules_mapping = ctx.actions.declare_file(ctx.attr.modules_mapping_name) 28 args = ctx.actions.args() 29 args.add("--output_file", modules_mapping.path) 30 args.add_all("--exclude_patterns", ctx.attr.exclude_patterns) 31 args.add_all("--wheels", [whl.path for whl in ctx.files.wheels]) 32 ctx.actions.run( 33 inputs = ctx.files.wheels, 34 outputs = [modules_mapping], 35 executable = ctx.executable._generator, 36 arguments = [args], 37 use_default_shell_env = False, 38 ) 39 return [DefaultInfo(files = depset([modules_mapping]))] 40 41modules_mapping = rule( 42 _modules_mapping_impl, 43 attrs = { 44 "exclude_patterns": attr.string_list( 45 default = ["^_|(\\._)+"], 46 doc = "A set of regex patterns to match against each calculated module path. By default, exclude the modules starting with underscores.", 47 mandatory = False, 48 ), 49 "modules_mapping_name": attr.string( 50 default = "modules_mapping.json", 51 doc = "The name for the output JSON file.", 52 mandatory = False, 53 ), 54 "wheels": attr.label_list( 55 allow_files = True, 56 doc = "The list of wheels, usually the 'all_whl_requirements' from @<pip_repository>//:requirements.bzl", 57 mandatory = True, 58 ), 59 "_generator": attr.label( 60 cfg = "exec", 61 default = "//modules_mapping:generator", 62 executable = True, 63 ), 64 }, 65 doc = "Creates a modules_mapping.json file for mapping module names to wheel distribution names.", 66) 67