Add support for pydantic dataclasses (#406)

This commit is contained in:
Samuel Yvon
2023-02-13 07:37:16 -08:00
committed by GitHub
parent 6df8cef3f0
commit 13d656587c
11 changed files with 283 additions and 19 deletions

View File

@@ -1,7 +1,10 @@
import asyncio
import atexit
import importlib
import os
import platform
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path
from types import ModuleType
@@ -22,6 +25,7 @@ root_path = Path(__file__).resolve().parent
inputs_path = root_path.joinpath("inputs")
output_path_reference = root_path.joinpath("output_reference")
output_path_betterproto = root_path.joinpath("output_betterproto")
output_path_betterproto_pydantic = root_path.joinpath("output_betterproto_pydantic")
def get_files(path, suffix: str) -> Generator[str, None, None]:
@@ -36,19 +40,56 @@ def get_directories(path):
async def protoc(
path: Union[str, Path], output_dir: Union[str, Path], reference: bool = False
path: Union[str, Path],
output_dir: Union[str, Path],
reference: bool = False,
pydantic_dataclasses: bool = False,
):
path: Path = Path(path).resolve()
output_dir: Path = Path(output_dir).resolve()
python_out_option: str = "python_betterproto_out" if not reference else "python_out"
command = [
sys.executable,
"-m",
"grpc.tools.protoc",
f"--proto_path={path.as_posix()}",
f"--{python_out_option}={output_dir.as_posix()}",
*[p.as_posix() for p in path.glob("*.proto")],
]
if pydantic_dataclasses:
plugin_path = Path("src/betterproto/plugin/main.py")
if "Win" in platform.system():
with tempfile.NamedTemporaryFile(
"w", encoding="UTF-8", suffix=".bat", delete=False
) as tf:
# See https://stackoverflow.com/a/42622705
tf.writelines(
[
"@echo off",
f"\nchdir {os.getcwd()}",
f"\n{sys.executable} -u {plugin_path.as_posix()}",
]
)
tf.flush()
plugin_path = Path(tf.name)
atexit.register(os.remove, plugin_path)
command = [
sys.executable,
"-m",
"grpc.tools.protoc",
f"--plugin=protoc-gen-custom={plugin_path.as_posix()}",
"--experimental_allow_proto3_optional",
"--custom_opt=pydantic_dataclasses",
f"--proto_path={path.as_posix()}",
f"--custom_out={output_dir.as_posix()}",
*[p.as_posix() for p in path.glob("*.proto")],
]
else:
command = [
sys.executable,
"-m",
"grpc.tools.protoc",
f"--proto_path={path.as_posix()}",
f"--{python_out_option}={output_dir.as_posix()}",
*[p.as_posix() for p in path.glob("*.proto")],
]
proc = await asyncio.create_subprocess_exec(
*command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
)