Skip to content

Commit 66dfd0e

Browse files
authored
Merge pull request #37 from geo-engine/fetch-backend
fetch openapi from repo
2 parents 5dba355 + 67ea06b commit 66dfd0e

File tree

23 files changed

+118
-152
lines changed

23 files changed

+118
-152
lines changed

.generation/README.md

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,6 @@ Auto-generated Python Client API for Geo Engine
77
- Python
88
- Podman
99

10-
# Requirements
11-
12-
- Postgres instance running on `localhost:5432` with
13-
- `geoengine:geoengine` credentials and
14-
- `geoengine` database
15-
1610
# Generation
1711

1812
From the root of the repository run:
@@ -26,9 +20,8 @@ From the root of the repository run:
2620
To fetch the OpenAPI spec from the backend, run:
2721

2822
```bash
29-
cargo run
30-
wget http://localhost:3030/api/api-docs/openapi.json -O - \
31-
| python -m json.tool --indent 2 > .generation/input/openapi.json
23+
wget -O .generation/input/openapi.json \
24+
https://raw.githubusercontent.com/geo-engine/geoengine/refs/heads/main/openapi.json
3225
```
3326

3427
To run the generation in dev mode, run:
@@ -45,7 +38,7 @@ It will also stop building the customized generator container.
4538
To update the config.ini file, run:
4639

4740
```bash
48-
.generation/update_config.py --backendTag pro-nightly-2023-11-28
41+
.generation/update_config.py --backendCommit 1076a616369dcc33e86b422a9364ac99553a18f8
4942
```
5043

51-
This will set a new backend tag and increment the version number.
44+
This will set a new backend commit hash and increment the version number.

.generation/config.ini

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
[input]
2-
backendTag = nightly-2025-03-14
2+
backendCommit = 1076a616369dcc33e86b422a9364ac99553a18f8
33

44
[general]
55
githubUrl = https://github.com/geo-engine/openapi-client
6+
version = 0.0.23
67

78
[python]
89
name = geoengine_openapi_client
9-
version = 0.0.22
10+
1011

1112
[typescript]
1213
name = @geoengine/openapi-client
13-
version = 0.0.22
14-

.generation/generate.py

Lines changed: 45 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -9,26 +9,19 @@
99
from dataclasses import dataclass
1010
from pathlib import Path
1111
from urllib import request
12-
from urllib.error import URLError
1312
from urllib.parse import urlsplit
1413
import configparser
15-
import json
1614
import os
1715
import shutil
1816
import subprocess
1917
import sys
20-
import time
2118
from typing import Literal
19+
import logging
2220

2321

2422
CWD = Path('.generation/')
2523

2624

27-
def eprint(*args, **kwargs):
28-
'''Print to stderr.'''
29-
print(*args, file=sys.stderr, **kwargs)
30-
31-
3225
class ProgramArgs(argparse.Namespace):
3326
'''Typed command line arguments.'''
3427
language: Literal['python', 'typescript']
@@ -55,18 +48,17 @@ def parse_arguments() -> ProgramArgs:
5548
class ConfigArgs():
5649
'''Typed config.ini arguments.'''
5750
# Backend version
58-
ge_backend_tag: str
51+
ge_backend_commit: str
5952

6053
# General
6154
github_url: str
55+
package_version: str
6256

6357
# Python package name
6458
python_package_name: str
65-
python_package_version: str
6659

6760
# TypeScript package name
6861
typescript_package_name: str
69-
typescript_package_version: str
7062

7163
@staticmethod
7264
def parse_config() -> ConfigArgs:
@@ -76,66 +68,32 @@ def parse_config() -> ConfigArgs:
7668
parsed.read(CWD / 'config.ini')
7769

7870
return ConfigArgs(
79-
ge_backend_tag=parsed['input']['backendTag'],
71+
ge_backend_commit=parsed['input']['backendCommit'],
8072
github_url=parsed['general']['githubUrl'],
73+
package_version=parsed['general']['version'],
8174
python_package_name=parsed['python']['name'],
82-
python_package_version=parsed['python']['version'],
8375
typescript_package_name=parsed['typescript']['name'],
84-
typescript_package_version=parsed['typescript']['version'],
8576
)
8677

8778

88-
def fetch_spec(*, ge_backend_tag: str) -> None:
79+
def fetch_spec(*, ge_backend_commit: str) -> None:
8980
'''
90-
Generate the openapi.json file.
91-
92-
Imitating manually fetching it, e.g.
93-
94-
```bash
95-
wget http://localhost:3030/api/api-docs/openapi.json -O - \
96-
| python -m json.tool --indent 2 > .generation/input/openapi.json
97-
```
81+
Copy the openapi.json file from the backend repo.
9882
'''
99-
eprint("Starting Geo Engine backend.")
100-
101-
ge_process = subprocess.Popen(
102-
[
103-
"podman", "run",
104-
"--rm", # remove the container after running
105-
"--network=host", # port 8080 by default
106-
# "-p", "3030:8080",
107-
f"quay.io/geoengine/geoengine:{ge_backend_tag}",
108-
],
109-
env={
110-
'GEOENGINE__POSTGRES__CLEAR_DATABASE_ON_START': 'true',
111-
'PATH': os.environ['PATH'],
112-
},
113-
)
114-
115-
for _ in range(180): # <3 minutes
116-
eprint("Requesting `openapi.json`….")
117-
try:
118-
with request.urlopen(
119-
"http://localhost:8080/api/api-docs/openapi.json",
120-
timeout=10,
121-
) as w:
122-
api_json = json.load(w)
12383

124-
with open(CWD / "input/openapi.json", "w", encoding='utf-8') as f:
125-
json.dump(api_json, f, indent=2)
84+
request_url = f"https://raw.githubusercontent.com/geo-engine/geoengine/{ge_backend_commit}/openapi.json"
12685

127-
eprint("Stored `openapi.json`.")
128-
break
129-
except URLError as _e:
130-
pass # try again
131-
time.sleep(1) # 1 second
86+
logging.info(f"Requesting `openapi.json` at `{request_url}`….")
87+
with request.urlopen(request_url, timeout=10) as w, \
88+
open(CWD / "input/openapi.json", "w", encoding='utf-8') as f:
89+
f.write(w.read().decode('utf-8'))
13290

133-
eprint("Stopping Geo Engine backend.")
134-
ge_process.kill()
91+
logging.info("Stored `openapi.json`.")
13592

13693

13794
def build_container():
13895
'''Build the patched generator image'''
96+
logging.info("Building patched generator image…")
13997
subprocess.run(
14098
[
14199
"podman", "build",
@@ -144,12 +102,15 @@ def build_container():
144102
],
145103
check=True,
146104
)
105+
logging.info("Patched generator image built.")
147106

148107

149108
def clean_dirs(*, language: Literal['python', 'typescript']):
150109
'''Remove some directories because they are not be overwritten by the generator.'''
151110

152111
dirs_to_remove = [
112+
'node_modules',
113+
'.mypy_cache',
153114
Path(language) / 'test'
154115
]
155116

@@ -158,20 +119,25 @@ def clean_dirs(*, language: Literal['python', 'typescript']):
158119
dirs_to_remove.extend([
159120
Path(language) / 'src',
160121
Path(language) / 'dist',
122+
Path(language) / 'node_modules',
161123
])
162124
case 'python':
163125
dirs_to_remove.extend([
164126
Path(language) / 'geoengine_openapi_client',
165127
])
166128

129+
logging.info(f"Removing directories:")
130+
167131
for the_dir in dirs_to_remove:
168132
if not os.path.isdir(the_dir):
169133
continue
134+
logging.info(f" - {the_dir}")
170135
shutil.rmtree(the_dir)
171136

172137

173138
def generate_python_code(*, package_name: str, package_version: str, package_url: str):
174139
'''Run the generator.'''
140+
175141
subprocess.run(
176142
[
177143
"podman", "run",
@@ -242,43 +208,53 @@ def generate_typescript_code(*, npm_name: str, npm_version: str, repository_url:
242208

243209
def main():
244210
'''The entry point of the program'''
211+
212+
# Set up logging
213+
logging.basicConfig(
214+
level=logging.INFO,
215+
format='[%(levelname)s] %(message)s'
216+
)
217+
245218
args = ProgramArgs.parse_arguments()
246219
config = ConfigArgs.parse_config()
247220

248221
if args.fetch_spec:
249-
fetch_spec(ge_backend_tag=config.ge_backend_tag)
222+
fetch_spec(ge_backend_commit=config.ge_backend_commit)
250223

251224
if args.build_container:
252225
build_container()
253226

254227
clean_dirs(language=args.language)
255228

256229
if args.language == 'python':
230+
logging.info("Generating Python client…")
257231
generate_python_code(
258232
package_name=config.python_package_name,
259-
package_version=config.python_package_version,
233+
package_version=config.package_version,
260234
package_url=config.github_url,
261235
)
262236
elif args.language == 'typescript':
237+
logging.info("Generating TypeScript client…")
263238
generate_typescript_code(
264239
npm_name=config.typescript_package_name,
265-
npm_version=config.typescript_package_version,
240+
npm_version=config.package_version,
266241
repository_url=config.github_url,
267242
)
268243

269244
# Create dist files.
270245
# This is necessary for using the package directly from the git repo for development.
246+
logging.info("Creating dist files…")
271247
subprocess.run(
272-
[
273-
"podman", "run",
274-
"--rm", # remove the container after running
275-
"-v", f"{os.getcwd()}:/local",
276-
"--workdir=/local/typescript", # set working directory
277-
"docker.io/node:lts-alpine3.19",
278-
"npm", "install",
279-
],
280-
check=True,
281-
)
248+
[
249+
"podman", "run",
250+
"--rm", # remove the container after running
251+
"-v", f"{os.getcwd()}/typescript:/local/typescript",
252+
"--workdir=/local/typescript", # set working directory
253+
"docker.io/node:lts-alpine3.20",
254+
"npm", "install",
255+
],
256+
check=True,
257+
)
282258
else:
283259
raise RuntimeError(f'Unknown language {args.language}.')
284260

.generation/post-process/python.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def api_client_py(file_contents: List[str]) -> Generator[str, None, None]:
2020

2121
if dedented_line.startswith('self.user_agent = '):
2222
line = indent(dedent(f'''\
23-
self.user_agent = 'geoengine/openapi-client/python/{version('python')}'
23+
self.user_agent = 'geoengine/openapi-client/python/{version()}'
2424
'''), 2 * INDENT)
2525

2626
yield line

.generation/post-process/typescript.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def runtime_ts(file_contents: List[str]) -> Generator[str, None, None]:
1919
line = dedent(f'''\
2020
export const DefaultConfig = new Configuration({{
2121
headers: {{
22-
'User-Agent': 'geoengine/openapi-client/typescript/{version("typescript")}'
22+
'User-Agent': 'geoengine/openapi-client/typescript/{version()}'
2323
}}
2424
}});
2525
''')

.generation/post-process/util.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,9 @@ def modify_file(input_path: Path,
2929
for line in modify_fn(file_contents):
3030
f.write(line)
3131

32-
def version(language: str) -> str:
33-
'''Get the version number for a given language from the `config.ini`.'''
34-
35-
# Use `Literal['python', 'typescript']` in Python version >= 3.8
36-
if language not in ['python', 'typescript']:
37-
raise ValueError(f'Language {language} not supported.')
32+
def version() -> str:
33+
'''Get the version number for the packages from the `config.ini`.'''
3834

3935
config = configparser.ConfigParser()
4036
config.read(INI_FILE)
41-
return config[language]['version']
37+
return config['general']['version']

.generation/update_config.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
INI_FILE = CWD / 'config.ini'
1414

1515
parser = argparse.ArgumentParser(description='Update the config.ini file.')
16-
parser.add_argument('--backendTag', dest='backend_tag',
16+
parser.add_argument('--backendCommit', dest='backend_commit',
1717
required=True, type=str)
1818

1919
args = parser.parse_args()
@@ -22,17 +22,16 @@
2222
config.optionxform = str # do not convert keys to lowercase
2323
config.read(INI_FILE)
2424

25-
config['input']['backendTag'] = args.backend_tag
26-
27-
for language in ['python', 'typescript']:
28-
# retrieve version
29-
version_digits: list[int] = [
30-
int(digit) for digit in config[language]['version'].split('.')]
31-
# increment last version digit
32-
version_digits[-1] += 1
33-
# write back
34-
config[language]['version'] = '.'.join(
35-
str(digit) for digit in version_digits)
25+
config['input']['backendCommit'] = args.backend_commit
26+
27+
# retrieve version
28+
version_digits: list[int] = [
29+
int(digit) for digit in config['general']['version'].split('.')]
30+
# increment last version digit
31+
version_digits[-1] += 1
32+
# write back
33+
config['general']['version'] = '.'.join(
34+
str(digit) for digit in version_digits)
3635

3736
with open(INI_FILE, 'w', encoding='utf-8') as f:
3837
config.write(f)

0 commit comments

Comments
 (0)