Fixed name conflict in auto-generated code
[osm/N2VC.git] / juju / client / facade.py
index 5b7ac35..c4834ee 100644 (file)
@@ -124,7 +124,7 @@ class Args(list):
                     self.append((name, rtype))
 
     def do_explode(self, kind):
-        if kind in basic_types:
+        if kind in basic_types or type(kind) is typing.TypeVar:
             return False
         if not issubclass(kind, (typing.Sequence,
                                  typing.Mapping)):
@@ -188,9 +188,9 @@ def buildTypes(schema, capture):
     for kind in sorted((k for k in _types if not isinstance(k, str)),
                        key=lambda x: str(x)):
         name = _types[kind]
-        args = Args(kind)
         if name in classes:
             continue
+        args = Args(kind)
         source = ["""
 class {}(Type):
     _toSchema = {}
@@ -218,14 +218,22 @@ class {}(Type):
                 if arg_type in basic_types:
                     source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
                 elif issubclass(arg_type, typing.Sequence):
-                    value_type = arg_type_name.__parameters__[0]
+                    value_type = (
+                        arg_type_name.__parameters__[0]
+                        if len(arg_type_name.__parameters__)
+                        else None
+                    )
                     if type(value_type) is typing.TypeVar:
                         source.append("{}self.{} = [{}.from_json(o) for o in {} or []]".format(
                             INDENT * 2, arg_name, strcast(value_type), arg_name))
                     else:
                         source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
                 elif issubclass(arg_type, typing.Mapping):
-                    value_type = arg_type_name.__parameters__[1]
+                    value_type = (
+                        arg_type_name.__parameters__[1]
+                        if len(arg_type_name.__parameters__) > 1
+                        else None
+                    )
                     if type(value_type) is typing.TypeVar:
                         source.append("{}self.{} = {{k: {}.from_json(v) for k, v in ({} or dict()).items()}}".format(
                             INDENT * 2, arg_name, strcast(value_type), arg_name))
@@ -308,15 +316,22 @@ def ReturnMapping(cls):
             reply = await f(*args, **kwargs)
             if cls is None:
                 return reply
-            if 'Error' in reply:
+            if 'error' in reply:
                 cls = classes['Error']
             if issubclass(cls, typing.Sequence):
                 result = []
                 item_cls = cls.__parameters__[0]
                 for item in reply:
                     result.append(item_cls.from_json(item))
+                    """
+                    if 'error' in item:
+                        cls = classes['Error']
+                    else:
+                        cls = item_cls
+                    result.append(cls.from_json(item))
+                    """
             else:
-                result = cls.from_json(reply['Response'])
+                result = cls.from_json(reply['response'])
 
             return result
         return wrapper
@@ -329,9 +344,9 @@ def makeFunc(cls, name, params, result, async=True):
     assignments = []
     toschema = args.PyToSchemaMapping()
     for arg in args._get_arg_str(False, False):
-        assignments.append("{}params[\'{}\'] = {}".format(INDENT,
-                                                          toschema[arg],
-                                                          arg))
+        assignments.append("{}_params[\'{}\'] = {}".format(INDENT,
+                                                           toschema[arg],
+                                                           arg))
     assignments = "\n".join(assignments)
     res = retspec(result)
     source = """
@@ -343,8 +358,8 @@ def makeFunc(cls, name, params, result, async=True):
     Returns -> {res}
     '''
     # map input types to rpc msg
-    params = dict()
-    msg = dict(Type='{cls.name}', Request='{name}', Version={cls.version}, Params=params)
+    _params = dict()
+    msg = dict(type='{cls.name}', request='{name}', version={cls.version}, params=_params)
 {assignments}
     reply = {await}self.rpc(msg)
     return reply
@@ -395,7 +410,7 @@ def buildFacade(schema):
                                           version=schema.version,
                                           schema=schema))
     source = """
-class {name}(Type):
+class {name}Facade(Type):
     name = '{name}'
     version = {version}
     schema = {schema}
@@ -428,7 +443,10 @@ class Type:
         for k, v in (data or {}).items():
             d[cls._toPy.get(k, k)] = v
 
-        return cls(**d)
+        try:
+            return cls(**d)
+        except TypeError:
+            raise
 
     def serialize(self):
         d = {}
@@ -526,7 +544,10 @@ class Schema(dict):
                 add((name, self.buildArray(pprop, d + 1)))
             else:
                 add((name, Mapping[str, SCHEMA_TO_PYTHON[ppkind]]))
-            #print("{}{}".format(d * "   ", struct))
+
+        if not struct and node.get('additionalProperties', False):
+            add((name, Mapping[str, SCHEMA_TO_PYTHON['object']]))
+
         return struct
 
     def buildArray(self, obj, d=0):
@@ -558,9 +579,13 @@ def generate_facacdes(options):
     global classes
     schemas = json.loads(Path(options.schema).read_text("utf-8"))
     capture = codegen.CodeWriter()
-    capture.write("""
-from juju.client.facade import Type, ReturnMapping
-                  """)
+    capture.write(textwrap.dedent("""\
+        # DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py.
+        # Changes will be overwritten/lost when the file is regenerated.
+
+        from juju.client.facade import Type, ReturnMapping
+
+    """))
     schemas = [Schema(s) for s in schemas]
 
     for schema in schemas: