Skip to content

Commit

Permalink
Moved templated loading to seperate module
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelvanstraten committed Sep 14, 2023
1 parent 6e1ad4a commit 268cd94
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 96 deletions.
14 changes: 6 additions & 8 deletions Sources/CodeGen/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
from os.path import abspath
from typing import List

from jinja2 import Template
from parse import process_json_files

from parsing_types.command import Command
from git_utils import make_sure_remote_repo_is_downloaded
from utils import clean_out_directory, get_todays_date, THIS_DIR
from swift_format import format_files
from templates import render

SRC_DIR = abspath(THIS_DIR + "/redis/src")
OUT_DIR = abspath(THIS_DIR + "/../SwiftyRedis/CodeGen/Commands")
Expand All @@ -18,16 +17,15 @@
def write_extensions_file(commands: List[Command], file_name: str):
with open(f"{OUT_DIR}/{file_name}", "x") as file:
file.write(
extension.render(
filename=file_name, creation_date=get_todays_date(), commands=commands
render(
"extension.swift",
filename=file_name,
creation_date=get_todays_date(),
commands=commands,
)
)


with open(THIS_DIR + "/templates/extension.swift", "r") as file:
extension = Template(file.read())


@click.group()
def cli():
pass
Expand Down
43 changes: 20 additions & 23 deletions Sources/CodeGen/parsing_types/argument.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from ast import Set
import os.path
from collections import Counter
from typing import List, Dict
from os.path import abspath
from jinja2 import Template

from templates import render
from utils import camel_case, snake_case, THIS_DIR
from config import names_to_substitute, token_to_substitute, arguments_to_ignore

Expand All @@ -25,28 +26,22 @@
"Int64": "123",
}

with open(abspath(f"{THIS_DIR}/templates/parameter.swift")) as file:
parameter_template = Template(file.read())

with open(abspath(f"{THIS_DIR}/templates/test_parameter.swift")) as file:
test_parameter_template = Template(file.read())


class Argument(object):
class Argument:
def __init__(self, desc: Dict):
self.name: str = names_to_substitute.get(
self.name = names_to_substitute.get(
camel_case(desc["name"]), camel_case(desc["name"])
)
self.type: str = ARG_TYPES.get(desc["type"])
self.type = ARG_TYPES.get(desc["type"], "unsupported type")
self.token = desc.get("token")
self.backup_token: str = desc["name"]
self.sanitized_token: str = (
self.backup_token = desc["name"]
self.sanitized_token = (
token_to_substitute.get(self.token, self.token)
if self.token
else snake_case(self.backup_token).upper()
)
self.is_optional: bool = desc.get("optional", False)
self.is_variadic: bool = desc.get("multiple", False)
self.is_optional = desc.get("optional", False)
self.is_variadic = desc.get("multiple", False)
self.must_have_label = False
if self.token:
self.token = self.token.replace('"', '\\"')
Expand All @@ -55,7 +50,8 @@ def use_token_as_name(self):
self.name = self.sanitized_token

def parameter(self):
return parameter_template.render(
return render(
"parameter.swift",
parameter_name=self.name,
parameter_type=self.type,
is_optional=self.is_optional,
Expand All @@ -64,7 +60,8 @@ def parameter(self):
)

def test_parameter(self):
return test_parameter_template.render(
return render(
"test_parameter.swift",
parameter_name=self.name,
parameter_value=self.test_value(),
)
Expand All @@ -79,9 +76,9 @@ def is_option(self):
def parse_args(
args: List[Dict], parent_name: str, make_options_arg=True, are_sub_args=False
):
parsed_args: List[Argument] = []
optional_args: List[Argument] = []
used_arg_names: Set[str] = set()
parsed_args = []
optional_args = []
arg_names_counter = Counter()

for arg in args:
if arg["type"] == "oneof":
Expand All @@ -95,12 +92,12 @@ def parse_args(
else:
new_arg = Argument(arg)

if new_arg.name in used_arg_names:
if arg_names_counter[new_arg.name] > 0:
new_arg.use_token_as_name()
else:
used_arg_names.add(new_arg.name)
arg_names_counter[new_arg.name] += 1

if not new_arg.name in arguments_to_ignore:
if new_arg.name not in arguments_to_ignore:
if new_arg.is_option() and make_options_arg:
optional_args.append(new_arg)
else:
Expand Down
33 changes: 9 additions & 24 deletions Sources/CodeGen/parsing_types/command.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,9 @@
from os.path import abspath
from typing import List

from utils import kebab_case, sanitize, snake_case, THIS_DIR
from utils import kebab_case, sanitize, snake_case

from parsing_types.argument import Argument, parse_args
from jinja2 import Template

with open(abspath(THIS_DIR + "/templates/command.swift")) as file:
command_template = Template(
file.read(),
)

with open(abspath(THIS_DIR + "/templates/command_test.swift")) as file:
command_test_template = Template(
file.read(),
)

with open(abspath(THIS_DIR + "/templates/options.swift")) as file:
options_template = Template(file.read())
from templates import render


class Command(object):
Expand All @@ -26,11 +12,13 @@ def __init__(self, name, desc, is_subcommand: bool = False):
self.is_subcommand = is_subcommand
self.name: str = sanitize(name.upper())
self.container_name = desc.get("container")
self.args: List[Argument] = parse_args(self.desc.get(
"arguments", []), self.fullname())
self.args: List[Argument] = parse_args(
self.desc.get("arguments", []), self.fullname()
)

def func(self, pipeline: bool = False, void: bool = False) -> str:
return command_template.render(
return render(
"command.swift",
func_name=self.func_name(),
void=void,
pipeline=pipeline,
Expand All @@ -42,14 +30,11 @@ def func(self, pipeline: bool = False, void: bool = False) -> str:
time_complexity=self.desc.get("complexity"),
history=self.desc.get("history"),
docs_name=self.fullname(),
docs_link_name=kebab_case(self.fullname())
docs_link_name=kebab_case(self.fullname()),
)

def test(self) -> str:
return command_test_template.render(
func_name=self.func_name(),
args=self.args
)
return render("command_test.swift", func_name=self.func_name(), args=self.args)

def func_name(self):
return snake_case(self.fullname())
Expand Down
24 changes: 11 additions & 13 deletions Sources/CodeGen/parsing_types/enum_argument.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
from os.path import abspath
from jinja2 import Template
from parsing_types.argument import parse_args

from utils import camel_case, THIS_DIR
from utils import camel_case
from parsing_types.complex_argument import ComplexArgument
from templates import render

with open(abspath(THIS_DIR + "/templates/enum.swift")) as file:
enum_template = Template(
file.read(),
)

class EnumArgument(ComplexArgument):
def __init__(self, parent_name, desc, is_sub_arg=False):
super().__init__(parent_name, desc, is_sub_arg)
self.args = parse_args(desc.get("arguments", []), self.fullname(), make_options_arg=False, are_sub_args=True)
self.args = parse_args(
desc.get("arguments", []),
self.fullname(),
make_options_arg=False,
are_sub_args=True,
)

def custom_type(self):
return enum_template.render(
enum_name=self.type,
args=self.args,
camel_case=camel_case
)
return render(
"enum.swift", enum_name=self.type, args=self.args, camel_case=camel_case
)
15 changes: 3 additions & 12 deletions Sources/CodeGen/parsing_types/options_argument.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
from os.path import abspath
from jinja2 import Template

from utils import pascal_case, THIS_DIR
from utils import pascal_case
from parsing_types.complex_argument import ComplexArgument
from templates import render

with open(abspath(THIS_DIR + "/templates/options.swift")) as file:
options_template = Template(
file.read(),
)

class OptionsArgument(ComplexArgument):
def __init__(self, parent_name, options, is_sub_arg=False):
Expand All @@ -19,7 +13,4 @@ def __init__(self, parent_name, options, is_sub_arg=False):
self.must_have_label = False

def custom_type(self):
return options_template.render(
options_name=self.type,
options=self.options
)
return render("options.swift", options_name=self.type, options=self.options)
24 changes: 8 additions & 16 deletions Sources/CodeGen/parsing_types/struct_argument.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
from os.path import abspath
from jinja2 import Template
from parsing_types.complex_argument import ComplexArgument

from utils import camel_case, THIS_DIR
from utils import camel_case
from parsing_types.argument import parse_args
from templates import render

with open(abspath(THIS_DIR + "/templates/struct.swift")) as file:
struct_template = Template(
file.read(),
)

with open(abspath(THIS_DIR + "/templates/options.swift")) as file:
options_template = Template(file.read())

class StructArgument(ComplexArgument):
def __init__(self, parent_name, desc, is_sub_arg=False):
super().__init__(parent_name, desc, is_sub_arg)
self.args = parse_args(desc.get("arguments", []), self.fullname(), are_sub_args=True)
self.args = parse_args(
desc.get("arguments", []), self.fullname(), are_sub_args=True
)

def custom_type(self):
return struct_template.render(
struct_name=self.type,
args=self.args,
camel_case=camel_case
)
return render(
"struct.swift", struct_name=self.type, args=self.args, camel_case=camel_case
)
22 changes: 22 additions & 0 deletions Sources/CodeGen/templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import os
from jinja2 import Environment, FileSystemLoader

# Get the directory containing this script
current_dir = os.path.dirname(os.path.abspath(__file__))
template_dir = os.path.join(current_dir, "templates")

# Create a Jinja2 environment
env = Environment(loader=FileSystemLoader(template_dir))


def render(template_name: str, *args, **kwargs) -> str:
"""
Render a Jinja2 template with the given arguments.
:param template_name: The name of the template file.
:param args: Positional arguments to pass to the template.
:param kwargs: Keyword arguments to pass to the template.
:return: The rendered template as a string.
"""
template = env.get_template(template_name)
return template.render(*args, **kwargs)

0 comments on commit 268cd94

Please sign in to comment.