-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathgenerate-from-proto.py
190 lines (144 loc) · 5.42 KB
/
generate-from-proto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import argparse
import fnmatch
import os
import shutil
import tempfile
import zipfile
from grpc_tools import protoc
import requests
def protofiles(proto_dir, proto_names):
files = []
for (dirpath, _, filenames) in os.walk(proto_dir):
for filename in filenames:
for protoname in proto_names:
if fnmatch.fnmatch(filename, protoname):
full_name = os.path.join(dirpath, filename)
relative_name = os.path.relpath(full_name, proto_dir)
files.append(relative_name)
return files
def generate(includes, protofile, other_args):
cli_params = []
for inc in includes:
cli_params.append(f"-I{inc}")
cli_params.append(protofile)
for arg in other_args:
cli_params.append(arg)
protoc.main(cli_params)
def create_module_directory(directory, confirm_deletions):
path = os.path.abspath(directory)
if os.path.exists(path):
if confirm_deletions:
confirmation = input(f"Delete {path} and all its contents? (y/N) ")
if confirmation.lower() != "y":
return None
# WARNING: Data deleting operation below!
shutil.rmtree(path)
os.mkdir(path)
return path
def download(url, filename):
with requests.get(url, stream=True) as req:
req.raise_for_status()
with open(filename, "wb") as f:
f.write(req.raw.read())
def fetch_repo(repo_name, branch, dir_name):
# Github convention for downloading as zip:
repo_zip_url = f"https://github.com/{repo_name}/archive/refs/heads/{branch}.zip"
# Name downloaded zip file for end of repo_name
repo_zip_name = f"{repo_name.split('/')[1]}.zip"
repo_zip_path = os.path.join(dir_name, repo_zip_name)
download(repo_zip_url, repo_zip_path)
zipfile.ZipFile(repo_zip_path).extractall(path=dir_name)
repo_root_path = os.path.join(dir_name, f"{repo_name.split('/')[1]}-{branch}")
return repo_root_path
def generate_code_for_protos(proto_path, std_proto_path, module_path):
print(f"Generating code for protos:")
for fname in protofiles(f"{proto_path}/proto", ["data.proto"]):
print(f" {fname}")
generate(
[
"/usr/include",
f"{proto_path}/proto",
f"{proto_path}/third_party/googleapis/",
f"{std_proto_path}/src/",
],
fname,
[
f"--python_gapic_out={module_path}",
],
)
def generate_code_for_dependencies(proto_path, std_proto_path, module_path):
print(f"Generating code for protobuf dependencies:")
for fname in protofiles(f"{proto_path}/third_party/googleapis", ["*.proto"]):
print(f" {fname}")
generate(
[
"/usr/include",
f"{proto_path}/proto",
f"{proto_path}/third_party/googleapis/",
f"{std_proto_path}/src/",
],
fname,
[
f"--pyi_out={module_path}",
f"--python_out={module_path}",
],
)
def generate_module(module_dir, proto_repo, branch, do_not_confirm_actions):
module_path = create_module_directory(module_dir, not do_not_confirm_actions)
if module_path is None:
print("Operation aborted by user.")
return False
print(f"Created temp working director {module_path}")
with tempfile.TemporaryDirectory() as tempdir:
# Fetch repo with cloudevent proto definitions
print(f"Fetching proto repo from {proto_repo}")
proto_path = fetch_repo(proto_repo, branch, tempdir)
# Fetch repo with referenced common protos (e.g., timestamp)
print(f"Fetching protobuf repo from {proto_repo}")
std_proto_path = fetch_repo("protocolbuffers/protobuf", "main", tempdir)
output_path = os.path.join(tempdir, "output_path")
os.mkdir(output_path)
generate_code_for_protos(proto_path, std_proto_path, output_path)
generate_code_for_dependencies(proto_path, std_proto_path, output_path)
os.mkdir(os.path.join(module_path, "google"))
shutil.move(
os.path.join(output_path, "google", "events"),
os.path.join(module_path, "google"),
)
return True
if __name__ == "__main__":
parser = argparse.ArgumentParser(
prog="Generate Google Cloudevents Python library",
description="Creates a new Python module for Google Cloudevents",
)
parser.add_argument(
"-o",
"--output",
required=True,
help="Directory to write the module source. "
"Will be created if necessary. "
"WARNING - preexisting contents will be deleted!",
)
parser.add_argument(
"-r",
"--repo",
help="GitHub repo containing protofiles for Cloud events",
default="googleapis/google-cloudevents",
)
parser.add_argument(
"-b",
"--branch",
help="Repo branch to fetch",
default="main",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="do not confirm any steps (even data destructive ones)",
)
args = parser.parse_args()
if generate_module(args.output, args.repo, args.branch, args.quiet):
print(f"Module generation complete. Source is at {args.output}")
else:
print(f"Module generation failed. See error output for details.")