3 from collections
import defaultdict
8 from pathlib
import Path
12 from typing
import Sequence
, Mapping
, TypeVar
, Any
, Union
19 JUJU_VERSION
= re
.compile('[0-9]+\.[0-9-]+[\.\-][0-9a-z]+(\.[0-9]+)?')
20 # Workaround for https://bugs.launchpad.net/juju/+bug/1683906
21 NAUGHTY_CLASSES
= ['ClientFacade', 'Client', 'FullStatus', 'ModelStatusInfo',
25 # Map basic types to Python's typing with a callable
36 # Friendly warning message to stick at the top of generated files.
38 # DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py.
39 # Changes will be overwritten/lost when the file is regenerated.
44 # Classes and helper functions that we'll write to _client.py
46 def lookup_facade(name, version):
48 Given a facade name and version, attempt to pull that facade out
49 of the correct client<version>.py file.
53 facade = getattr(CLIENTS[str(version)], name)
55 raise ImportError("No facades found for version {}".format(version))
56 except AttributeError:
58 "No facade with name '{}' in version {}".format(name, version))
67 def from_connection(cls, connection):
69 Given a connected Connection object, return an initialized and
70 connected instance of an API Interface matching the name of
73 @param connection: initialized Connection object.
76 version = connection.facades[cls.__name__[:-6]]
78 c = lookup_facade(cls.__name__, version)
96 class KindRegistry(dict):
97 def register(self
, name
, version
, obj
):
98 self
[name
] = {version
: {
102 def lookup(self
, name
, version
=None):
103 """If version is omitted, max version is used"""
104 versions
= self
.get(name
)
108 return versions
[version
]
109 return versions
[max(versions
)]
111 def getObj(self
, name
, version
=None):
112 result
= self
.lookup(name
, version
)
114 obj
= result
["object"]
119 class TypeRegistry(dict):
122 refname
= Schema
.referenceName(name
)
123 if refname
not in self
:
124 result
= TypeVar(refname
)
125 self
[refname
] = result
126 self
[result
] = refname
130 _types
= TypeRegistry()
131 _registry
= KindRegistry()
133 factories
= codegen
.Capture()
137 if isinstance(v
, str):
144 return _types
.get(ref
)
148 return getRefType(obj
["$ref"])
152 kind
= obj
.get('type')
154 raise ValueError("%s has no type" % obj
)
155 result
= SCHEMA_TO_PYTHON
.get(kind
)
157 raise ValueError("%s has type %s" % (obj
, kind
))
161 basic_types
= [str, bool, int, float]
164 def name_to_py(name
):
165 result
= name
.replace("-", "_")
166 result
= result
.lower()
167 if keyword
.iskeyword(result
) or result
in dir(builtins
):
172 def strcast(kind
, keep_builtins
=False):
173 if issubclass(kind
, typing
.GenericMeta
):
175 if str(kind
).startswith('~'):
177 if (kind
in basic_types
or
178 type(kind
) in basic_types
) and keep_builtins
is False:
184 def __init__(self
, defs
):
187 rtypes
= _registry
.getObj(_types
[defs
])
189 if not self
.do_explode(rtypes
[0][1]):
190 for name
, rtype
in rtypes
:
191 self
.append((name
, rtype
))
193 for name
, rtype
in rtypes
:
194 self
.append((name
, rtype
))
196 def do_explode(self
, kind
):
197 if kind
in basic_types
or type(kind
) is typing
.TypeVar
:
199 if not issubclass(kind
, (typing
.Sequence
,
202 self
.extend(Args(kind
))
206 def PyToSchemaMapping(self
):
212 def SchemaToPyMapping(self
):
218 def _format(self
, name
, rtype
, typed
=True):
220 return "{} : {}".format(
225 return name_to_py(name
)
227 def _get_arg_str(self
, typed
=False, joined
=", "):
231 parts
.append(self
._format
(item
[0], item
[1], typed
))
233 return joined
.join(parts
)
241 parts
.append('{}=None'.format(name_to_py(item
[0])))
242 return ', '.join(parts
)
246 return self
._get
_arg
_str
(True)
249 return self
._get
_arg
_str
(False)
252 return self
._get
_arg
_str
(True, "\n")
255 def buildTypes(schema
, capture
):
257 for kind
in sorted((k
for k
in _types
if not isinstance(k
, str)),
258 key
=lambda x
: str(x
)):
260 if name
in capture
and not name
in NAUGHTY_CLASSES
:
263 # Write Factory class for _client.py
270 def __init__(self{}{}, **unknown_fields):
275 # pprint these to get stable ordering across regens
276 pprint
.pformat(args
.PyToSchemaMapping(), width
=999),
277 pprint
.pformat(args
.SchemaToPyMapping(), width
=999),
278 ", " if args
else "",
280 textwrap
.indent(args
.get_doc(), INDENT
* 2))
282 assignments
= args
._get
_arg
_str
(False, False)
285 source
.append("{}pass".format(INDENT
* 2))
288 arg_name
= name_to_py(arg
[0])
290 arg_type_name
= strcast(arg_type
)
291 if arg_type
in basic_types
:
292 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
293 elif issubclass(arg_type
, typing
.Sequence
):
295 arg_type_name
.__parameters
__[0]
296 if len(arg_type_name
.__parameters
__)
299 if type(value_type
) is typing
.TypeVar
:
300 source
.append("{}self.{} = [{}.from_json(o) for o in {} or []]".format(
301 INDENT
* 2, arg_name
, strcast(value_type
), arg_name
))
303 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
304 elif issubclass(arg_type
, typing
.Mapping
):
306 arg_type_name
.__parameters
__[1]
307 if len(arg_type_name
.__parameters
__) > 1
310 if type(value_type
) is typing
.TypeVar
:
311 source
.append("{}self.{} = {{k: {}.from_json(v) for k, v in ({} or dict()).items()}}".format(
312 INDENT
* 2, arg_name
, strcast(value_type
), arg_name
))
314 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
315 elif type(arg_type
) is typing
.TypeVar
:
316 source
.append("{}self.{} = {}.from_json({}) if {} else None".format(
317 INDENT
* 2, arg_name
, arg_type_name
, arg_name
, arg_name
))
319 source
.append("{}self.{} = {}".format(INDENT
* 2, arg_name
, arg_name
))
321 source
= "\n".join(source
)
323 capture
[name
].write(source
)
324 capture
[name
].write("\n\n")
325 co
= compile(source
, __name__
, "exec")
334 # only return 1, so if there is more than one type
335 # we need to include a union
336 # In truth there is only 1 return
337 # Error or the expected Type
340 if defs
in basic_types
:
341 return strcast(defs
, False)
342 rtypes
= _registry
.getObj(_types
[defs
])
346 return Union
[tuple([strcast(r
[1], True) for r
in rtypes
])]
347 return strcast(rtypes
[0][1], False)
350 def return_type(defs
):
353 rtypes
= _registry
.getObj(_types
[defs
])
364 def type_anno_func(func
, defs
, is_result
=False):
368 rtypes
= _registry
.getObj(_types
[defs
])
373 elif len(rtypes
) > 1:
374 annos
[kn
] = Union
[tuple([r
[1] for r
in rtypes
])]
376 annos
[kn
] = rtypes
[0][1]
378 for name
, rtype
in rtypes
:
379 name
= name_to_py(name
)
381 func
.__annotations
__.update(annos
)
385 def ReturnMapping(cls
):
386 # Annotate the method with a return Type
387 # so the value can be cast
390 async def wrapper(*args
, **kwargs
):
392 reply
= await f(*args
, **kwargs
)
396 cls
= CLASSES
['Error']
397 if issubclass(cls
, typing
.Sequence
):
399 item_cls
= cls
.__parameters
__[0]
401 result
.append(item_cls
.from_json(item
))
404 cls = CLASSES['Error']
407 result.append(cls.from_json(item))
410 result
= cls
.from_json(reply
['response'])
417 def makeFunc(cls
, name
, params
, result
, async=True):
421 toschema
= args
.PyToSchemaMapping()
422 for arg
in args
._get
_arg
_str
(False, False):
423 assignments
.append("{}_params[\'{}\'] = {}".format(INDENT
,
426 assignments
= "\n".join(assignments
)
427 res
= retspec(result
)
430 @ReturnMapping({rettype})
431 {async}def {name}(self{argsep}{args}):
436 # map input types to rpc msg
438 msg = dict(type='{cls.name}', request='{name}', version={cls.version}, params=_params)
440 reply = {await}self.rpc(msg)
445 fsource
= source
.format(async="async " if async else "",
447 argsep
=", " if args
else "",
450 rettype
=result
.__name
__ if result
else None,
451 docstring
=textwrap
.indent(args
.get_doc(), INDENT
),
453 assignments
=assignments
,
454 await="await " if async else "")
461 def buildMethods(cls
, capture
):
462 properties
= cls
.schema
['properties']
463 for methodname
in sorted(properties
):
464 method
, source
= _buildMethod(cls
, methodname
)
465 setattr(cls
, methodname
, method
)
466 capture
["{}Facade".format(cls
.__name
__)].write(source
, depth
=1)
469 def _buildMethod(cls
, name
):
472 method
= cls
.schema
['properties'][name
]
473 if 'properties' in method
:
474 prop
= method
['properties']
475 spec
= prop
.get('Params')
477 params
= _types
.get(spec
['$ref'])
478 spec
= prop
.get('Result')
481 result
= _types
.get(spec
['$ref'])
483 result
= SCHEMA_TO_PYTHON
[spec
['type']]
484 return makeFunc(cls
, name
, params
, result
)
487 def buildFacade(schema
):
488 cls
= type(schema
.name
, (Type
,), dict(name
=schema
.name
,
489 version
=schema
.version
,
492 class {name}Facade(Type):
496 """.format(name
=schema
.name
,
497 version
=schema
.version
,
498 schema
=textwrap
.indent(pprint
.pformat(schema
), " "))
502 class TypeEncoder(json
.JSONEncoder
):
503 def default(self
, obj
):
504 if isinstance(obj
, Type
):
505 return obj
.serialize()
506 return json
.JSONEncoder
.default(self
, obj
)
510 def connect(self
, connection
):
511 self
.connection
= connection
513 async def rpc(self
, msg
):
514 result
= await self
.connection
.rpc(msg
, encoder
=TypeEncoder
)
518 def from_json(cls
, data
):
519 if isinstance(data
, cls
):
521 if isinstance(data
, str):
523 data
= json
.loads(data
)
524 except json
.JSONDecodeError
:
527 for k
, v
in (data
or {}).items():
528 d
[cls
._toPy
.get(k
, k
)] = v
537 for attr
, tgt
in self
._toSchema
.items():
538 d
[tgt
] = getattr(self
, attr
)
542 return json
.dumps(self
.serialize())
546 def __init__(self
, schema
):
547 self
.name
= schema
['Name']
548 self
.version
= schema
['Version']
549 self
.update(schema
['Schema'])
552 def referenceName(cls
, ref
):
553 if ref
.startswith("#/definitions/"):
554 ref
= ref
.rsplit("/", 1)[-1]
557 def resolveDefinition(self
, ref
):
558 return self
['definitions'][self
.referenceName(ref
)]
560 def deref(self
, prop
, name
):
561 if not isinstance(prop
, dict):
562 raise TypeError(prop
)
563 if "$ref" not in prop
:
566 target
= self
.resolveDefinition(prop
["$ref"])
569 def buildDefinitions(self
):
570 # here we are building the types out
571 # anything in definitions is a type
572 # but these may contain references themselves
573 # so we dfs to the bottom and build upwards
574 # when a types is already in the registry
575 defs
= self
.get('definitions')
578 for d
, data
in defs
.items():
579 if d
in _registry
and not d
in NAUGHTY_CLASSES
:
581 node
= self
.deref(data
, d
)
582 kind
= node
.get("type")
584 result
= self
.buildObject(node
, d
)
585 elif kind
== "array":
587 _registry
.register(d
, self
.version
, result
)
588 # XXX: This makes sure that the type gets added to the global
589 # _types dict even if no other type in the schema has a ref
593 def buildObject(self
, node
, name
=None, d
=0):
594 # we don't need to build types recursively here
595 # they are all in definitions already
596 # we only want to include the type reference
597 # which we can derive from the name
600 props
= node
.get("properties")
601 pprops
= node
.get("patternProperties")
603 # Sort these so the __init__ arg list for each Type remains
604 # consistently ordered across regens of client.py
605 for p
in sorted(props
):
608 add((p
, refType(prop
)))
612 add((p
, self
.buildArray(prop
, d
+ 1)))
613 elif kind
== "object":
614 struct
.extend(self
.buildObject(prop
, p
, d
+ 1))
616 add((p
, objType(prop
)))
618 if ".*" not in pprops
:
620 "Cannot handle actual pattern in patternProperties %s" %
624 add((name
, Mapping
[str, refType(pprop
)]))
626 ppkind
= pprop
["type"]
627 if ppkind
== "array":
628 add((name
, self
.buildArray(pprop
, d
+ 1)))
630 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
[ppkind
]]))
632 if not struct
and node
.get('additionalProperties', False):
633 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
['object']]))
637 def buildArray(self
, obj
, d
=0):
638 # return a sequence from an array in the schema
640 return Sequence
[refType(obj
)]
642 kind
= obj
.get("type")
643 if kind
and kind
== "array":
645 return self
.buildArray(items
, d
+ 1)
647 return Sequence
[objType(obj
)]
653 'ReturnMapping': ReturnMapping
655 # Copy our types into the globals of the method
656 for facade
in _registry
:
657 ns
[facade
] = _registry
.getObj(facade
)
661 def make_factory(name
):
662 if name
in factories
:
664 factories
[name
].write("class {}(TypeFactory):\n pass\n\n".format(name
))
667 def write_facades(captures
, options
):
669 Write the Facades to the appropriate _client<version>.py
672 for version
in sorted(captures
.keys()):
673 filename
= "{}/_client{}.py".format(options
.output_dir
, version
)
674 with
open(filename
, "w") as f
:
676 f
.write("from juju.client.facade import Type, ReturnMapping\n")
677 f
.write("from juju.client._definitions import *\n\n")
679 [k
for k
in captures
[version
].keys() if "Facade" in k
]):
680 print(captures
[version
][key
], file=f
)
682 # Return the last (most recent) version for use in other routines.
686 def write_definitions(captures
, options
, version
):
688 Write auxillary (non versioned) classes to
689 _definitions.py The auxillary classes currently get
690 written redudantly into each capture object, so we can look in
691 one of them -- we just use the last one from the loop above.
694 with
open("{}/_definitions.py".format(options
.output_dir
), "w") as f
:
696 f
.write("from juju.client.facade import Type, ReturnMapping\n\n")
698 [k
for k
in captures
[version
].keys() if "Facade" not in k
]):
699 print(captures
[version
][key
], file=f
)
702 def write_client(captures
, options
):
704 Write the TypeFactory classes to _client.py, along with some
705 imports and tables so that we can look up versioned Facades.
708 with
open("{}/_client.py".format(options
.output_dir
), "w") as f
:
710 f
.write("from juju.client._definitions import *\n\n")
711 clients
= ", ".join("_client{}".format(v
) for v
in captures
)
712 f
.write("from juju.client import " + clients
+ "\n\n")
713 f
.write(CLIENT_TABLE
.format(clients
=",\n ".join(
714 ['"{}": _client{}'.format(v
, v
) for v
in captures
])))
715 f
.write(LOOKUP_FACADE
)
716 f
.write(TYPE_FACTORY
)
717 for key
in sorted([k
for k
in factories
.keys() if "Facade" in k
]):
718 print(factories
[key
], file=f
)
721 def generate_facades(options
):
722 captures
= defaultdict(codegen
.Capture
)
724 for p
in sorted(glob(options
.schema
)):
726 juju_version
= 'latest'
729 juju_version
= re
.search(JUJU_VERSION
, p
).group()
730 except AttributeError:
731 print("Cannot extract a juju version from {}".format(p
))
732 print("Schemas must include a juju version in the filename")
735 new_schemas
= json
.loads(Path(p
).read_text("utf-8"))
736 schemas
[juju_version
] = [Schema(s
) for s
in new_schemas
]
738 # Build all of the auxillary (unversioned) classes
739 # TODO: get rid of some of the excess trips through loops in the
741 for juju_version
in sorted(schemas
.keys()):
742 for schema
in schemas
[juju_version
]:
743 schema
.buildDefinitions()
744 buildTypes(schema
, captures
[schema
.version
])
746 # Build the Facade classes
747 for juju_version
in sorted(schemas
.keys()):
748 for schema
in schemas
[juju_version
]:
749 cls
, source
= buildFacade(schema
)
750 cls_name
= "{}Facade".format(schema
.name
)
752 captures
[schema
.version
].clear(cls_name
)
753 # Make the factory class for _client.py
754 make_factory(cls_name
)
755 # Make the actual class
756 captures
[schema
.version
][cls_name
].write(source
)
757 # Build the methods for each Facade class.
758 buildMethods(cls
, captures
[schema
.version
])
759 # Mark this Facade class as being done for this version --
760 # helps mitigate some excessive looping.
761 CLASSES
[schema
.name
] = cls
766 parser
= argparse
.ArgumentParser()
767 parser
.add_argument("-s", "--schema", default
="juju/client/schemas*")
768 parser
.add_argument("-o", "--output_dir", default
="juju/client")
769 options
= parser
.parse_args()
775 # Generate some text blobs
776 captures
= generate_facades(options
)
778 # ... and write them out
779 last_version
= write_facades(captures
, options
)
780 write_definitions(captures
, options
, last_version
)
781 write_client(captures
, options
)
783 if __name__
== '__main__':