Skip to content

Commit 972ed09

Browse files
scripts: check in library generation script
Also update build_twilio_library.py to use subprocess instead of shelling out to os.system.
1 parent 19849ce commit 972ed09

File tree

2 files changed

+124
-11
lines changed

2 files changed

+124
-11
lines changed

scripts/build_twilio_library.py

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,13 @@
22
import json
33
import os
44
import re
5+
import shlex
56
import shutil
7+
import subprocess
68
from pathlib import Path
79
from typing import List, Tuple
810

11+
912
from clean_unused_imports import remove_unused_imports, remove_duplicate_imports
1013
from process_orgs_api import preprocess_orgs_spec
1114

@@ -88,18 +91,34 @@ def generate_domain_for_language(spec_file: str, config_path: str, spec_folder:
8891
with open(full_config_path, 'w') as f:
8992
f.write(json.dumps(config))
9093

91-
9294
def run_openapi_generator(parent_dir: Path, language: str) -> None:
93-
properties = '-DapiTests=false'
94-
if language in {'node', 'python'}:
95-
properties += ' -DskipFormModel=false'
96-
97-
command = f'cd {parent_dir} && java {properties} ' \
98-
f'-cp target/twilio-openapi-generator.jar ' \
99-
f'org.openapitools.codegen.OpenAPIGenerator batch {CONFIG_FOLDER}/{language}/*'
100-
101-
if os.system(command + '> /dev/null') != 0: # Suppress stdout
102-
raise RuntimeError()
95+
properties = "-DapiTests=false"
96+
if language in {"node", "python"}:
97+
properties += " -DskipFormModel=false"
98+
99+
command = [
100+
"java",
101+
*properties.split(), # Splits e.g. "-DapiTests=false -DskipFormModel=false" into separate arguments
102+
"-cp",
103+
"target/twilio-openapi-generator.jar",
104+
"org.openapitools.codegen.OpenAPIGenerator",
105+
"batch",
106+
f"{CONFIG_FOLDER}/{language}/*"
107+
]
108+
109+
printable_cmd = " ".join(shlex.quote(arg) for arg in command)
110+
print(f"Running command: {printable_cmd}")
111+
112+
try:
113+
subprocess.run(
114+
command,
115+
cwd=parent_dir, # Change working directory to parent_dir
116+
check=True, # Raise CalledProcessError on non-zero exit
117+
stdout=subprocess.DEVNULL, # Suppress standard output
118+
)
119+
except subprocess.CalledProcessError as exc:
120+
# Wrap the original exception for more informative error handling
121+
raise RuntimeError("OpenAPI generation failed.") from exc
103122

104123

105124
def get_domain_info(oai_spec_location: str, domain: str, is_file: bool = False) -> Tuple[str, str, str]:

scripts/generate_libraries/main.py

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#!/usr/bin/env python3
2+
3+
import argparse
4+
import glob
5+
import os
6+
import scripts.build_twilio_library as build_library
7+
8+
9+
def parse_args():
10+
parser = argparse.ArgumentParser(
11+
description="Generate files for Twilio library in different languages."
12+
)
13+
parser.add_argument(
14+
"--language",
15+
choices=["csharp", "java", "node", "php", "go", "python", "ruby", "terraform"],
16+
required=True,
17+
help="Specify the target language for code generation."
18+
)
19+
parser.add_argument(
20+
"--base",
21+
default=".",
22+
help="Base directory for code generation. Defaults to current directory."
23+
)
24+
parser.add_argument(
25+
"--input",
26+
default=None,
27+
help="Path to the OpenAPI spec JSON files. If not specified, defaults to 'spec/json' inside the base directory."
28+
)
29+
return parser.parse_args()
30+
31+
32+
def get_output_dir(base, language):
33+
"""
34+
Constructs the output directory for each language based on the given base path.
35+
Update these paths as needed for your environment or repository layout.
36+
"""
37+
if language == "csharp":
38+
return os.path.join(base, "twilio-csharp/src/Twilio")
39+
elif language == "java":
40+
return os.path.join(base, "twilio-java/src/main/java/com/twilio")
41+
elif language == "node":
42+
return os.path.join(base, "twilio-node/src")
43+
elif language == "php":
44+
return os.path.join(base, "twilio-php/src/Twilio")
45+
elif language == "go":
46+
return os.path.join(base, "twilio-go")
47+
elif language == "python":
48+
return os.path.join(base, "twilio-python/twilio")
49+
elif language == "ruby":
50+
return os.path.join(base, "twilio-ruby/lib/twilio-ruby")
51+
elif language == "terraform":
52+
return os.path.join(base, "terraform-provider-twilio")
53+
else:
54+
return None
55+
56+
57+
def generate_files(input_dir, output_dir, language):
58+
# If needed, you can iterate over the input spec files here using glob:
59+
# for filepath in glob.glob(os.path.join(input_dir, "*.json")):
60+
# print(filepath)
61+
build_library.build(input_dir, output_dir, language)
62+
63+
64+
def main():
65+
args = parse_args()
66+
67+
# Determine input directory
68+
input_dir = args.input if args.input else os.path.join(args.base, "spec/json")
69+
70+
# Determine output directory for the chosen language
71+
output_dir = get_output_dir(args.base, args.language)
72+
73+
if not output_dir:
74+
print("Unsupported language or path couldn't be resolved.")
75+
return
76+
77+
# Ensure the output directory exists
78+
os.makedirs(output_dir, exist_ok=True)
79+
80+
# Run a make install (if needed for your environment)
81+
os.system("make install")
82+
83+
# Generate files
84+
generate_files(input_dir, output_dir, args.language)
85+
86+
# Optional language-specific post-processing
87+
if args.language == "go":
88+
os.chdir(output_dir)
89+
os.system("go fmt ./...")
90+
os.system("goimports -w .")
91+
92+
93+
if __name__ == "__main__":
94+
main()

0 commit comments

Comments
 (0)