c4834ee6509fabd4a7c37609001155e836a1a66a
6 from pathlib
import Path
9 from typing
import Sequence
, Mapping
, TypeVar
, Any
, Union
16 # Map basic types to Python's typing with a callable
27 class KindRegistry(dict):
28 def register(self
, name
, version
, obj
):
29 self
[name
] = {version
: {
33 def lookup(self
, name
, version
=None):
34 """If version is omitted, max version is used"""
35 versions
= self
.get(name
)
39 return versions
[version
]
40 return versions
[max(versions
)]
42 def getObj(self
, name
, version
=None):
43 result
= self
.lookup(name
, version
)
45 obj
= result
["object"]
50 class TypeRegistry(dict):
53 refname
= Schema
.referenceName(name
)
54 if refname
not in self
:
55 result
= TypeVar(refname
)
56 self
[refname
] = result
57 self
[result
] = refname
61 _types
= TypeRegistry()
62 _registry
= KindRegistry()
67 if isinstance(v
, str):
74 return _types
.get(ref
)
78 return getRefType(obj
["$ref"])
82 kind
= obj
.get('type')
84 raise ValueError("%s has no type" % obj
)
85 result
= SCHEMA_TO_PYTHON
.get(kind
)
87 raise ValueError("%s has type %s" % (obj
, kind
))
91 basic_types
= [str, bool, int, float]
95 result
= name
.replace("-", "_")
96 result
= result
.lower()
97 if keyword
.iskeyword(result
) or result
in dir(builtins
):
102 def strcast(kind
, keep_builtins
=False):
103 if issubclass(kind
, typing
.GenericMeta
):
105 if str(kind
).startswith('~'):
107 if (kind
in basic_types
or
108 type(kind
) in basic_types
) and keep_builtins
is False:
114 def __init__(self
, defs
):
117 rtypes
= _registry
.getObj(_types
[defs
])
119 if not self
.do_explode(rtypes
[0][1]):
120 for name
, rtype
in rtypes
:
121 self
.append((name
, rtype
))
123 for name
, rtype
in rtypes
:
124 self
.append((name
, rtype
))
126 def do_explode(self
, kind
):
127 if kind
in basic_types
or type(kind
) is typing
.TypeVar
:
129 if not issubclass(kind
, (typing
.Sequence
,
132 self
.extend(Args(kind
))
136 def PyToSchemaMapping(self
):
142 def SchemaToPyMapping(self
):
148 def _format(self
, name
, rtype
, typed
=True):
150 return "{} : {}".format(
155 return name_to_py(name
)
157 def _get_arg_str(self
, typed
=False, joined
=", "):
161 parts
.append(self
._format
(item
[0], item
[1], typed
))
163 return joined
.join(parts
)
171 parts
.append('{}=None'.format(name_to_py(item
[0])))
172 return ', '.join(parts
)
176 return self
._get
_arg
_str
(True)
179 return self
._get
_arg
_str
(False)
182 return self
._get
_arg
_str
(True, "\n")
185 def buildTypes(schema
, capture
):
188 for kind
in sorted((k
for k
in _types
if not isinstance(k
, str)),
189 key
=lambda x
: str(x
)):
198 def __init__(self{}{}):
203 args
.PyToSchemaMapping(),
204 args
.SchemaToPyMapping(),
205 ", " if args
else "",
207 textwrap
.indent(args
.get_doc(), INDENT
* 2))
209 assignments
= args
._get
_arg
_str
(False, False)
212 source
.append("{}pass".format(INDENT
* 2))
215 arg_name
= name_to_py(arg
[0])
217 arg_type_name
= strcast(arg_type
)
218 if arg_type
in basic_types
:
219 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
220 elif issubclass(arg_type
, typing
.Sequence
):
222 arg_type_name
.__parameters
__[0]
223 if len(arg_type_name
.__parameters
__)
226 if type(value_type
) is typing
.TypeVar
:
227 source
.append("{}self.{} = [{}.from_json(o) for o in {} or []]".format(
228 INDENT
* 2, arg_name
, strcast(value_type
), arg_name
))
230 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
231 elif issubclass(arg_type
, typing
.Mapping
):
233 arg_type_name
.__parameters
__[1]
234 if len(arg_type_name
.__parameters
__) > 1
237 if type(value_type
) is typing
.TypeVar
:
238 source
.append("{}self.{} = {{k: {}.from_json(v) for k, v in ({} or dict()).items()}}".format(
239 INDENT
* 2, arg_name
, strcast(value_type
), arg_name
))
241 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
242 elif type(arg_type
) is typing
.TypeVar
:
243 source
.append("{}self.{} = {}.from_json({}) if {} else None".format(
244 INDENT
* 2, arg_name
, arg_type_name
, arg_name
, arg_name
))
246 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
248 source
= "\n".join(source
)
249 capture
.write(source
)
250 capture
.write("\n\n")
251 co
= compile(source
, __name__
, "exec")
260 # only return 1, so if there is more than one type
261 # we need to include a union
262 # In truth there is only 1 return
263 # Error or the expected Type
266 rtypes
= _registry
.getObj(_types
[defs
])
270 return Union
[tuple([strcast(r
[1], True) for r
in rtypes
])]
271 return strcast(rtypes
[0][1], False)
274 def return_type(defs
):
277 rtypes
= _registry
.getObj(_types
[defs
])
288 def type_anno_func(func
, defs
, is_result
=False):
292 rtypes
= _registry
.getObj(_types
[defs
])
297 elif len(rtypes
) > 1:
298 annos
[kn
] = Union
[tuple([r
[1] for r
in rtypes
])]
300 annos
[kn
] = rtypes
[0][1]
302 for name
, rtype
in rtypes
:
303 name
= name_to_py(name
)
305 func
.__annotations
__.update(annos
)
309 def ReturnMapping(cls
):
310 # Annotate the method with a return Type
311 # so the value can be cast
314 async def wrapper(*args
, **kwargs
):
316 reply
= await f(*args
, **kwargs
)
320 cls
= classes
['Error']
321 if issubclass(cls
, typing
.Sequence
):
323 item_cls
= cls
.__parameters
__[0]
325 result
.append(item_cls
.from_json(item
))
328 cls = classes['Error']
331 result.append(cls.from_json(item))
334 result
= cls
.from_json(reply
['response'])
341 def makeFunc(cls
, name
, params
, result
, async=True):
345 toschema
= args
.PyToSchemaMapping()
346 for arg
in args
._get
_arg
_str
(False, False):
347 assignments
.append("{}_params[\'{}\'] = {}".format(INDENT
,
350 assignments
= "\n".join(assignments
)
351 res
= retspec(result
)
354 @ReturnMapping({rettype})
355 {async}def {name}(self{argsep}{args}):
360 # map input types to rpc msg
362 msg = dict(type='{cls.name}', request='{name}', version={cls.version}, params=_params)
364 reply = {await}self.rpc(msg)
369 fsource
= source
.format(async="async " if async else "",
371 argsep
=", " if args
else "",
374 rettype
=result
.__name
__ if result
else None,
375 docstring
=textwrap
.indent(args
.get_doc(), INDENT
),
377 assignments
=assignments
,
378 await="await " if async else "")
385 def buildMethods(cls
, capture
):
386 properties
= cls
.schema
['properties']
387 for methodname
in sorted(properties
):
388 method
, source
= _buildMethod(cls
, methodname
)
389 setattr(cls
, methodname
, method
)
390 capture
.write(source
, depth
=1)
393 def _buildMethod(cls
, name
):
396 method
= cls
.schema
['properties'][name
]
397 if 'properties' in method
:
398 prop
= method
['properties']
399 spec
= prop
.get('Params')
401 params
= _types
.get(spec
['$ref'])
402 spec
= prop
.get('Result')
404 result
= _types
.get(spec
['$ref'])
405 return makeFunc(cls
, name
, params
, result
)
408 def buildFacade(schema
):
409 cls
= type(schema
.name
, (Type
,), dict(name
=schema
.name
,
410 version
=schema
.version
,
413 class {name}Facade(Type):
417 """.format(name
=schema
.name
,
418 version
=schema
.version
,
419 schema
=textwrap
.indent(pprint
.pformat(schema
), " "))
423 class TypeEncoder(json
.JSONEncoder
):
424 def default(self
, obj
):
425 if isinstance(obj
, Type
):
426 return obj
.serialize()
427 return json
.JSONEncoder
.default(self
, obj
)
431 def connect(self
, connection
):
432 self
.connection
= connection
434 async def rpc(self
, msg
):
435 result
= await self
.connection
.rpc(msg
, encoder
=TypeEncoder
)
439 def from_json(cls
, data
):
440 if isinstance(data
, str):
441 data
= json
.loads(data
)
443 for k
, v
in (data
or {}).items():
444 d
[cls
._toPy
.get(k
, k
)] = v
453 for attr
, tgt
in self
._toSchema
.items():
454 d
[tgt
] = getattr(self
, attr
)
458 return json
.dumps(self
.serialize())
462 def __init__(self
, schema
):
463 self
.name
= schema
['Name']
464 self
.version
= schema
['Version']
465 self
.update(schema
['Schema'])
468 def referenceName(cls
, ref
):
469 if ref
.startswith("#/definitions/"):
470 ref
= ref
.rsplit("/", 1)[-1]
473 def resolveDefinition(self
, ref
):
474 return self
['definitions'][self
.referenceName(ref
)]
476 def deref(self
, prop
, name
):
477 if not isinstance(prop
, dict):
478 raise TypeError(prop
)
479 if "$ref" not in prop
:
482 target
= self
.resolveDefinition(prop
["$ref"])
485 def buildDefinitions(self
):
486 # here we are building the types out
487 # anything in definitions is a type
488 # but these may contain references themselves
489 # so we dfs to the bottom and build upwards
490 # when a types is already in the registry
491 defs
= self
.get('definitions')
494 for d
, data
in defs
.items():
497 node
= self
.deref(data
, d
)
498 kind
= node
.get("type")
500 result
= self
.buildObject(node
, d
)
501 elif kind
== "array":
503 _registry
.register(d
, self
.version
, result
)
504 # XXX: This makes sure that the type gets added to the global
505 # _types dict even if no other type in the schema has a ref
509 def buildObject(self
, node
, name
=None, d
=0):
510 # we don't need to build types recursively here
511 # they are all in definitions already
512 # we only want to include the type reference
513 # which we can derive from the name
516 props
= node
.get("properties")
517 pprops
= node
.get("patternProperties")
519 # Sort these so the __init__ arg list for each Type remains
520 # consistently ordered across regens of client.py
521 for p
in sorted(props
):
524 add((p
, refType(prop
)))
528 add((p
, self
.buildArray(prop
, d
+ 1)))
529 elif kind
== "object":
530 struct
.extend(self
.buildObject(prop
, p
, d
+ 1))
532 add((p
, objType(prop
)))
534 if ".*" not in pprops
:
536 "Cannot handle actual pattern in patternProperties %s" %
540 add((name
, Mapping
[str, refType(pprop
)]))
542 ppkind
= pprop
["type"]
543 if ppkind
== "array":
544 add((name
, self
.buildArray(pprop
, d
+ 1)))
546 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
[ppkind
]]))
548 if not struct
and node
.get('additionalProperties', False):
549 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
['object']]))
553 def buildArray(self
, obj
, d
=0):
554 # return a sequence from an array in the schema
556 return Sequence
[refType(obj
)]
558 kind
= obj
.get("type")
559 if kind
and kind
== "array":
561 return self
.buildArray(items
, d
+ 1)
563 return Sequence
[objType(obj
)]
569 'ReturnMapping': ReturnMapping
571 # Copy our types into the globals of the method
572 for facade
in _registry
:
573 ns
[facade
] = _registry
.getObj(facade
)
578 def generate_facacdes(options
):
580 schemas
= json
.loads(Path(options
.schema
).read_text("utf-8"))
581 capture
= codegen
.CodeWriter()
582 capture
.write(textwrap
.dedent("""\
583 # DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py.
584 # Changes will be overwritten/lost when the file is regenerated.
586 from juju.client.facade import Type, ReturnMapping
589 schemas
= [Schema(s
) for s
in schemas
]
591 for schema
in schemas
:
592 schema
.buildDefinitions()
593 buildTypes(schema
, capture
)
595 for schema
in schemas
:
596 # TODO generate class now with a metaclass that takes the schema
597 # the generated class has the right name and it in turn uses
598 # the metaclass to populate cls
599 cls
, source
= buildFacade(schema
)
600 capture
.write(source
)
601 buildMethods(cls
, capture
)
602 classes
[schema
.name
] = cls
607 parser
= argparse
.ArgumentParser()
608 parser
.add_argument("-s", "--schema", default
="schemas.json")
609 parser
.add_argument("-o", "--output", default
="client.py")
610 options
= parser
.parse_args()
615 capture
= generate_facacdes(options
)
616 with
open(options
.output
, "w") as fp
:
617 print(capture
, file=fp
)
621 if __name__
== '__main__':