Commit 6d22c304 authored by Janis Streib's avatar Janis Streib

ADD: first python generator

parent d3860fd6
......@@ -3,12 +3,11 @@ import json
from json import JSONEncoder
import re
import os
import logging
from .bootstrap_model import *
from .loader import Loader
keyword_replacements = {'class': 'cls'}
loader = Loader()
......@@ -24,9 +23,113 @@ def cli():
loader.load()
@cli.command()
@click.option('--strict/--skip-errors', default=True)
def python(strict):
keyword_replacements = {'class': 'cls'}
def replace_keywords(k):
for t, s in keyword_replacements.items():
k = k.replace(t, s)
return k
def quote_def(p, scope):
if translate_json_data_type(p.data_type['json_name']) == 'str':
return f"'{scope.data_default}'"
return scope.data_default
def translate_json_data_type(t):
if t == 'boolean':
return 'bool'
if t == 'number':
return 'int'
if t == 'string':
return 'str'
if t == 'array':
return 'list'
if t == 'object':
return 'dict'
if t == 'json':
return 'str'
raise ValueError(t)
print("""### AUTOGENERATED
import requests
from dataclasses import dataclass
import click
class APIObject(object):
\tpass
""")
class_bodies = {k: f"""
@click.group()
def {v.system}_{v.name}():
\tpass
@dataclass()
class {v.system}_{v.name}(APIObject):
""" for k, v in loader.api_objects.items()}
# generate fields
for k, v in loader.api_objects.items():
for p in v.attributes.values():
class_bodies[k] += f"""\t{replace_keywords(p.name)}: {translate_json_data_type(p.data_type['json_name'])}\n"""
# generate __post_init__
for k, v in loader.api_objects.items():
class_bodies[k] += f"""\n\tdef __post_init__(self):\n"""
for p in v.attributes.values():
class_bodies[
k] += f"""\t\tif {f"self.{replace_keywords(p.name)} is not None and" if p.is_nullable else ""} not isinstance(self.{replace_keywords(p.name)}, {translate_json_data_type(p.data_type['json_name'])}):
\t\t\traise ValueError(f"'{replace_keywords(p.name)}' of incorrect type. Expected {translate_json_data_type(p.data_type['json_name'])}, got {{type(self.{replace_keywords(p.name)})}}")\n"""
# generate functions
for f in loader.api_functions:
if f.name == 'document':
continue # FIXME
if f"{f.system}.{f.object_type}" not in class_bodies:
if not f.is_returning:
continue
if strict:
raise ValueError(f"'{f.system}.{f.object_type}' not found in object index!")
logging.warning(f"'{f.system}.{f.object_type}' not found in object index!")
continue
params = sorted([
f"{replace_keywords(p.name)}_new:{translate_json_data_type(p.data_type['json_name'])}{f'={quote_def(p, p.new)}' if p.new.data_default is not None else ''}"
for p in f.parameters.values() if p.new is not None],
key=lambda item: 'Z' if '=' in item else 'A')
old_params = sorted([
f"{replace_keywords(p.name)}_old:{translate_json_data_type(p.data_type['json_name'])}{f'={quote_def(p, p.old)}' if p.old.data_default is not None else ''}"
for p in f.parameters.values() if p.old is not None],
key=lambda item: 'Z' if '=' in item else 'A')
params.extend(old_params)
params = sorted(params,key=lambda item: 'Z' if '=' in item else 'A')
dict_new_params_identity = [f"'{replace_keywords(p.name)}':{replace_keywords(p.name)}_new" for p in f.parameters.values() if p.new is not None]
dict_old_params_identity = [f"'{replace_keywords(p.name)}':{replace_keywords(p.name)}_old" for p in f.parameters.values() if p.old is not None]
new_params_identity = [f"{replace_keywords(p.name)}_new={replace_keywords(p.name)}_new" for p in f.parameters.values() if p.new is not None]
old_params_identity = [f"{replace_keywords(p.name)}_old={replace_keywords(p.name)}_old" for p in f.parameters.values() if p.old is not None]
class_bodies[f'{f.system}.{f.object_type}'] += f"""
\t@staticmethod
\tdef {f.name}_ta({','.join(params)}) -> dict:
\t\treturn {{'name': '{f.system}.{f.object_type}.{f.name}', 'new': {{{','.join(dict_new_params_identity)}}}, 'old': {{{','.join(dict_old_params_identity)}}}}}
\ŧ# TODO: Consider is_returning
\t@classmethod
\tdef {f.name}(tgtc, session:requests.Session, {','.join(params)}) -> '{f.system}_{f.name}':
\t\treturn [tgtc(**s) for s in session.post(json=cls.{f.name}_ta({','.join(new_params_identity)}{',' if len(new_params_identity) > 0 else ''}{','.join(old_params_identity)})).json()[0]]
"""
# dump
for b in class_bodies.values():
print(b)
@cli.command(name='es-webpack')
@click.option('--output_dir', default='src/api-services.gen/')
def es_webpack(output_dir):
keyword_replacements = {'class': 'cls'}
files = {}
for f in loader.api_functions:
if f.name == 'document':
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment