Repository navigation
Expand file tree
/
Copy pathgenerate.py
More file actions
405 lines (355 loc) · 15.8 KB
/
Copy pathgenerate.py
File metadata and controls
405 lines (355 loc) · 15.8 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import importlib.util
import os
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path
from typing import Any
REPO_URL = "https://github.com/camunda/camunda.git"
SPEC_DIR = "zeebe/gateway-protocol/src/main/proto/v2"
SPEC_FILE = "rest-api.yaml"
DEFAULT_SPEC_REF = "main"
def log(msg: str) -> None:
print(msg)
def _resolve_metadata_path(
bundled_spec_input: Path | None, spec_overridden: bool
) -> Path | None:
"""Return the spec-metadata.json that corresponds to the *selected* spec.
The default-tenant injection, semantic types, spec hash and other
post-generation behaviour are driven by bundler metadata. That metadata is
only correct when it was produced from the same spec that is being
generated from; using the committed ``external-spec/bundled/spec-metadata.json``
snapshot while ``--local-spec`` / ``--spec-ref`` / ``--bundled-spec`` selects a
*different* spec silently mislabels operations (issue #489, PR #490 review).
Rules:
- ``--bundled-spec <path>``: the metadata must sit next to the bundled spec —
prefer ``<stem>-metadata.json`` (the bundler's derivation, which names the
exact bundle) over the generic ``spec-metadata.json``. The generic name is
this repo's convention for the *default* bundle (``rest-api.bundle.json``,
as written by ``scripts/bundle-spec.sh``), so it is only accepted when the
selected bundle *is* ``rest-api.bundle.json`` and the directory holds no
other bundles that the generic file could describe instead. If neither
condition yields metadata we cannot trust any other snapshot, so fail
rather than guess.
- ``--local-spec`` / ``--spec-ref`` (legacy jsonref bundling): no matching
metadata is derivable here, so return ``None`` and let the post-gen hooks
skip metadata-driven behaviour instead of applying an unrelated snapshot.
- default (no override): the spec is fetched from *live* upstream ``main``
while the committed snapshot is pinned and drifts from it, so return
``None`` for the same reason. The committed snapshot is used only when
the committed bundle itself is the input (``--bundled-spec
external-spec/bundled/rest-api.bundle.json``, as ``make generate`` does).
"""
if bundled_spec_input is not None:
# The metadata must sit next to the bundled spec. Prefer the bundler's
# ``<stem>-metadata.json`` derivation: it names the exact bundle it was
# produced from, so it is unambiguous. The repo's own convention
# (``spec-metadata.json`` next to ``rest-api.bundle.json``, as produced
# by scripts/bundle-spec.sh) is generic — it describes the *default*
# bundle, so it is only trustworthy when the selected bundle is that
# default bundle and no other bundle in the directory could be the one
# it describes. If neither exists we cannot trust any other snapshot,
# so fail rather than guess.
stem_metadata = bundled_spec_input.with_name(
f"{bundled_spec_input.stem}-metadata.json"
)
if stem_metadata.exists():
return stem_metadata
generic = bundled_spec_input.with_name("spec-metadata.json")
other_bundles = [
p
for p in bundled_spec_input.parent.glob("*.bundle.json")
if p != bundled_spec_input
]
if (
generic.exists()
and bundled_spec_input.name == "rest-api.bundle.json"
and not other_bundles
):
return generic
raise FileNotFoundError(
f"--bundled-spec was given but no matching metadata found next to "
f"{bundled_spec_input} (looked for {stem_metadata.name}"
+ (
f"; {generic.name} is only accepted for the repo's own "
f"rest-api.bundle.json with no other bundles beside it"
if generic.exists()
else f", {generic.name}"
)
+ "). Generate metadata alongside the bundled spec "
"(camunda-schema-bundler --output-metadata) so tenant injection "
"and semantic types reflect the selected spec."
)
if spec_overridden:
log(
"Spec source overridden (--local-spec/--spec-ref): no matching "
"spec-metadata.json is available, so metadata-driven post-gen steps "
"(default-tenant injection, semantic types, SPEC_HASH emission) are "
"skipped "
"rather than applied from the unrelated committed snapshot."
)
return None
# No override: the spec is fetched from live upstream ``main`` while the
# committed snapshot is pinned to the ref ``make bundle-spec`` last ran
# with, so it drifts from the fetched spec. Treat this like an override and
# skip metadata-driven behaviour; the committed snapshot is used only when
# the committed bundle itself is the input (handled above).
log(
"Spec fetched from live upstream main: the committed "
"external-spec/bundled/spec-metadata.json snapshot is pinned and may "
"not match, so metadata-driven post-gen steps (default-tenant "
"injection, semantic types, SPEC_HASH emission) are skipped. Use "
"make generate (which bundles first and passes --bundled-spec) to "
"generate with metadata."
)
return None
def _should_run_acceptance_tests(
skip_tests: bool, skip_generate: bool, metadata_available: bool
) -> bool:
"""Decide whether the acceptance suite can meaningfully validate this run.
The acceptance suite asserts metadata-driven output (``SPEC_HASH``,
default-tenant injection). When generation ran without matching metadata
(live-fetch / overridden spec), those steps were intentionally skipped, so
running the suite would fail on behaviour that was deliberately omitted.
"""
if skip_tests:
return False
if not skip_generate and not metadata_available:
return False
return True
def ensure_cache_dir(cache_dir: Path) -> None:
cache_dir.mkdir(parents=True, exist_ok=True)
def fetch_spec(cache_dir: Path, ref: str) -> Path:
"""Clone repo sparsely and return path to the spec."""
ensure_cache_dir(cache_dir)
repo_dir = cache_dir / "camunda"
spec_path = repo_dir / SPEC_DIR / SPEC_FILE
try:
if not repo_dir.exists():
log("Initializing sparse clone...")
repo_dir.mkdir(parents=True, exist_ok=True)
subprocess.run(["git", "init"], cwd=str(repo_dir), check=True)
subprocess.run(
["git", "remote", "add", "origin", REPO_URL],
cwd=str(repo_dir),
check=True,
)
subprocess.run(
["git", "config", "core.sparseCheckout", "true"],
cwd=str(repo_dir),
check=True,
)
sparse_checkout_file = repo_dir / ".git" / "info" / "sparse-checkout"
sparse_checkout_file.parent.mkdir(parents=True, exist_ok=True)
with open(sparse_checkout_file, "w") as f:
f.write(f"{SPEC_DIR}\n")
log("Updating repository...")
# Fetch specific ref
subprocess.run(
["git", "fetch", "--depth", "1", "origin", ref],
cwd=str(repo_dir),
check=True,
)
# Checkout FETCH_HEAD
subprocess.run(
["git", "checkout", "-f", "FETCH_HEAD"], cwd=str(repo_dir), check=True
)
except Exception as e:
log(f"Warning: failed to update/clone remote repo: {e}")
if spec_path.exists():
log(f"Using spec from cache: {spec_path}")
return spec_path
raise FileNotFoundError(f"OpenAPI spec not found at {spec_path}")
def load_hooks(hooks_dir: Path) -> list[Callable[[dict[str, str]], None]]:
hooks: list[Callable[[dict[str, str]], None]] = []
if not hooks_dir.exists():
return hooks
# Make sibling modules (e.g. _identifier_guard) importable by all hooks.
hooks_dir_str = str(hooks_dir.resolve())
if hooks_dir_str not in sys.path:
sys.path.append(hooks_dir_str)
for hook_file in sorted(hooks_dir.glob("*.py")):
spec = importlib.util.spec_from_file_location(hook_file.stem, hook_file)
if spec and spec.loader:
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if hasattr(module, "run") and callable(module.run):
hooks.append(module.run)
return hooks
def run_hooks(
hooks: list[Callable[[dict[str, str]], None]], context: dict[str, str]
) -> None:
for hook in hooks:
log(f"Running hook: {hook.__module__}")
hook(context)
def run_acceptance_tests(root: Path, out_dir: Path) -> None:
log("Running acceptance tests...")
env = os.environ.copy()
existing = env.get("PYTHONPATH", "")
# Ensure generated code is importable by tests
env["PYTHONPATH"] = (
f"{out_dir!s}{os.pathsep}{existing}" if existing else str(out_dir)
)
tests_dir = root / "tests" / "acceptance"
cmd = [sys.executable, "-m", "pytest", "-q", str(tests_dir)]
subprocess.run(cmd, check=True, env=env, cwd=str(root))
def main():
parser = argparse.ArgumentParser(
description="Generate Python SDK for Camunda Orchestration Cluster API"
)
parser.add_argument(
"--out-dir", default="generated", help="Output directory for generated SDK"
)
parser.add_argument(
"--cache-dir", default=".openapi-cache", help="Cache directory for spec repo"
)
parser.add_argument(
"--spec-ref",
default=DEFAULT_SPEC_REF,
help="Git ref/branch/tag for the spec repo",
)
parser.add_argument(
"--generator", default="openapi-python-client", help="OpenAPI generator name"
)
parser.add_argument(
"--config", default="generator-config.yaml", help="Path to generator config"
)
parser.add_argument(
"--skip-generate", action="store_true", help="Skip generation (run hooks only)"
)
parser.add_argument(
"--package-name",
default=None,
help="Override packageName in config (in-memory)",
)
parser.add_argument(
"--skip-tests", action="store_true", help="Skip acceptance tests"
)
parser.add_argument(
"--local-spec", help="Path to local OpenAPI spec file (skips git fetch)"
)
parser.add_argument(
"--bundled-spec",
help="Path to a pre-bundled spec (from camunda-schema-bundler). Skips fetch and bundling.",
)
args = parser.parse_args()
root = Path(__file__).resolve().parent
out_dir = (root / args.out_dir).resolve()
cache_dir = (root / args.cache_dir).resolve()
config_path = (root / args.config).resolve()
bundled_spec_input: Path | None = None
if args.bundled_spec:
bundled_spec_input = Path(args.bundled_spec).resolve()
if not bundled_spec_input.exists():
raise FileNotFoundError(f"Bundled spec not found: {bundled_spec_input}")
log(f"Using pre-bundled spec: {bundled_spec_input}")
spec_path = bundled_spec_input
elif args.local_spec:
spec_path = Path(args.local_spec).resolve()
if not spec_path.exists():
raise FileNotFoundError(f"Local spec file not found: {spec_path}")
log(f"Using local spec: {spec_path}")
else:
spec_path = fetch_spec(cache_dir, args.spec_ref)
# If package name override is provided, create a temp config copy
effective_config = config_path
tmp_config = None
if args.package_name is not None:
import yaml # lazy import
with open(config_path, "r", encoding="utf-8") as f:
cfg: dict[str, Any] = yaml.safe_load(f) or {}
cfg["packageName"] = args.package_name
tmp_config = root / ".openapi-cache" / "generator-config.effective.yaml"
tmp_config.parent.mkdir(parents=True, exist_ok=True)
with open(tmp_config, "w", encoding="utf-8") as f:
yaml.safe_dump(cfg, f, sort_keys=False)
effective_config = tmp_config
metadata_available = True
if not args.skip_generate:
hooks_root = root / "hooks"
pre_gen_hooks_dir = hooks_root / "pre_gen"
post_gen_hooks_dir = hooks_root / "post_gen"
import yaml
out_dir.mkdir(parents=True, exist_ok=True)
bundled_spec_path = out_dir / "bundled_spec.yaml"
if args.bundled_spec:
# Use pre-bundled spec from camunda-schema-bundler
import shutil as _shutil
assert bundled_spec_input is not None
_shutil.copy2(bundled_spec_input, bundled_spec_path)
log(f"Using pre-bundled spec: {bundled_spec_input}")
else:
# Bundle from raw spec
from bundle import bundle_spec
log(f"Bundling spec from {spec_path} to {bundled_spec_path}...")
bundle_spec(spec_path, bundled_spec_path)
# Build context shared by all hooks. The metadata must correspond to the
# spec actually being generated from — never the committed snapshot when a
# different spec was selected (issue #489). A non-default spec source is any
# explicit --local-spec or a --spec-ref other than the default "main".
spec_overridden = bool(args.local_spec) or args.spec_ref != DEFAULT_SPEC_REF
metadata_path = _resolve_metadata_path(bundled_spec_input, spec_overridden)
metadata_available = metadata_path is not None
context = {
"out_dir": str(out_dir),
"spec_path": str(spec_path),
"bundled_spec_path": str(bundled_spec_path),
"metadata_path": str(metadata_path) if metadata_path else "",
"config_path": str(effective_config),
"generator": args.generator,
}
# 1. Pre-gen hooks (spec transforms)
pre_hooks = load_hooks(pre_gen_hooks_dir)
run_hooks(pre_hooks, context)
# 2. Generate
with open(effective_config, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
package_name = config.get("package_name_override", "client")
actual_out_dir = out_dir / package_name
cmd = [
"openapi-python-client",
"generate",
"--path",
str(bundled_spec_path),
"--config",
str(effective_config),
"--output-path",
str(actual_out_dir),
"--overwrite",
"--meta",
"none",
]
log(f"Running openapi-python-client with config {effective_config}...")
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
if result.stdout:
print(result.stdout)
if result.stderr:
print(result.stderr, file=sys.stderr)
# Fail the build if the generator emitted any warnings
combined_output = (result.stdout or "") + (result.stderr or "")
if "WARNING" in combined_output.upper():
raise RuntimeError(
"openapi-python-client emitted warnings (see above). "
"Fix the spec or hooks so generation is warning-free."
)
# 3. Post-gen hooks (code transforms)
post_hooks = load_hooks(post_gen_hooks_dir)
run_hooks(post_hooks, context)
# Run acceptance tests as final stage
if _should_run_acceptance_tests(
args.skip_tests, args.skip_generate, metadata_available
):
run_acceptance_tests(root, out_dir)
elif not args.skip_tests:
log(
"Skipping acceptance tests: generated without matching spec "
"metadata, so metadata-driven output (SPEC_HASH, default-tenant "
"injection) the suite asserts was intentionally omitted. Use "
"make generate to generate and validate with metadata."
)
log("Done.")
if __name__ == "__main__":
main()