Skip to content

Commit d463578

Browse files
use request converter to generate python examples
1 parent 47dcd2b commit d463578

File tree

1 file changed

+28
-59
lines changed

1 file changed

+28
-59
lines changed

utils/generate-examples.py

Lines changed: 28 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,17 @@
1919

2020
import collections
2121
import json
22-
import os
23-
import tempfile
2422
from pathlib import Path
23+
import subprocess
2524

26-
import black
2725
from click.testing import CliRunner
2826
from jinja2 import Environment, FileSystemLoader
2927

3028
code_root = Path(__file__).absolute().parent.parent
3129
asciidocs_dir = code_root / "docs/examples"
3230
flight_recorder_dir = code_root.parent / "clients-flight-recorder"
3331
report_path = flight_recorder_dir / "recordings/docs/parsed-alternative-report.json"
32+
request_converter_path = flight_recorder_dir / "scripts/parsed-alternative-report-recorder/node_modules/.bin/es-request-converter"
3433
substitutions = {"type": "doc_type", "from": "from_"}
3534

3635
jinja_env = Environment(
@@ -195,14 +194,6 @@
195194
ParsedSource = collections.namedtuple("ParsedSource", ["api", "params", "body"])
196195

197196

198-
def blacken(filename):
199-
runner = CliRunner()
200-
result = runner.invoke(
201-
black.main, [str(filename), "--line-length=75", "--target-version=py37"]
202-
)
203-
assert result.exit_code == 0, result.output
204-
205-
206197
def main():
207198
for filepath in asciidocs_dir.iterdir():
208199
if filepath.name.endswith(".asciidoc"):
@@ -213,62 +204,40 @@ def main():
213204
f"clients-flight-recorder repository not checked out at {flight_recorder_dir}"
214205
)
215206

207+
if not request_converter_path.exists():
208+
raise RuntimeError(
209+
f"request-converter not installed in clients-flight-recorder"
210+
)
211+
216212
with report_path.open() as f:
217213
report = json.loads(f.read())
218214

219-
t = jinja_env.get_template("example")
220-
215+
count = 0
216+
errors = 0
221217
for exm in report:
222218
if exm["lang"] != "console":
223219
continue
224-
if exm["source_location"]["file"] not in files_to_generate:
225-
continue
226-
227-
parsed_sources = []
228-
for src in exm["parsed_source"]:
229-
params = (src.get("params") or {}).copy()
230-
params.update(src.get("query") or {})
231-
params = {
232-
k: (list(v.split(",")) if isinstance(v, str) and "," in v else v)
233-
for k, v in params.items()
234-
}
235220

236-
parsed_sources.append(
237-
ParsedSource(
238-
api=src["api"],
239-
params={
240-
substitutions.get(k, k): repr(v) for k, v in params.items()
241-
},
242-
body=src.get("body", None) or None,
221+
proc = subprocess.run(
222+
[request_converter_path, '-f', 'python', '--print-response'],
223+
input=exm['source'].encode(), capture_output=True)
224+
if proc.returncode == 0:
225+
data = proc.stdout.decode()
226+
227+
with (asciidocs_dir / f"{exm['digest']}.asciidoc").open(mode="w") as f:
228+
f.truncate()
229+
f.write(
230+
f"""// {exm['source_location']['file']}:{exm['source_location']['line']}
231+
232+
[source, python]
233+
----
234+
{data}
235+
----"""
243236
)
244-
)
245-
246-
with tempfile.NamedTemporaryFile("w+", delete=False) as tmp_file:
247-
tmp_file.write(t.render(parsed_sources=parsed_sources))
248-
249-
try:
250-
blacken(tmp_file.name)
251-
except AssertionError:
252-
loc = exm["source_location"]
253-
print(f"Failed to format {loc['file']}:{loc['line']}, skipping.")
254-
continue
255-
256-
with open(tmp_file.name) as f:
257-
data = f.read()
258-
data = data.rstrip().replace(",)", ")")
259-
260-
os.unlink(tmp_file.name)
261-
262-
with (asciidocs_dir / f"{exm['digest']}.asciidoc").open(mode="w") as f:
263-
f.truncate()
264-
f.write(
265-
f"""// {exm['source_location']['file']}:{exm['source_location']['line']}
266-
267-
[source, python]
268-
----
269-
{data}
270-
----"""
271-
)
237+
else:
238+
errors += 1
239+
count += 1
240+
print(f'\r{count}/{len(report)} generated ({errors} errors)', end='')
272241

273242

274243
if __name__ == "__main__":

0 commit comments

Comments
 (0)