forked from googleapis/synthtool
/
java.py
317 lines (270 loc) · 10.7 KB
/
java.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import os
import xml.etree.ElementTree as ET
import requests
import synthtool as s
import synthtool.gcp as gcp
from synthtool import cache
from synthtool import log
from synthtool import shell
from pathlib import Path
from typing import Optional
JAR_DOWNLOAD_URL = "https://github.com/google/google-java-format/releases/download/google-java-format-{version}/google-java-format-{version}-all-deps.jar"
DEFAULT_FORMAT_VERSION = "1.7"
GOOD_LICENSE = """
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"""
PROTOBUF_HEADER = "// Generated by the protocol buffer compiler. DO NOT EDIT!"
BAD_LICENSE = """/\\*
\\* Copyright \\d{4} Google LLC
\\*
\\* Licensed under the Apache License, Version 2.0 \\(the "License"\\); you may not use this file except
\\* in compliance with the License. You may obtain a copy of the License at
\\*
\\* http://www.apache.org/licenses/LICENSE-2.0
\\*
\\* Unless required by applicable law or agreed to in writing, software distributed under the License
\\* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
\\* or implied. See the License for the specific language governing permissions and limitations under
\\* the License.
\\*/
"""
def format_code(
path: str, version: str = DEFAULT_FORMAT_VERSION, times: int = 2
) -> None:
"""
Runs the google-java-format jar against all .java files found within the
provided path.
"""
jar_name = f"google-java-format-{version}.jar"
jar = cache.get_cache_dir() / jar_name
if not jar.exists():
_download_formatter(version, jar)
# Find all .java files in path and run the formatter on them
files = list(glob.iglob(os.path.join(path, "**/*.java"), recursive=True))
# Run the formatter as a jar file
log.info("Running java formatter on {} files".format(len(files)))
for _ in range(times):
shell.run(["java", "-jar", str(jar), "--replace"] + files)
def _download_formatter(version: str, dest: Path) -> None:
log.info("Downloading java formatter")
url = JAR_DOWNLOAD_URL.format(version=version)
response = requests.get(url)
response.raise_for_status()
with open(dest, "wb") as fh:
fh.write(response.content)
def fix_proto_headers(proto_root: Path) -> None:
s.replace(
[proto_root / "src/**/*.java"],
PROTOBUF_HEADER,
f"{GOOD_LICENSE}{PROTOBUF_HEADER}",
)
# https://github.com/googleapis/gapic-generator/issues/3074
s.replace(
[proto_root / "src/**/*Name.java", proto_root / "src/**/*Names.java"],
BAD_LICENSE,
GOOD_LICENSE,
)
def fix_grpc_headers(grpc_root: Path, package_name: str) -> None:
s.replace(
[grpc_root / "src/**/*.java"],
f"package {package_name};",
f"{GOOD_LICENSE}package {package_name};",
)
def latest_maven_version(group_id: str, artifact_id: str) -> Optional[str]:
"""Helper function to find the latest released version of a Maven artifact.
Fetches metadata from Maven Central and parses out the latest released
version.
Args:
group_id (str): The groupId of the Maven artifact
artifact_id (str): The artifactId of the Maven artifact
Returns:
The latest version of the artifact as a string or None
"""
group_path = "/".join(group_id.split("."))
url = (
f"https://repo1.maven.org/maven2/{group_path}/{artifact_id}/maven-metadata.xml"
)
response = requests.get(url)
response.raise_for_status()
return version_from_maven_metadata(response.text)
def version_from_maven_metadata(metadata: str) -> Optional[str]:
"""Helper function to parse the latest released version from the Maven
metadata XML file.
Args:
metadata (str): The XML contents of the Maven metadata file
Returns:
The latest version of the artifact as a string or None
"""
root = ET.fromstring(metadata)
latest = root.find("./versioning/latest")
if latest is not None:
return latest.text
return None
def _common_generation(
service: str,
version: str,
library: Path,
package_pattern: str,
suffix: str = "",
destination_name: str = None,
):
"""Helper function to execution the common generation cleanup actions.
Fixes headers for protobuf classes and generated gRPC stub services. Copies
code and samples to their final destinations by convention. Runs the code
formatter on the generated code.
Args:
service (str): Name of the service.
version (str): Service API version.
library (Path): Path to the temp directory with the generated library.
package_pattern (str): Package name template for fixing file headers.
suffix (str, optional): Suffix that the generated library folder. The
artman output differs from bazel's output directory. Defaults to "".
destination_name (str, optional): Override the service name for the
destination of the output code. Defaults to the service name.
"""
if destination_name is None:
destination_name = service
package_name = package_pattern.format(service=service, version=version)
fix_proto_headers(library / f"proto-google-cloud-{service}-{version}{suffix}")
fix_grpc_headers(
library / f"grpc-google-cloud-{service}-{version}{suffix}", package_name
)
s.copy(
[library / f"gapic-google-cloud-{service}-{version}{suffix}/src"],
f"google-cloud-{destination_name}/src",
)
s.copy(
[library / f"grpc-google-cloud-{service}-{version}{suffix}/src"],
f"grpc-google-cloud-{destination_name}-{version}/src",
)
s.copy(
[library / f"proto-google-cloud-{service}-{version}{suffix}/src"],
f"proto-google-cloud-{destination_name}-{version}/src",
)
s.copy(
[library / f"gapic-google-cloud-{service}-{version}{suffix}/samples/src"],
"samples/src",
excludes=["**/*.manifest.yaml"],
)
s.copy(
[library / f"gapic-google-cloud-{service}-{version}{suffix}/samples/resources"],
"samples/resources",
)
s.copy(
[
library
/ f"gapic-google-cloud-{service}-{version}{suffix}/samples/src/**/*.manifest.yaml"
],
f"samples/src/main/java/com/google/cloud/examples/{service}/{version}/{service}.manifest.yaml",
)
format_code(f"google-cloud-{destination_name}/src")
format_code(f"grpc-google-cloud-{destination_name}-{version}/src")
format_code(f"proto-google-cloud-{destination_name}-{version}/src")
format_code("samples/src")
def gapic_library(
service: str,
version: str,
config_pattern: str = "/google/cloud/{service}/artman_{service}_{version}.yaml",
package_pattern: str = "com.google.cloud.{service}.{version}",
gapic: gcp.GAPICGenerator = None,
destination_name: str = None,
**kwargs,
) -> Path:
"""Generate a Java library using the gapic-generator via artman via Docker.
Generates code into a temp directory, fixes missing header fields, and
copies into the expected locations.
Args:
service (str): Name of the service.
version (str): Service API version.
config_pattern (str, optional): Path template to artman config YAML
file. Defaults to "/google/cloud/{service}/artman_{service}_{version}.yaml"
package_pattern (str, optional): Package name template for fixing file
headers. Defaults to "com.google.cloud.{service}.{version}".
gapic (GAPICGenerator, optional): Generator instance.
destination_name (str, optional): Override the service name for the
destination of the output code. Defaults to the service name.
**kwargs: Additional options for gapic.java_library()
Returns:
The path to the temp directory containing the generated client.
"""
if gapic is None:
gapic = gcp.GAPICGenerator()
library = gapic.java_library(
service=service,
version=version,
config_path=config_pattern.format(service=service, version=version),
artman_output_name="",
include_samples=True,
**kwargs,
)
_common_generation(
service=service,
version=version,
library=library,
package_pattern=package_pattern,
destination_name=destination_name,
)
return library
def bazel_library(
service: str,
version: str,
package_pattern: str = "com.google.cloud.{service}.{version}",
gapic: gcp.GAPICBazel = None,
destination_name: str = None,
**kwargs,
) -> Path:
"""Generate a Java library using the gapic-generator via bazel.
Generates code into a temp directory, fixes missing header fields, and
copies into the expected locations.
Args:
service (str): Name of the service.
version (str): Service API version.
package_pattern (str, optional): Package name template for fixing file
headers. Defaults to "com.google.cloud.{service}.{version}".
gapic (GAPICBazel, optional): Generator instance.
destination_name (str, optional): Override the service name for the
destination of the output code. Defaults to the service name.
**kwargs: Additional options for gapic.java_library()
Returns:
The path to the temp directory containing the generated client.
"""
if gapic is None:
gapic = gcp.GAPICBazel()
library = gapic.java_library(service=service, version=version, **kwargs)
_common_generation(
service=service,
version=version,
library=library / f"google-cloud-{service}-{version}-java",
package_pattern=package_pattern,
suffix="-java",
destination_name=destination_name,
)
return library