Greg Estren | c1d7087 | 2020-08-25 07:17:08 -0700 | [diff] [blame] | 1 | # Copyright 2020 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 | """General-purpose business logic.""" |
| 15 | from typing import Tuple |
| 16 | |
| 17 | # Do not edit this line. Copybara replaces it with PY2 migration helper..third_party.bazel.tools.ctexplain.bazel_api as bazel_api |
| 18 | from tools.ctexplain.types import ConfiguredTarget |
| 19 | |
| 20 | |
| 21 | def analyze_build(bazel: bazel_api.BazelApi, labels: Tuple[str, ...], |
| 22 | build_flags: Tuple[str, ...]) -> Tuple[ConfiguredTarget, ...]: |
| 23 | """Gets a build invocation's configured targets. |
| 24 | |
| 25 | Args: |
| 26 | bazel: API for invoking Bazel. |
| 27 | labels: The targets to build. |
| 28 | build_flags: The build flags to use. |
| 29 | |
| 30 | Returns: |
| 31 | Configured targets representing the build. |
| 32 | |
| 33 | Raises: |
| 34 | RuntimeError: On any invocation errors. |
| 35 | """ |
| 36 | cquery_args = [f'deps({",".join(labels)})'] |
| 37 | cquery_args.extend(build_flags) |
| 38 | (success, stderr, cts) = bazel.cquery(cquery_args) |
| 39 | if not success: |
| 40 | raise RuntimeError("invocation failed: " + stderr.decode("utf-8")) |
| 41 | |
| 42 | # We have to do separate calls to "bazel config" to get the actual configs |
| 43 | # from their hashes. |
| 44 | hashes_to_configs = {} |
| 45 | cts_with_configs = [] |
| 46 | for ct in cts: |
| 47 | # Don't use dict.setdefault because that unconditionally calls get_config |
| 48 | # as one of its parameters and that's an expensive operation to waste. |
| 49 | if ct.config_hash not in hashes_to_configs: |
| 50 | hashes_to_configs[ct.config_hash] = bazel.get_config(ct.config_hash) |
| 51 | config = hashes_to_configs[ct.config_hash] |
| 52 | cts_with_configs.append( |
| 53 | ConfiguredTarget(ct.label, config, ct.config_hash, |
| 54 | ct.transitive_fragments)) |
| 55 | |
| 56 | return tuple(cts_with_configs) |