Skip to content

Commit f0a8ceb

Browse files
laramielcopybara-github
authored andcommitted
bazel_to_cmake modernize type hints
PiperOrigin-RevId: 895684812 Change-Id: Ic1adfb4e62a25276bcdb8fe786f92142e93cb60f
1 parent 90cba53 commit f0a8ceb

19 files changed

Lines changed: 154 additions & 152 deletions

tools/cmake/bazel_to_cmake/active_repository.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
# pylint: disable=g-importing-member,missing-function-docstring
16+
1517
import pathlib
16-
from typing import Dict, Set
1718

1819
from .cmake_repository import CMakeRepository
1920
from .cmake_target import CMakePackage
@@ -40,14 +41,14 @@ def __init__(
4041
self,
4142
workspace: Workspace,
4243
repository_id: RepositoryId,
43-
bindings: Dict[TargetId, TargetId],
44+
bindings: dict[TargetId, TargetId],
4445
top_level: bool,
4546
):
4647
self._workspace: Workspace = workspace
4748
self._repository_id: RepositoryId = repository_id
48-
self._bindings: Dict[TargetId, TargetId] = bindings
49+
self._bindings: dict[TargetId, TargetId] = bindings
4950
self.top_level: bool = top_level
50-
self.ignored_libraries: Set[TargetId] = (
51+
self.ignored_libraries: set[TargetId] = (
5152
workspace.global_ignored_libraries.copy()
5253
)
5354
self._repository = None
@@ -62,6 +63,9 @@ def ignore_library(self, target: TargetId) -> None:
6263
6364
Like all `Workspace` state, this also propagates to bazel_to_cmake
6465
invocations for dependencies.
66+
67+
Args:
68+
target: The TargetId of the bzl library to ignore.
6569
"""
6670
assert isinstance(target, TargetId)
6771
self.ignored_libraries.add(target)
@@ -79,7 +83,7 @@ def repository(self) -> CMakeRepository:
7983
return self._repository
8084

8185
@property
82-
def bindings(self) -> Dict[TargetId, TargetId]:
86+
def bindings(self) -> dict[TargetId, TargetId]:
8387
return self._bindings
8488

8589
@property
@@ -99,5 +103,5 @@ def cmake_binary_dir(self) -> pathlib.PurePath:
99103
return self.repository.cmake_binary_dir
100104

101105
@property
102-
def repo_mapping(self) -> Dict[RepositoryId, RepositoryId]:
106+
def repo_mapping(self) -> dict[RepositoryId, RepositoryId]:
103107
return self.repository.repo_mapping

tools/cmake/bazel_to_cmake/cmake_provider.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,14 @@
1717
bazel build targets.
1818
"""
1919

20-
from typing import Tuple, Union
20+
# pylint: disable=g-importing-member,missing-function-docstring
21+
2122

2223
from .cmake_target import CMakePackage
2324
from .cmake_target import CMakeTarget
2425
from .cmake_target import CMakeTargetPair
2526
from .starlark.provider import Provider
27+
from .starlark.provider import ProviderTuple
2628

2729

2830
class CMakeHallucinatedTarget(Provider):
@@ -104,8 +106,8 @@ def __repr__(self):
104106

105107

106108
def make_providers(
107-
source: Union[CMakeTarget, CMakeTargetPair], *providers
108-
) -> Tuple[Provider, ...]:
109+
source: CMakeTarget | CMakeTargetPair, *providers
110+
) -> ProviderTuple:
109111
"""Construct providers from a CMakeTarget or CMakeTargetPair."""
110112
result = ()
111113
if isinstance(source, CMakeTargetPair):
@@ -125,7 +127,7 @@ def make_providers(
125127
return result
126128

127129

128-
def default_providers(source: CMakeTargetPair) -> Tuple[Provider, ...]:
130+
def default_providers(source: CMakeTargetPair) -> ProviderTuple:
129131
return make_providers(
130132
source,
131133
CMakePackageDepsProvider,

tools/cmake/bazel_to_cmake/cmake_target.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
"""CMake Provider types."""
1515

16-
from typing import NamedTuple, Optional
16+
from typing import NamedTuple
1717

1818

1919
class CMakePackage(str):
@@ -27,11 +27,11 @@ class CMakeTarget(str):
2727
class CMakeTargetPair(NamedTuple):
2828
"""CMakeTargetPair identifies a cmake target, optionally with an alias."""
2929

30-
cmake_package: Optional[CMakePackage]
30+
cmake_package: CMakePackage | None
3131
target: CMakeTarget
32-
alias: Optional[CMakeTarget] = None
32+
alias: CMakeTarget | None = None
3333

34-
def with_alias(self, alias: Optional[CMakeTarget]) -> "CMakeTargetPair":
34+
def with_alias(self, alias: CMakeTarget | None) -> 'CMakeTargetPair':
3535
if alias is not None:
3636
assert isinstance(alias, CMakeTarget)
3737
return self._replace(alias=alias)

tools/cmake/bazel_to_cmake/emit_alias.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
# limitations under the License.
1414
"""Emits a library alias."""
1515

16+
# pylint: disable=g-importing-member,missing-function-docstring
17+
1618
import io
1719

1820
from .cmake_provider import CMakeAliasProvider
@@ -25,7 +27,7 @@ def emit_cc_library_aliases(
2527
out: io.StringIO,
2628
target_name: CMakeTarget,
2729
cmake_target_pair: CMakeTargetPair,
28-
) -> None:
30+
) -> ProviderTuple:
2931
"""Generates common alias targets."""
3032

3133
has_alias = False

tools/cmake/bazel_to_cmake/golden_test.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import pathlib
2121
import shutil
2222
import sys
23-
from typing import Any, Dict, List, Tuple, Union
23+
from typing import Any
2424

2525
import pytest
2626

@@ -57,20 +57,20 @@
5757
}
5858

5959

60-
def parameters() -> List[Tuple[str, Dict[str, Any]]]:
60+
def parameters() -> list[tuple[str, dict[str, Any]]]:
6161
"""Returns config tuples by reading config.json from the 'testdata' subdir."""
6262
if UPDATE_GOLDENS:
6363
print('UPDATE_GOLDENS')
6464
testdata = pathlib.Path(__file__).resolve().with_name('testdata')
6565
else:
6666
testdata = pathlib.Path(__file__).with_name('testdata').resolve()
67-
result: List[Tuple[str, Dict[str, Any]]] = []
67+
result: list[tuple[str, dict[str, Any]]] = []
6868
for x in testdata.iterdir():
6969
if '__' in str(x):
7070
continue
7171
try:
7272
with (x / 'config.json').open('r') as f:
73-
config: Dict[str, Any] = json.load(f)
73+
config: dict[str, Any] = json.load(f)
7474
except FileNotFoundError as e:
7575
raise FileNotFoundError(f'Failed to read {str(x)}/config.json') from e
7676
config['source_directory'] = str(x)
@@ -80,9 +80,9 @@ def parameters() -> List[Tuple[str, Dict[str, Any]]]:
8080

8181
def get_files_list(
8282
source_directory: pathlib.Path, include_goldens=False
83-
) -> List[pathlib.Path]:
83+
) -> list[pathlib.Path]:
8484
"""Returns non-golden files under source directory."""
85-
files: List[pathlib.Path] = []
85+
files: list[pathlib.Path] = []
8686
try:
8787
for x in sorted(source_directory.glob('**/*')):
8888
if not x.is_file():
@@ -95,7 +95,7 @@ def get_files_list(
9595
return files
9696

9797

98-
def copy_tree(source_dir: str, source_files: List[str], dest_dir: pathlib.Path):
98+
def copy_tree(source_dir: str, source_files: list[str], dest_dir: pathlib.Path):
9999
"""Copies source_files from source_dir to dest_dir."""
100100
for x in source_files:
101101
dest_path = dest_dir.joinpath(x)
@@ -141,7 +141,7 @@ def add_repositories(workspace: Workspace):
141141
)
142142

143143
def persist_cmake_name(
144-
target: Union[str, TargetId],
144+
target: str | TargetId,
145145
cmake_alias: CMakeTarget,
146146
):
147147
if not isinstance(target, TargetId):
@@ -231,7 +231,7 @@ def persist_cmake_name(
231231

232232

233233
@pytest.mark.parametrize('test_name,config', parameters())
234-
def test_golden(test_name: str, config: Dict[str, Any], tmpdir):
234+
def test_golden(test_name: str, config: dict[str, Any], tmpdir):
235235
# Start with the list of source files.
236236
source_directory = pathlib.Path(config['source_directory'])
237237
del config['source_directory']

tools/cmake/bazel_to_cmake/main.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@
1313
# limitations under the License.
1414
"""Main entry point for bazel_to_cmake."""
1515

16-
# pylint: disable=relative-beyond-top-level
16+
# pylint: disable=relative-beyond-top-level,g-importing-member,missing-function-docstring
1717

1818
import argparse
19+
from collections.abc import Iterable
1920
import json
2021
import os
2122
import pathlib
2223
import pickle
2324
import sys
24-
from typing import Dict, List, Set, Union
2525

2626
from . import native_rules # pylint: disable=unused-import
2727
from .active_repository import Repository
@@ -44,10 +44,10 @@
4444

4545
def maybe_expand_special_targets(
4646
t: TargetId,
47-
available: Union[Set[TargetId], List[TargetId]],
48-
):
47+
available: Iterable[TargetId],
48+
) -> list[TargetId]:
4949
# Handle special targets t, :all, :... from the available targets.
50-
result: List[TargetId] = []
50+
result: list[TargetId] = []
5151
if t.target_name == "all":
5252
for u in available:
5353
if u.package_id == t.package_id:
@@ -65,11 +65,11 @@ def maybe_expand_special_targets(
6565
def get_bindings_from_args(
6666
args: argparse.Namespace,
6767
repository_id: RepositoryId,
68-
) -> Dict[TargetId, TargetId]:
68+
) -> dict[TargetId, TargetId]:
6969
# Add repository bindings. These provide the "native.bind" equivalent,
7070
# and are resolved after repo mappings. Unlike native.bind, they are
7171
# not restricted to only bind //external:name = alias values.
72-
bindings: Dict[TargetId, TargetId] = {}
72+
bindings: dict[TargetId, TargetId] = {}
7373
for name in args.bind:
7474
i = name.find("=")
7575
assert i > 0
@@ -85,7 +85,7 @@ def get_bindings_from_args(
8585
def create_root_workspace(
8686
args: argparse.Namespace,
8787
repository_id: RepositoryId,
88-
):
88+
) -> Workspace:
8989
"""Creates a workspace for the root repository."""
9090
assert args.cmake_vars is not None
9191
try:
@@ -121,7 +121,7 @@ def create_root_workspace(
121121

122122
def load_root_workspace(
123123
args: argparse.Namespace,
124-
):
124+
) -> Workspace:
125125
"""Unpickles a workspace and loads the repository from it."""
126126
with open(args.load_workspace, "rb") as f:
127127
workspace = pickle.load(f)
@@ -139,7 +139,7 @@ def do_process_build_files(
139139
args: argparse.Namespace,
140140
active_repo: Repository,
141141
state: EvaluationState,
142-
):
142+
) -> set[TargetId]:
143143
# Load build files.
144144
include_packages = args.include_package or ["**"]
145145
exclude_packages = args.exclude_package or []
@@ -185,7 +185,7 @@ def do_process_build_files(
185185
return targets_to_analyze
186186

187187

188-
def run_main(args: argparse.Namespace):
188+
def run_main(args: argparse.Namespace) -> int:
189189
assert args.bazel_repo_name
190190
repository_id: RepositoryId = RepositoryId(args.bazel_repo_name)
191191

@@ -347,7 +347,7 @@ def _persist_cmakepairs(target: TargetId, cmake_pair: CMakeTargetPair):
347347
return 0
348348

349349

350-
def main():
350+
def main() -> int:
351351
ap = argparse.ArgumentParser()
352352
# Used for sub-projects only.
353353
ap.add_argument("--load-workspace")

tools/cmake/bazel_to_cmake/native_aspect.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737
# pylint: disable=invalid-name
3838

39-
from typing import List, Optional, Protocol, Tuple
39+
from typing import Any, Protocol
4040

4141
from .starlark.bazel_target import RepositoryId
4242
from .starlark.bazel_target import TargetId
@@ -54,16 +54,16 @@ def __call__(
5454
self, # ignored
5555
context: InvocationContext,
5656
proto_target: TargetId,
57-
visibility: Optional[List[RelativeLabel]] = None,
58-
**kwargs,
59-
):
57+
visibility: list[RelativeLabel] | None = None,
58+
**kwargs: Any,
59+
) -> None:
6060
pass
6161

6262

63-
_PROTO_ASPECT: List[Tuple[str, ProtoAspectCallable]] = []
63+
_PROTO_ASPECT: list[tuple[str, ProtoAspectCallable]] = []
6464

6565

66-
def add_proto_aspect(name: str, fn: ProtoAspectCallable):
66+
def add_proto_aspect(name: str, fn: ProtoAspectCallable) -> None:
6767
print(f"Proto aspect: {name}")
6868

6969
_PROTO_ASPECT.append((
@@ -75,8 +75,8 @@ def add_proto_aspect(name: str, fn: ProtoAspectCallable):
7575
def invoke_proto_aspects(
7676
context: InvocationContext,
7777
proto_target: TargetId,
78-
visibility: Optional[List[RelativeLabel]] = None,
79-
**kwargs,
80-
):
78+
visibility: list[RelativeLabel] | None = None,
79+
**kwargs: Any,
80+
) -> None:
8181
for t in _PROTO_ASPECT:
8282
t[1](context, proto_target, visibility, **kwargs)

tools/cmake/bazel_to_cmake/native_rules.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,7 @@
2020
https://github.com/bazelbuild/bazel/tree/master/src/main/starlark/builtins_bzl/common
2121
"""
2222

23-
# pylint: disable=relative-beyond-top-level,invalid-name,missing-function-docstring,g-long-lambda
24-
25-
from typing import List, Optional
23+
# pylint: disable=g-importing-member
2624

2725
from . import native_rules_alias # pylint: disable=unused-import
2826
from . import native_rules_cc # pylint: disable=unused-import
@@ -65,7 +63,7 @@ def package_group(self: InvocationContext, **kwargs):
6563
@register_native_build_rule
6664
def package(
6765
self: InvocationContext,
68-
default_visibility: Optional[List[RelativeLabel]] = None,
66+
default_visibility: list[RelativeLabel] | None = None,
6967
**kwargs,
7068
):
7169
del kwargs
@@ -85,10 +83,10 @@ def existing_rule(self: InvocationContext, name: str):
8583
@register_native_build_rule
8684
def glob(
8785
self: InvocationContext,
88-
include: List[str],
89-
exclude: Optional[List[str]] = None,
86+
include: list[str],
87+
exclude: list[str] | None = None,
9088
allow_empty: bool = True,
91-
) -> List[str]:
89+
) -> list[str]:
9290
package_directory = self.get_source_package_dir(self.caller_package_id)
9391
return starlark_glob(str(package_directory), include, exclude, allow_empty)
9492

@@ -203,4 +201,3 @@ def sh_test(self: InvocationContext, name: str, **kwargs):
203201
del self
204202
del name
205203
del kwargs
206-

tools/cmake/bazel_to_cmake/native_rules_alias.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515

1616
# pylint: disable=relative-beyond-top-level,invalid-name,missing-function-docstring,g-long-lambda
1717
import io
18-
from typing import List, Optional
1918

2019
from .cmake_builder import CMakeBuilder
2120
from .cmake_provider import CMakeAddDependenciesProvider
@@ -41,7 +40,7 @@ def alias(
4140
self: InvocationContext,
4241
name: str,
4342
actual: Configurable[RelativeLabel],
44-
visibility: Optional[List[RelativeLabel]] = None,
43+
visibility: list[RelativeLabel] | None = None,
4544
**kwargs,
4645
):
4746
del kwargs

0 commit comments

Comments
 (0)