|
1 | 1 | import os |
2 | 2 | import pathlib |
| 3 | +import re |
3 | 4 | import shutil |
4 | 5 |
|
5 | 6 | from typing import List |
6 | 7 | from argparse import ArgumentParser |
7 | 8 |
|
8 | | -from grpc_tools import command |
| 9 | +_GRPC_VERSION_GATE_RE = re.compile( |
| 10 | + r"GRPC_GENERATED_VERSION = '[^']+'\n" |
| 11 | + r"GRPC_VERSION = grpc\.__version__\n" |
| 12 | + r"_version_not_supported = False\n\n" |
| 13 | + r"try:\n" |
| 14 | + r" from grpc\._utilities import first_version_is_lower\n" |
| 15 | + r" _version_not_supported = first_version_is_lower\(GRPC_VERSION, GRPC_GENERATED_VERSION\)\n" |
| 16 | + r"except ImportError:\n" |
| 17 | + r" _version_not_supported = True\n\n" |
| 18 | + r"if _version_not_supported:\n" |
| 19 | + r" raise RuntimeError\(\n" |
| 20 | + r"(?: .+\n)+" |
| 21 | + r" \)\n" |
| 22 | +) |
| 23 | + |
| 24 | + |
| 25 | +def strip_grpc_version_gate(content: str) -> str: |
| 26 | + """Remove grpcio-tools version gate from generated *_grpc.py stubs.""" |
| 27 | + updated = _GRPC_VERSION_GATE_RE.sub("", content) |
| 28 | + if updated != content: |
| 29 | + updated = updated.replace("import warnings\n", "") |
| 30 | + return updated |
| 31 | + |
| 32 | + |
| 33 | +def strip_grpc_version_gate_from_tree(rootdir: str) -> None: |
| 34 | + for dirpath, _, fnames in os.walk(rootdir): |
| 35 | + for fname in fnames: |
| 36 | + if not fname.endswith("_grpc.py"): |
| 37 | + continue |
| 38 | + |
| 39 | + path = os.path.join(dirpath, fname) |
| 40 | + with open(path, "r+t") as f: |
| 41 | + content = f.read() |
| 42 | + updated = strip_grpc_version_gate(content) |
| 43 | + if updated == content: |
| 44 | + continue |
| 45 | + f.seek(0) |
| 46 | + f.write(updated) |
| 47 | + f.truncate() |
9 | 48 |
|
10 | 49 |
|
11 | 50 | def files_filter(dir, items: List[str]) -> List[str]: |
@@ -56,11 +95,18 @@ def fix_file_contents(rootdir, protobuf_version: str): |
56 | 95 |
|
57 | 96 | # Add ignore style check |
58 | 97 | content = content.replace("# -*- coding: utf-8 -*-", "# -*- coding: utf-8 -*-\n" + flake_ignore_line) |
| 98 | + |
| 99 | + if fname.endswith("_grpc.py"): |
| 100 | + content = strip_grpc_version_gate(content) |
| 101 | + |
59 | 102 | f.seek(0) |
60 | 103 | f.write(content) |
| 104 | + f.truncate() |
61 | 105 |
|
62 | 106 |
|
63 | 107 | def generate_protobuf(src_proto_dir: str, dst_dir, protobuf_version: str): |
| 108 | + from grpc_tools import command |
| 109 | + |
64 | 110 | shutil.rmtree(dst_dir, ignore_errors=True) |
65 | 111 |
|
66 | 112 | shutil.copytree(src_proto_dir, dst_dir, ignore=files_filter) |
|
0 commit comments