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
:
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
):
221 value_type
= arg_type_name
.__parameters
__[0]
222 if type(value_type
) is typing
.TypeVar
:
223 source
.append("{}self.{} = [{}.from_json(o) for o in {} or []]".format(
224 INDENT
* 2, arg_name
, strcast(value_type
), arg_name
))
226 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
227 elif issubclass(arg_type
, typing
.Mapping
):
228 value_type
= arg_type_name
.__parameters
__[1]
229 if type(value_type
) is typing
.TypeVar
:
230 source
.append("{}self.{} = {{k: {}.from_json(v) for k, v in ({} or dict()).items()}}".format(
231 INDENT
* 2, arg_name
, strcast(value_type
), arg_name
))
233 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
234 elif type(arg_type
) is typing
.TypeVar
:
235 source
.append("{}self.{} = {}.from_json({}) if {} else None".format(
236 INDENT
* 2, arg_name
, arg_type_name
, arg_name
, arg_name
))
238 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
240 source
= "\n".join(source
)
241 capture
.write(source
)
242 capture
.write("\n\n")
243 co
= compile(source
, __name__
, "exec")
252 # only return 1, so if there is more than one type
253 # we need to include a union
254 # In truth there is only 1 return
255 # Error or the expected Type
258 rtypes
= _registry
.getObj(_types
[defs
])
262 return Union
[tuple([strcast(r
[1], True) for r
in rtypes
])]
263 return strcast(rtypes
[0][1], False)
266 def return_type(defs
):
269 rtypes
= _registry
.getObj(_types
[defs
])
280 def type_anno_func(func
, defs
, is_result
=False):
284 rtypes
= _registry
.getObj(_types
[defs
])
289 elif len(rtypes
) > 1:
290 annos
[kn
] = Union
[tuple([r
[1] for r
in rtypes
])]
292 annos
[kn
] = rtypes
[0][1]
294 for name
, rtype
in rtypes
:
295 name
= name_to_py(name
)
297 func
.__annotations
__.update(annos
)
301 def ReturnMapping(cls
):
302 # Annotate the method with a return Type
303 # so the value can be cast
306 async def wrapper(*args
, **kwargs
):
308 reply
= await f(*args
, **kwargs
)
312 cls
= classes
['Error']
313 if issubclass(cls
, typing
.Sequence
):
315 item_cls
= cls
.__parameters
__[0]
317 result
.append(item_cls
.from_json(item
))
319 result
= cls
.from_json(reply
['response'])
326 def makeFunc(cls
, name
, params
, result
, async=True):
330 toschema
= args
.PyToSchemaMapping()
331 for arg
in args
._get
_arg
_str
(False, False):
332 assignments
.append("{}params[\'{}\'] = {}".format(INDENT
,
335 assignments
= "\n".join(assignments
)
336 res
= retspec(result
)
339 @ReturnMapping({rettype})
340 {async}def {name}(self{argsep}{args}):
345 # map input types to rpc msg
347 msg = dict(Type='{cls.name}', Request='{name}', Version={cls.version}, Params=params)
349 reply = {await}self.rpc(msg)
354 fsource
= source
.format(async="async " if async else "",
356 argsep
=", " if args
else "",
359 rettype
=result
.__name
__ if result
else None,
360 docstring
=textwrap
.indent(args
.get_doc(), INDENT
),
362 assignments
=assignments
,
363 await="await " if async else "")
370 def buildMethods(cls
, capture
):
371 properties
= cls
.schema
['properties']
372 for methodname
in sorted(properties
):
373 method
, source
= _buildMethod(cls
, methodname
)
374 setattr(cls
, methodname
, method
)
375 capture
.write(source
, depth
=1)
378 def _buildMethod(cls
, name
):
381 method
= cls
.schema
['properties'][name
]
382 if 'properties' in method
:
383 prop
= method
['properties']
384 spec
= prop
.get('Params')
386 params
= _types
.get(spec
['$ref'])
387 spec
= prop
.get('Result')
389 result
= _types
.get(spec
['$ref'])
390 return makeFunc(cls
, name
, params
, result
)
393 def buildFacade(schema
):
394 cls
= type(schema
.name
, (Type
,), dict(name
=schema
.name
,
395 version
=schema
.version
,
398 class {name}Facade(Type):
402 """.format(name
=schema
.name
,
403 version
=schema
.version
,
404 schema
=textwrap
.indent(pprint
.pformat(schema
), " "))
408 class TypeEncoder(json
.JSONEncoder
):
409 def default(self
, obj
):
410 if isinstance(obj
, Type
):
411 return obj
.serialize()
412 return json
.JSONEncoder
.default(self
, obj
)
416 def connect(self
, connection
):
417 self
.connection
= connection
419 async def rpc(self
, msg
):
420 result
= await self
.connection
.rpc(msg
, encoder
=TypeEncoder
)
424 def from_json(cls
, data
):
425 if isinstance(data
, str):
426 data
= json
.loads(data
)
428 for k
, v
in (data
or {}).items():
429 d
[cls
._toPy
.get(k
, k
)] = v
439 for attr
, tgt
in self
._toSchema
.items():
440 d
[tgt
] = getattr(self
, attr
)
444 return json
.dumps(self
.serialize())
448 def __init__(self
, schema
):
449 self
.name
= schema
['Name']
450 self
.version
= schema
['Version']
451 self
.update(schema
['Schema'])
454 def referenceName(cls
, ref
):
455 if ref
.startswith("#/definitions/"):
456 ref
= ref
.rsplit("/", 1)[-1]
459 def resolveDefinition(self
, ref
):
460 return self
['definitions'][self
.referenceName(ref
)]
462 def deref(self
, prop
, name
):
463 if not isinstance(prop
, dict):
464 raise TypeError(prop
)
465 if "$ref" not in prop
:
468 target
= self
.resolveDefinition(prop
["$ref"])
471 def buildDefinitions(self
):
472 # here we are building the types out
473 # anything in definitions is a type
474 # but these may contain references themselves
475 # so we dfs to the bottom and build upwards
476 # when a types is already in the registry
477 defs
= self
.get('definitions')
480 for d
, data
in defs
.items():
483 node
= self
.deref(data
, d
)
484 kind
= node
.get("type")
486 result
= self
.buildObject(node
, d
)
487 elif kind
== "array":
489 _registry
.register(d
, self
.version
, result
)
490 # XXX: This makes sure that the type gets added to the global
491 # _types dict even if no other type in the schema has a ref
495 def buildObject(self
, node
, name
=None, d
=0):
496 # we don't need to build types recursively here
497 # they are all in definitions already
498 # we only want to include the type reference
499 # which we can derive from the name
502 props
= node
.get("properties")
503 pprops
= node
.get("patternProperties")
505 # Sort these so the __init__ arg list for each Type remains
506 # consistently ordered across regens of client.py
507 for p
in sorted(props
):
510 add((p
, refType(prop
)))
514 add((p
, self
.buildArray(prop
, d
+ 1)))
515 elif kind
== "object":
516 struct
.extend(self
.buildObject(prop
, p
, d
+ 1))
518 add((p
, objType(prop
)))
520 if ".*" not in pprops
:
522 "Cannot handle actual pattern in patternProperties %s" %
526 add((name
, Mapping
[str, refType(pprop
)]))
528 ppkind
= pprop
["type"]
529 if ppkind
== "array":
530 add((name
, self
.buildArray(pprop
, d
+ 1)))
532 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
[ppkind
]]))
534 if not struct
and node
.get('additionalProperties', False):
535 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
['object']]))
539 def buildArray(self
, obj
, d
=0):
540 # return a sequence from an array in the schema
542 return Sequence
[refType(obj
)]
544 kind
= obj
.get("type")
545 if kind
and kind
== "array":
547 return self
.buildArray(items
, d
+ 1)
549 return Sequence
[objType(obj
)]
555 'ReturnMapping': ReturnMapping
557 # Copy our types into the globals of the method
558 for facade
in _registry
:
559 ns
[facade
] = _registry
.getObj(facade
)
564 def generate_facacdes(options
):
566 schemas
= json
.loads(Path(options
.schema
).read_text("utf-8"))
567 capture
= codegen
.CodeWriter()
568 capture
.write(textwrap
.dedent("""\
569 # DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py.
570 # Changes will be overwritten/lost when the file is regenerated.
572 from juju.client.facade import Type, ReturnMapping
575 schemas
= [Schema(s
) for s
in schemas
]
577 for schema
in schemas
:
578 schema
.buildDefinitions()
579 buildTypes(schema
, capture
)
581 for schema
in schemas
:
582 # TODO generate class now with a metaclass that takes the schema
583 # the generated class has the right name and it in turn uses
584 # the metaclass to populate cls
585 cls
, source
= buildFacade(schema
)
586 capture
.write(source
)
587 buildMethods(cls
, capture
)
588 classes
[schema
.name
] = cls
593 parser
= argparse
.ArgumentParser()
594 parser
.add_argument("-s", "--schema", default
="schemas.json")
595 parser
.add_argument("-o", "--output", default
="client.py")
596 options
= parser
.parse_args()
601 capture
= generate_facacdes(options
)
602 with
open(options
.output
, "w") as fp
:
603 print(capture
, file=fp
)
607 if __name__
== '__main__':