From a6cbc002f6d180297a1d984ee6db24dfe9728b8e Mon Sep 17 00:00:00 2001 From: Ferdinand Thiessen Date: Thu, 23 Dec 2021 02:48:28 +0100 Subject: [PATCH] fix(cli): InterfaceGenerator now works even without a namespace defined --- flaschengeist/cli/InterfaceGenerator.py | 38 ++++++++++++++++++------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/flaschengeist/cli/InterfaceGenerator.py b/flaschengeist/cli/InterfaceGenerator.py index 177a1a9..3bcb545 100644 --- a/flaschengeist/cli/InterfaceGenerator.py +++ b/flaschengeist/cli/InterfaceGenerator.py @@ -1,3 +1,4 @@ +import io import sys import inspect import logging @@ -93,15 +94,32 @@ class InterfaceGenerator: self.basename = models.__name__ self.walker(("models", models)) + def _write_types(self): + TYPE = "type {name} = {alias};\n" + INTERFACE = "interface {name} {{\n{properties}}}\n" + PROPERTY = "\t{name}{modifier}: {type};\n" + + buffer = io.StringIO() + for cls, props in self.classes.items(): + if isinstance(props, str): + buffer.write(TYPE.format(name=cls, alias=props)) + else: + buffer.write( + INTERFACE.format( + name=cls, + properties="".join( + [PROPERTY.format(name=name, modifier=props[name][0], type=props[name][1]) for name in props] + ), + ) + ) + return buffer + def write(self): with (open(self.filename, "w") if self.filename else sys.stdout) as file: - file.write("declare namespace {} {{\n".format(self.namespace)) - for cls, params in self.classes.items(): - if isinstance(params, str): - file.write("\ttype {} = {};\n".format(cls, params)) - else: - file.write("\tinterface {} {{\n".format(cls)) - for name in params: - file.write("\t\t{}{}: {};\n".format(name, *params[name])) - file.write("\t}\n") - file.write("}\n") + if self.namespace: + file.write(f"declare namespace {self.namespace} {{\n") + for line in self._write_types().getvalue().split("\n"): + file.write(f"\t{line}\n") + file.write("}\n") + else: + file.write(self._write_types().getvalue())