10 from collections
import defaultdict
12 from pathlib
import Path
13 from typing
import Any
, Mapping
, Sequence
, TypeVar
, Union
19 JUJU_VERSION
= re
.compile(r
'[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',
22 'ModelInfo', 'ApplicationDeploy']
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.
52 for _version in range(int(version), 0, -1):
54 facade = getattr(CLIENTS[str(_version)], name)
56 except (KeyError, AttributeError):
59 raise ImportError("No supported version for facade: "
68 def from_connection(cls, connection):
70 Given a connected Connection object, return an initialized and
71 connected instance of an API Interface matching the name of
74 @param connection: initialized Connection object.
77 facade_name = cls.__name__
78 if not facade_name.endswith('Facade'):
79 raise TypeError('Unexpected class name: {}'.format(facade_name))
80 facade_name = facade_name[:-len('Facade')]
81 version = connection.facades.get(facade_name)
83 raise Exception('No facade {} in facades {}'.format(facade_name,
86 c = lookup_facade(cls.__name__, version)
104 class KindRegistry(dict):
105 def register(self
, name
, version
, obj
):
106 self
[name
] = {version
: {
110 def lookup(self
, name
, version
=None):
111 """If version is omitted, max version is used"""
112 versions
= self
.get(name
)
116 return versions
[version
]
117 return versions
[max(versions
)]
119 def getObj(self
, name
, version
=None):
120 result
= self
.lookup(name
, version
)
122 obj
= result
["object"]
127 class TypeRegistry(dict):
130 refname
= Schema
.referenceName(name
)
131 if refname
not in self
:
132 result
= TypeVar(refname
)
133 self
[refname
] = result
134 self
[result
] = refname
139 _types
= TypeRegistry()
140 _registry
= KindRegistry()
142 factories
= codegen
.Capture()
146 if isinstance(v
, str):
153 return _types
.get(ref
)
157 return getRefType(obj
["$ref"])
161 kind
= obj
.get('type')
163 raise ValueError("%s has no type" % obj
)
164 result
= SCHEMA_TO_PYTHON
.get(kind
)
166 raise ValueError("%s has type %s" % (obj
, kind
))
170 basic_types
= [str, bool, int, float]
173 def name_to_py(name
):
174 result
= name
.replace("-", "_")
175 result
= result
.lower()
176 if keyword
.iskeyword(result
) or result
in dir(builtins
):
181 def strcast(kind
, keep_builtins
=False):
182 if (kind
in basic_types
or
183 type(kind
) in basic_types
) and keep_builtins
is False:
185 if str(kind
).startswith('~'):
187 if issubclass(kind
, typing
.GenericMeta
):
193 def __init__(self
, defs
):
196 rtypes
= _registry
.getObj(_types
[defs
])
198 if not self
.do_explode(rtypes
[0][1]):
199 for name
, rtype
in rtypes
:
200 self
.append((name
, rtype
))
202 for name
, rtype
in rtypes
:
203 self
.append((name
, rtype
))
205 def do_explode(self
, kind
):
206 if kind
in basic_types
or type(kind
) is typing
.TypeVar
:
208 if not issubclass(kind
, (typing
.Sequence
,
211 self
.extend(Args(kind
))
215 def PyToSchemaMapping(self
):
221 def SchemaToPyMapping(self
):
227 def _format(self
, name
, rtype
, typed
=True):
229 return "{} : {}".format(
234 return name_to_py(name
)
236 def _get_arg_str(self
, typed
=False, joined
=", "):
240 parts
.append(self
._format
(item
[0], item
[1], typed
))
242 return joined
.join(parts
)
250 parts
.append('{}=None'.format(name_to_py(item
[0])))
251 return ', '.join(parts
)
255 return self
._get
_arg
_str
(True)
258 return self
._get
_arg
_str
(False)
261 return self
._get
_arg
_str
(True, "\n")
264 def buildTypes(schema
, capture
):
266 for kind
in sorted((k
for k
in _types
if not isinstance(k
, str)),
267 key
=lambda x
: str(x
)):
269 if name
in capture
and name
not in NAUGHTY_CLASSES
:
272 # Write Factory class for _client.py
279 def __init__(self{}{}, **unknown_fields):
284 # pprint these to get stable ordering across regens
285 pprint
.pformat(args
.PyToSchemaMapping(), width
=999),
286 pprint
.pformat(args
.SchemaToPyMapping(), width
=999),
287 ", " if args
else "",
289 textwrap
.indent(args
.get_doc(), INDENT
* 2))]
292 source
.append("{}pass".format(INDENT
* 2))
295 arg_name
= name_to_py(arg
[0])
297 arg_type_name
= strcast(arg_type
)
298 if arg_type
in basic_types
:
299 source
.append("{}self.{} = {}".format(INDENT
* 2,
302 elif type(arg_type
) is typing
.TypeVar
:
303 source
.append("{}self.{} = {}.from_json({}) "
304 "if {} else None".format(INDENT
* 2,
309 elif issubclass(arg_type
, typing
.Sequence
):
311 arg_type_name
.__parameters
__[0]
312 if len(arg_type_name
.__parameters
__)
315 if type(value_type
) is typing
.TypeVar
:
317 "{}self.{} = [{}.from_json(o) "
318 "for o in {} or []]".format(INDENT
* 2,
323 source
.append("{}self.{} = {}".format(INDENT
* 2,
326 elif issubclass(arg_type
, typing
.Mapping
):
328 arg_type_name
.__parameters
__[1]
329 if len(arg_type_name
.__parameters
__) > 1
332 if type(value_type
) is typing
.TypeVar
:
334 "{}self.{} = {{k: {}.from_json(v) "
335 "for k, v in ({} or dict()).items()}}".format(
341 source
.append("{}self.{} = {}".format(INDENT
* 2,
345 source
.append("{}self.{} = {}".format(INDENT
* 2,
349 source
= "\n".join(source
)
351 capture
[name
].write(source
)
352 capture
[name
].write("\n\n")
353 co
= compile(source
, __name__
, "exec")
362 # only return 1, so if there is more than one type
363 # we need to include a union
364 # In truth there is only 1 return
365 # Error or the expected Type
368 if defs
in basic_types
:
369 return strcast(defs
, False)
370 rtypes
= _registry
.getObj(_types
[defs
])
374 return Union
[tuple([strcast(r
[1], True) for r
in rtypes
])]
375 return strcast(rtypes
[0][1], False)
378 def return_type(defs
):
381 rtypes
= _registry
.getObj(_types
[defs
])
392 def type_anno_func(func
, defs
, is_result
=False):
396 rtypes
= _registry
.getObj(_types
[defs
])
401 elif len(rtypes
) > 1:
402 annos
[kn
] = Union
[tuple([r
[1] for r
in rtypes
])]
404 annos
[kn
] = rtypes
[0][1]
406 for name
, rtype
in rtypes
:
407 name
= name_to_py(name
)
409 func
.__annotations
__.update(annos
)
413 def ReturnMapping(cls
):
414 # Annotate the method with a return Type
415 # so the value can be cast
418 async def wrapper(*args
, **kwargs
):
420 reply
= await f(*args
, **kwargs
)
424 cls
= CLASSES
['Error']
425 if issubclass(cls
, typing
.Sequence
):
427 item_cls
= cls
.__parameters
__[0]
429 result
.append(item_cls
.from_json(item
))
432 cls = CLASSES['Error']
435 result.append(cls.from_json(item))
438 result
= cls
.from_json(reply
['response'])
445 def makeFunc(cls
, name
, params
, result
, _async
=True):
449 toschema
= args
.PyToSchemaMapping()
450 for arg
in args
._get
_arg
_str
(False, False):
451 assignments
.append("{}_params[\'{}\'] = {}".format(INDENT
,
454 assignments
= "\n".join(assignments
)
455 res
= retspec(result
)
458 @ReturnMapping({rettype})
459 {_async}def {name}(self{argsep}{args}):
464 # map input types to rpc msg
466 msg = dict(type='{cls.name}',
468 version={cls.version},
471 reply = {_await}self.rpc(msg)
476 fsource
= source
.format(_async
="async " if _async
else "",
478 argsep
=", " if args
else "",
481 rettype
=result
.__name
__ if result
else None,
482 docstring
=textwrap
.indent(args
.get_doc(), INDENT
),
484 assignments
=assignments
,
485 _await
="await " if _async
else "")
492 def buildMethods(cls
, capture
):
493 properties
= cls
.schema
['properties']
494 for methodname
in sorted(properties
):
495 method
, source
= _buildMethod(cls
, methodname
)
496 setattr(cls
, methodname
, method
)
497 capture
["{}Facade".format(cls
.__name
__)].write(source
, depth
=1)
500 def _buildMethod(cls
, name
):
503 method
= cls
.schema
['properties'][name
]
504 if 'properties' in method
:
505 prop
= method
['properties']
506 spec
= prop
.get('Params')
508 params
= _types
.get(spec
['$ref'])
509 spec
= prop
.get('Result')
512 result
= _types
.get(spec
['$ref'])
514 result
= SCHEMA_TO_PYTHON
[spec
['type']]
515 return makeFunc(cls
, name
, params
, result
)
518 def buildFacade(schema
):
519 cls
= type(schema
.name
, (Type
,), dict(name
=schema
.name
,
520 version
=schema
.version
,
523 class {name}Facade(Type):
527 """.format(name
=schema
.name
,
528 version
=schema
.version
,
529 schema
=textwrap
.indent(pprint
.pformat(schema
), " "))
533 class TypeEncoder(json
.JSONEncoder
):
534 def default(self
, obj
):
535 if isinstance(obj
, Type
):
536 return obj
.serialize()
537 return json
.JSONEncoder
.default(self
, obj
)
541 def connect(self
, connection
):
542 self
.connection
= connection
544 async def rpc(self
, msg
):
545 result
= await self
.connection
.rpc(msg
, encoder
=TypeEncoder
)
549 def from_json(cls
, data
):
550 if isinstance(data
, cls
):
552 if isinstance(data
, str):
554 data
= json
.loads(data
)
555 except json
.JSONDecodeError
:
558 for k
, v
in (data
or {}).items():
559 d
[cls
._toPy
.get(k
, k
)] = v
568 for attr
, tgt
in self
._toSchema
.items():
569 d
[tgt
] = getattr(self
, attr
)
573 return json
.dumps(self
.serialize(), cls
=TypeEncoder
, sort_keys
=True)
577 def __init__(self
, schema
):
578 self
.name
= schema
['Name']
579 self
.version
= schema
['Version']
580 self
.update(schema
['Schema'])
583 def referenceName(cls
, ref
):
584 if ref
.startswith("#/definitions/"):
585 ref
= ref
.rsplit("/", 1)[-1]
588 def resolveDefinition(self
, ref
):
589 return self
['definitions'][self
.referenceName(ref
)]
591 def deref(self
, prop
, name
):
592 if not isinstance(prop
, dict):
593 raise TypeError(prop
)
594 if "$ref" not in prop
:
597 target
= self
.resolveDefinition(prop
["$ref"])
600 def buildDefinitions(self
):
601 # here we are building the types out
602 # anything in definitions is a type
603 # but these may contain references themselves
604 # so we dfs to the bottom and build upwards
605 # when a types is already in the registry
606 defs
= self
.get('definitions')
609 for d
, data
in defs
.items():
610 if d
in _registry
and d
not in NAUGHTY_CLASSES
:
612 node
= self
.deref(data
, d
)
613 kind
= node
.get("type")
615 result
= self
.buildObject(node
, d
)
616 elif kind
== "array":
618 _registry
.register(d
, self
.version
, result
)
619 # XXX: This makes sure that the type gets added to the global
620 # _types dict even if no other type in the schema has a ref
624 def buildObject(self
, node
, name
=None, d
=0):
625 # we don't need to build types recursively here
626 # they are all in definitions already
627 # we only want to include the type reference
628 # which we can derive from the name
631 props
= node
.get("properties")
632 pprops
= node
.get("patternProperties")
634 # Sort these so the __init__ arg list for each Type remains
635 # consistently ordered across regens of client.py
636 for p
in sorted(props
):
639 add((p
, refType(prop
)))
643 add((p
, self
.buildArray(prop
, d
+ 1)))
644 elif kind
== "object":
645 struct
.extend(self
.buildObject(prop
, p
, d
+ 1))
647 add((p
, objType(prop
)))
649 if ".*" not in pprops
:
651 "Cannot handle actual pattern in patternProperties %s" %
655 add((name
, Mapping
[str, refType(pprop
)]))
657 ppkind
= pprop
["type"]
658 if ppkind
== "array":
659 add((name
, self
.buildArray(pprop
, d
+ 1)))
661 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
[ppkind
]]))
663 if not struct
and node
.get('additionalProperties', False):
664 add((name
, Mapping
[str, SCHEMA_TO_PYTHON
['object']]))
668 def buildArray(self
, obj
, d
=0):
669 # return a sequence from an array in the schema
671 return Sequence
[refType(obj
)]
673 kind
= obj
.get("type")
674 if kind
and kind
== "array":
676 return self
.buildArray(items
, d
+ 1)
678 return Sequence
[objType(obj
)]
684 'ReturnMapping': ReturnMapping
686 # Copy our types into the globals of the method
687 for facade
in _registry
:
688 ns
[facade
] = _registry
.getObj(facade
)
692 def make_factory(name
):
693 if name
in factories
:
695 factories
[name
].write("class {}(TypeFactory):\n pass\n\n".format(name
))
698 def write_facades(captures
, options
):
700 Write the Facades to the appropriate _client<version>.py
703 for version
in sorted(captures
.keys()):
704 filename
= "{}/_client{}.py".format(options
.output_dir
, version
)
705 with
open(filename
, "w") as f
:
707 f
.write("from juju.client.facade import Type, ReturnMapping\n")
708 f
.write("from juju.client._definitions import *\n\n")
710 [k
for k
in captures
[version
].keys() if "Facade" in k
]):
711 print(captures
[version
][key
], file=f
)
713 # Return the last (most recent) version for use in other routines.
717 def write_definitions(captures
, options
, version
):
719 Write auxillary (non versioned) classes to
720 _definitions.py The auxillary classes currently get
721 written redudantly into each capture object, so we can look in
722 one of them -- we just use the last one from the loop above.
725 with
open("{}/_definitions.py".format(options
.output_dir
), "w") as f
:
727 f
.write("from juju.client.facade import Type, ReturnMapping\n\n")
729 [k
for k
in captures
[version
].keys() if "Facade" not in k
]):
730 print(captures
[version
][key
], file=f
)
733 def write_client(captures
, options
):
735 Write the TypeFactory classes to _client.py, along with some
736 imports and tables so that we can look up versioned Facades.
739 with
open("{}/_client.py".format(options
.output_dir
), "w") as f
:
741 f
.write("from juju.client._definitions import *\n\n")
742 clients
= ", ".join("_client{}".format(v
) for v
in captures
)
743 f
.write("from juju.client import " + clients
+ "\n\n")
744 f
.write(CLIENT_TABLE
.format(clients
=",\n ".join(
745 ['"{}": _client{}'.format(v
, v
) for v
in captures
])))
746 f
.write(LOOKUP_FACADE
)
747 f
.write(TYPE_FACTORY
)
748 for key
in sorted([k
for k
in factories
.keys() if "Facade" in k
]):
749 print(factories
[key
], file=f
)
752 def generate_facades(options
):
753 captures
= defaultdict(codegen
.Capture
)
755 for p
in sorted(glob(options
.schema
)):
757 juju_version
= 'latest'
760 juju_version
= re
.search(JUJU_VERSION
, p
).group()
761 except AttributeError:
762 print("Cannot extract a juju version from {}".format(p
))
763 print("Schemas must include a juju version in the filename")
766 new_schemas
= json
.loads(Path(p
).read_text("utf-8"))
767 schemas
[juju_version
] = [Schema(s
) for s
in new_schemas
]
769 # Build all of the auxillary (unversioned) classes
770 # TODO: get rid of some of the excess trips through loops in the
772 for juju_version
in sorted(schemas
.keys()):
773 for schema
in schemas
[juju_version
]:
774 schema
.buildDefinitions()
775 buildTypes(schema
, captures
[schema
.version
])
777 # Build the Facade classes
778 for juju_version
in sorted(schemas
.keys()):
779 for schema
in schemas
[juju_version
]:
780 cls
, source
= buildFacade(schema
)
781 cls_name
= "{}Facade".format(schema
.name
)
783 captures
[schema
.version
].clear(cls_name
)
784 # Make the factory class for _client.py
785 make_factory(cls_name
)
786 # Make the actual class
787 captures
[schema
.version
][cls_name
].write(source
)
788 # Build the methods for each Facade class.
789 buildMethods(cls
, captures
[schema
.version
])
790 # Mark this Facade class as being done for this version --
791 # helps mitigate some excessive looping.
792 CLASSES
[schema
.name
] = cls
798 parser
= argparse
.ArgumentParser()
799 parser
.add_argument("-s", "--schema", default
="juju/client/schemas*")
800 parser
.add_argument("-o", "--output_dir", default
="juju/client")
801 options
= parser
.parse_args()
808 # Generate some text blobs
809 captures
= generate_facades(options
)
811 # ... and write them out
812 last_version
= write_facades(captures
, options
)
813 write_definitions(captures
, options
, last_version
)
814 write_client(captures
, options
)
817 if __name__
== '__main__':