Skip to content

Commit

Permalink
Add ability to dynamically import namespaces from types in the tsd cl…
Browse files Browse the repository at this point in the history
…ient (#235)

* Add ability to dynamically import namespaces from types in the tsd client
  • Loading branch information
rogebrd committed May 17, 2021
1 parent 76986cb commit 35121e8
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion stone/backends/tsd_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,29 @@
help=('Wraps the response in a response class')
)

_cmdline_parser.add_argument(
'--import-namespaces',
default=False,
action='store_true',
help=('Adds an import statement at the top of the file to import each '
'namespace from the as a named import. Must be used in conjunction '
'with the --export-namespaces command when generating the ts_types.')
)
_cmdline_parser.add_argument(
'--import-template-string',
type=str,
default='IMPORT',
help=('The name of the template string to replace with import statement. '
'Defaults to IMPORT, which replaces the string /*IMPORT*/ with import.')
)
_cmdline_parser.add_argument(
'--types-file',
type=str,
default='',
help=('If using the --import-namespaces flag, this is the file that contains '
'the named exports to import here.')
)

_header = """\
// Auto-generated by Stone, do not modify.
"""
Expand Down Expand Up @@ -103,10 +126,32 @@ def generate(self, api):
t_end = len(template)
t_ends_with_newline = template[t_end - 1] == '\n'

self.emit_raw(template[0:r_start] + ('\n' if not r_ends_with_newline else ''))
if self.args.import_namespaces:
import_template_string = self.args.import_template_string
import_from_file = self.args.types_file
# /*IMPORT*/
i_match = re.search("/\\*%s\\*/" % (import_template_string), template)
if not i_match:
raise AssertionError(
'Missing /*%s*/ in TypeScript template file.' % import_template_string)
i_start = i_match.start()
i_end = i_match.end()
i_ends_with_newline = template[i_end - 1] == '\n'
t_end = len(template)
t_ends_with_newline = template[t_end - 1] == '\n'

self.emit_raw(template[0:i_start] + ('\n' if not i_ends_with_newline else ''))
self._generate_import(api, import_from_file)
self.emit_raw(template[i_end + 1:r_end] + ('\n' if not r_ends_with_newline else ''))
else:
self.emit_raw(template[0:r_start] + ('\n' if not r_ends_with_newline else ''))
self._generate_routes(api, spaces_per_indent, indent_level)
self.emit_raw(template[r_end + 1:t_end] + ('\n' if not t_ends_with_newline else ''))

def _generate_import(self, api, type_file):
namespaces = ", ".join(map(lambda namespace: namespace.name, api.namespaces.values()))
self.emit("import { %s } from '%s';" % (namespaces, type_file))

def _generate_routes(self, api, spaces_per_indent, indent_level):
with self.indent(dent=spaces_per_indent * (indent_level + 1)):
for namespace in api.namespaces.values():
Expand Down

0 comments on commit 35121e8

Please sign in to comment.