10 from collections
import defaultdict
12 from pathlib
import Path
13 from typing
import Any
, Mapping
, Sequence
, TypeVar
, 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
131 _types
= TypeRegistry()
132 _registry
= KindRegistry()
134 factories
= codegen
.Capture()
138 if isinstance(v
, str):
145 return _types
.get(ref
)
149 return getRefType(obj
["$ref"])
153 kind
= obj
.get('type')
155 raise ValueError("%s has no type" % obj
)
156 result
= SCHEMA_TO_PYTHON
.get(kind
)
158 raise ValueError("%s has type %s" % (obj
, kind
))
162 basic_types
= [str, bool, int, float]
165 def name_to_py(name
):
166 result
= name
.replace("-", "_")
167 result
= result
.lower()
168 if keyword
.iskeyword(result
) or result
in dir(builtins
):
173 def strcast(kind
, keep_builtins
=False):
174 if (kind
in basic_types
or
175 type(kind
) in basic_types
) and keep_builtins
is False:
177 if str(kind
).startswith('~'):
179 if issubclass(kind
, typing
.GenericMeta
):
185 def __init__(self
, defs
):
188 rtypes
= _registry
.getObj(_types
[defs
])
190 if not self
.do_explode(rtypes
[0][1]):
191 for name
, rtype
in rtypes
:
192 self
.append((name
, rtype
))
194 for name
, rtype
in rtypes
:
195 self
.append((name
, rtype
))
197 def do_explode(self
, kind
):
198 if kind
in basic_types
or type(kind
) is typing
.TypeVar
:
200 if not issubclass(kind
, (typing
.Sequence
,
203 self
.extend(Args(kind
))
207 def PyToSchemaMapping(self
):
213 def SchemaToPyMapping(self
):
219 def _format(self
, name
, rtype
, typed
=True):
221 return "{} : {}".format(
226 return name_to_py(name
)
228 def _get_arg_str(self
, typed
=False, joined
=", "):
232 parts
.append(self
._format
(item
[0], item
[1], typed
))
234 return joined
.join(parts
)
242 parts
.append('{}=None'.format(name_to_py(item
[0])))
243 return ', '.join(parts
)
247 return self
._get
_arg
_str
(True)
250 return self
._get
_arg
_str
(False)
253 return self
._get
_arg
_str
(True, "\n")
256 def buildTypes(schema
, capture
):
258 for kind
in sorted((k
for k
in _types
if not isinstance(k
, str)),
259 key
=lambda x
: str(x
)):
261 if name
in capture
and name
not in NAUGHTY_CLASSES
:
264 # Write Factory class for _client.py
271 def __init__(self{}{}, **unknown_fields):
276 # pprint these to get stable ordering across regens
277 pprint
.pformat(args
.PyToSchemaMapping(), width
=999),
278 pprint
.pformat(args
.SchemaToPyMapping(), width
=999),
279 ", " if args
else "",
281 textwrap
.indent(args
.get_doc(), INDENT
* 2))]
284 source
.append("{}pass".format(INDENT
* 2))
287 arg_name
= name_to_py(arg
[0])
289 arg_type_name
= strcast(arg_type
)
290 if arg_type
in basic_types
:
291 source
.append("{}self.{} = {}".format(INDENT
* 2,
294 elif type(arg_type
) is typing
.TypeVar
:
295 source
.append("{}self.{} = {}.from_json({}) "
296 "if {} else None".format(INDENT
* 2,
301 elif issubclass(arg_type
, typing
.Sequence
):
303 arg_type_name
.__parameters
__[0]
304 if len(arg_type_name
.__parameters
__)
307 if type(value_type
) is typing
.TypeVar
:
309 "{}self.{} = [{}.from_json(o) "
310 "for o in {} or []]".format(INDENT
* 2,
315 source
.append("{}self.{} = {}".format(INDENT
* 2,
318 elif issubclass(arg_type
, typing
.Mapping
):
320 arg_type_name
.__parameters
__[1]
321 if len(arg_type_name
.__parameters
__) > 1
324 if type(value_type
) is typing
.TypeVar
:
326 "{}self.{} = {{k: {}.from_json(v) "
327 "for k, v in ({} or dict()).items()}}".format(
333 source
.append("{}self.{} = {}".format(INDENT
* 2,
337 source
.append("{}self.{} = {}".format(INDENT
* 2,
341 source
= "\n".join(source
)
343 capture
[name
].write(source
)
344 capture
[name
].write("\n\n")
345 co
= compile(source
, __name__
, "exec")
354 # only return 1, so if there is more than one type
355 # we need to include a union
356 # In truth there is only 1 return
357 # Error or the expected Type
360 if defs
in basic_types
:
361 return strcast(defs
, False)
362 rtypes
= _registry
.getObj(_types
[defs
])
366 return Union
[tuple([strcast(r
[1], True) for r
in rtypes
])]
367 return strcast(rtypes
[0][1], False)
370 def return_type(defs
):
373 rtypes
= _registry
.getObj(_types
[defs
])
384 def type_anno_func(func
, defs
, is_result
=False):
388 rtypes
= _registry
.getObj(_types
[defs
])
393 elif len(rtypes
) > 1:
394 annos
[kn
] = Union
[tuple([r
[1] for r
in rtypes
])]
396 annos
[kn
] = rtypes
[0][1]
398 for name
, rtype
in rtypes
:
399 name
= name_to_py(name
)
401 func
.__annotations
__.update(annos
)
405 def ReturnMapping(cls
):
406 # Annotate the method with a return Type
407 # so the value can be cast
410 async def wrapper(*args
, **kwargs
):
412 reply
= await f(*args
, **kwargs
)
416 cls
= CLASSES
['Error']
417 if issubclass(cls
, typing
.Sequence
):
419 item_cls
= cls
.__parameters
__[0]
421 result
.append(item_cls
.from_json(item
))
424 cls = CLASSES['Error']
427 result.append(cls.from_json(item))
430 result
= cls
.from_json(reply
['response'])
437 def makeFunc(cls
, name
, params
, result
, _async
=True):
441 toschema
= args
.PyToSchemaMapping()
442 for arg
in args
._get
_arg
_str
(False, False):
443 assignments
.append("{}_params[\'{}\'] = {}".format(INDENT
,
446 assignments
= "\n".join(assignments
)
447 res
= retspec(result
)
450 @ReturnMapping({rettype})
451 {_async}def {name}(self{argsep}{args}):
456 # map input types to rpc msg
458 msg = dict(type='{cls.name}',
460 version={cls.version},
463 reply = {_await}self.rpc(msg)
468 fsource
= source
.format(_async
="async " if _async
else "",
470 argsep
=", " if args
else "",
473 rettype
=result
.__name
__ if result
else None,
474 docstring
=textwrap
.indent(args
.get_doc(), INDENT
),
476 assignments
=assignments
,
477 _await
="await " if _async
else "")
484 def buildMethods(cls
, capture
):
485 properties
= cls
.schema
['properties']
486 for methodname
in sorted(properties
):
487 method
, source
= _buildMethod(cls
, methodname
)
488 setattr(cls
, methodname
, method
)
489 capture
["{}Facade".format(cls
.__name
__)].write(source
, depth
=1)
492 def _buildMethod(cls
, name
):
495 method
= cls
.schema
['properties'][name
]
496 if 'properties' in method
:
497 prop
= method
['properties']
498 spec
= prop
.get('Params')
500 params
= _types
.get(spec
['$ref'])
501 spec
= prop
.get('Result')
504 result
= _types
.get(spec
['$ref'])
506 result
= SCHEMA_TO_PYTHON
[spec
['type']]
507 return makeFunc(cls
, name
, params
, result
)
510 def buildFacade(schema
):
511 cls
= type(schema
.name
, (Type
,), dict(name
=schema
.name
,
512 version
=schema
.version
,
515 class {name}Facade(Type):
519 """.format(name
=schema
.name
,
520 version
=schema
.version
,
521 schema
=textwrap
.indent(pprint
.pformat(schema
), " "))
525 class TypeEncoder(json
.JSONEncoder
):
526 def default(self
, obj
):
527 if isinstance(obj
, Type
):
528 return obj
.serialize()
529 return json
.JSONEncoder
.default(self
, obj
)
533 def connect(self
, connection
):
534 self
.connection
= connection
536 async def rpc(self
, msg
):
537 result
= await self
.connection
.rpc(msg
, encoder
=TypeEncoder
)
541 def from_json(cls
, data
):
542 if isinstance(data
, cls
):
544 if isinstance(data
, str):
546 data
= json
.loads(data
)
547 except json
.JSONDecodeError
:
550 for k
, v
in (data
or {}).items():
551 d
[cls
._toPy
.get(k
, k
)] = v
560 for attr
, tgt
in self
._toSchema
.items():
561 d
[tgt
] = getattr(self
, attr
)
565 return json
.dumps(self
.serialize(), cls
=TypeEncoder
, sort_keys
=True)
569 def __init__(self
, schema
):
570 self
.name
= schema
['Name']
571 self
.version
= schema
['Version']
572 self
.update(schema
['Schema'])
575 def referenceName(cls
, ref
):
576 if ref
.startswith("#/definitions/"):
577 ref
= ref
.rsplit("/", 1)[-1]
580 def resolveDefinition(self
, ref
):
581 return self
['definitions'][self
.referenceName(ref
)]
583 def deref(self
, prop
, name
):
584 if not isinstance(prop
, dict):
585 raise TypeError(prop
)
586 if "$ref" not in prop
:
589 target
= self
.resolveDefinition(prop
["$ref"])
592 def buildDefinitions(self
):
593 # here we are building the types out
594 # anything in definitions is a type
595 # but these may contain references themselves
596 # so we dfs to the bottom and build upwards
597 # when a types is already in the registry
598 defs
= self
.get('definitions')
601 for d
, data
in defs
.items():
602 if d
in _registry
and d
not in NAUGHTY_CLASSES
:
604 node
= self
.deref(data
, d
)
605 kind
= node
.get("type")
607 result
= self
.buildObject(node
, d
)
608 elif kind
== "array":
610 _registry
.register(d
, self
.version
, result
)
611 # XXX: This makes sure that the type gets added to the global
612 # _types dict even if no other type in the schema has a ref
616 def buildObject(self
, node
, name
=None, d
=0):
617 # we don't need to build types recursively here
618 # they are all in definitions already
619 # we only want to include the type reference
620 # which we can derive from the name
623 props
= node
.get("properties")
624 pprops
= node
.get("patternProperties")
626 # Sort these so the __init__ arg list for each Type remains
627 # consistently ordered across regens of client.py
628 for p
in sorted(props
):
631 add((p
, refType(prop
)))
635 add((p
, self
.buildArray(prop
, d
+ 1)))
636 elif kind
== "object":
637 struct
.extend(self
.buildObject(prop
, p
, d
+ 1))
639 add((p
, objType(prop
)))
641 if ".*" not in pprops
:
643 "Cannot handle actual pattern in patternProperties %s" %
647 add((name
, Mapping
[str, refType(pprop
)]))
649 ppkind
= pprop
["type"]
650 if ppkind
== "array":
651 add((name
, self
.buildArray(pprop
, d
+ 1)))
653 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
[ppkind
]]))
655 if not struct
and node
.get('additionalProperties', False):
656 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
['object']]))
660 def buildArray(self
, obj
, d
=0):
661 # return a sequence from an array in the schema
663 return Sequence
[refType(obj
)]
665 kind
= obj
.get("type")
666 if kind
and kind
== "array":
668 return self
.buildArray(items
, d
+ 1)
670 return Sequence
[objType(obj
)]
676 'ReturnMapping': ReturnMapping
678 # Copy our types into the globals of the method
679 for facade
in _registry
:
680 ns
[facade
] = _registry
.getObj(facade
)
684 def make_factory(name
):
685 if name
in factories
:
687 factories
[name
].write("class {}(TypeFactory):\n pass\n\n".format(name
))
690 def write_facades(captures
, options
):
692 Write the Facades to the appropriate _client<version>.py
695 for version
in sorted(captures
.keys()):
696 filename
= "{}/_client{}.py".format(options
.output_dir
, version
)
697 with
open(filename
, "w") as f
:
699 f
.write("from juju.client.facade import Type, ReturnMapping\n")
700 f
.write("from juju.client._definitions import *\n\n")
702 [k
for k
in captures
[version
].keys() if "Facade" in k
]):
703 print(captures
[version
][key
], file=f
)
705 # Return the last (most recent) version for use in other routines.
709 def write_definitions(captures
, options
, version
):
711 Write auxillary (non versioned) classes to
712 _definitions.py The auxillary classes currently get
713 written redudantly into each capture object, so we can look in
714 one of them -- we just use the last one from the loop above.
717 with
open("{}/_definitions.py".format(options
.output_dir
), "w") as f
:
719 f
.write("from juju.client.facade import Type, ReturnMapping\n\n")
721 [k
for k
in captures
[version
].keys() if "Facade" not in k
]):
722 print(captures
[version
][key
], file=f
)
725 def write_client(captures
, options
):
727 Write the TypeFactory classes to _client.py, along with some
728 imports and tables so that we can look up versioned Facades.
731 with
open("{}/_client.py".format(options
.output_dir
), "w") as f
:
733 f
.write("from juju.client._definitions import *\n\n")
734 clients
= ", ".join("_client{}".format(v
) for v
in captures
)
735 f
.write("from juju.client import " + clients
+ "\n\n")
736 f
.write(CLIENT_TABLE
.format(clients
=",\n ".join(
737 ['"{}": _client{}'.format(v
, v
) for v
in captures
])))
738 f
.write(LOOKUP_FACADE
)
739 f
.write(TYPE_FACTORY
)
740 for key
in sorted([k
for k
in factories
.keys() if "Facade" in k
]):
741 print(factories
[key
], file=f
)
744 def generate_facades(options
):
745 captures
= defaultdict(codegen
.Capture
)
747 for p
in sorted(glob(options
.schema
)):
749 juju_version
= 'latest'
752 juju_version
= re
.search(JUJU_VERSION
, p
).group()
753 except AttributeError:
754 print("Cannot extract a juju version from {}".format(p
))
755 print("Schemas must include a juju version in the filename")
758 new_schemas
= json
.loads(Path(p
).read_text("utf-8"))
759 schemas
[juju_version
] = [Schema(s
) for s
in new_schemas
]
761 # Build all of the auxillary (unversioned) classes
762 # TODO: get rid of some of the excess trips through loops in the
764 for juju_version
in sorted(schemas
.keys()):
765 for schema
in schemas
[juju_version
]:
766 schema
.buildDefinitions()
767 buildTypes(schema
, captures
[schema
.version
])
769 # Build the Facade classes
770 for juju_version
in sorted(schemas
.keys()):
771 for schema
in schemas
[juju_version
]:
772 cls
, source
= buildFacade(schema
)
773 cls_name
= "{}Facade".format(schema
.name
)
775 captures
[schema
.version
].clear(cls_name
)
776 # Make the factory class for _client.py
777 make_factory(cls_name
)
778 # Make the actual class
779 captures
[schema
.version
][cls_name
].write(source
)
780 # Build the methods for each Facade class.
781 buildMethods(cls
, captures
[schema
.version
])
782 # Mark this Facade class as being done for this version --
783 # helps mitigate some excessive looping.
784 CLASSES
[schema
.name
] = cls
790 parser
= argparse
.ArgumentParser()
791 parser
.add_argument("-s", "--schema", default
="juju/client/schemas*")
792 parser
.add_argument("-o", "--output_dir", default
="juju/client")
793 options
= parser
.parse_args()
800 # Generate some text blobs
801 captures
= generate_facades(options
)
803 # ... and write them out
804 last_version
= write_facades(captures
, options
)
805 write_definitions(captures
, options
, last_version
)
806 write_client(captures
, options
)
809 if __name__
== '__main__':