Skip to content

Commit

Permalink
ajout de la command djanog et de la command cli et multiple amélioration
Browse files Browse the repository at this point in the history
  • Loading branch information
enzofrnt committed Mar 10, 2024
1 parent 4e9ad8f commit 2b4ed07
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 16 deletions.
1 change: 1 addition & 0 deletions django_model_to_typescript_types/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .modeltotypescriptconverter import ModelToTypeScriptConverter, main
5 changes: 1 addition & 4 deletions django_model_to_typescript_types/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ class DjangoModelToTypescriptTypesConfig(AppConfig):

def ready(self):
if os.environ.get('RUN_MAIN') :
print('Lets convert the models to typescript types')
# converter = ModelToTypeScriptConverter(os.environ.get('TS_APP_TO_INCLUDE', 'app'), os.environ.get('TS_PATH', '/tmp/tsinterface/interfaces.ts'), os.environ.get('TS_SEPERATED_FILES', False))
print("TS_SEPERATED_FILES "+os.environ.get('TS_SEPERATED_FILES', True))
converter = ModelToTypeScriptConverter(os.environ.get('TS_APP_TO_INCLUDE', 'app'), os.environ.get('TS_PATH', '/tmp/tsinterface/'), os.environ.get('TS_SEPERATED_FILES', True))
converter = ModelToTypeScriptConverter(os.environ.get('TS_APP_TO_INCLUDE', 'app'), os.environ.get('TS_PATH', '/tmp/tsinterface/'), os.environ.get('TS_SEPERATED_FILES', False), os.environ.get('DJANGO2TS_VERBOSE', False))
converter.generate_interfaces()


Expand Down
Empty file.
Empty file.
14 changes: 14 additions & 0 deletions django_model_to_typescript_types/management/commands/django2ts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import os

from django.core.management.base import BaseCommand
from ...modeltotypescriptconverter import ModelToTypeScriptConverter

class Command(BaseCommand):
"""Django command to pause execution until database is available"""

def handle(self, *args, **options):
"""Handle the command"""
converter = ModelToTypeScriptConverter(os.environ.get('TS_APP_TO_INCLUDE', 'app'), os.environ.get('TS_PATH', '/tmp/tsinterface/'), os.environ.get('TS_SEPERATED_FILES', False))
converter.generate_interfaces()


89 changes: 80 additions & 9 deletions django_model_to_typescript_types/modeltotypescriptconverter.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# https://gist.github.com/emoss08/c87c9864ce2af470dc301ff64e39f857
# https://gist.github.com/guizesilva/474fce56fcd5ab766e65e11e0dbff545
import os
import argparse
import sys
import importlib

from django.apps import apps
from django.core.wsgi import get_wsgi_application
from rich.progress import Progress, BarColumn, TextColumn, TimeRemainingColumn

class ModelToTypeScriptConverter:
def __init__(self, apps_to_include=['app'], path_for_interfaces='/tmp/tsinterface/', separated_files=False):
def __init__(self, apps_to_include=['app'], path_for_interfaces='/tmp/tsinterface/', separated_files=False, verbose=False):
self.apps_to_include = apps_to_include.split(',')
self.path_for_interfaces = path_for_interfaces
self.separated_files = separated_files if isinstance(separated_files, bool) else separated_files.lower() in ('true', '1', 't')
Expand All @@ -27,10 +32,16 @@ def __init__(self, apps_to_include=['app'], path_for_interfaces='/tmp/tsinterfac
"UUIDField": "string",
"BigAutoField": "number",
}
# New attribute to keep track of model relationships
self.verbose = verbose
self.model_relations = {}

def get_wsgi_application(self):
def get_wsgi_application(self):
current_folder = os.getcwd()
if current_folder not in sys.path:
sys.path.append(current_folder)
modules = [f[:-3] for f in os.listdir(current_folder) if f.endswith('.py') and not f.startswith('__')]
for module in modules:
globals()[module] = importlib.import_module(module)
get_wsgi_application()

def to_camel_case(self, snake_str):
Expand Down Expand Up @@ -58,7 +69,6 @@ def collect_model_relations(self, all_models):
def generate_interface_file(self, model):
filename = f"{self.path_for_interfaces}{model.__name__.lower()}.ts"
with open(filename, "w") as file:
print(f"Generating {model.__name__}.ts")
file.write(self.generate_interface_definition(model))

def generate_interface_definition(self, model):
Expand Down Expand Up @@ -112,18 +122,79 @@ def generate_field_line(self, field):
name += "?"

return f"{name}: {_type};", needs_import

def generate_single_interface_file(self, all_models):
with Progress(
TextColumn("[bold green]{task.fields[filename]}", justify="right"),
BarColumn(bar_width=None, complete_style="green", finished_style="green"),
"[progress.percentage]{task.percentage:>3.0f}%",
TimeRemainingColumn(),
expand=True
) as progress:
generate_ts_models = progress.add_task("[red]Converting Django Models to TypeScript Models...", total=len(all_models), filename="interfaces.ts")
filename = f"{self.path_for_interfaces}interfaces.ts"
with open(filename, "w") as file:
print("Generating interfaces.ts")
for model in all_models:
file.write(self.generate_interface_definition(model))
progress.update(generate_ts_models, advance=1)

def generate_interfaces(self, in_django=True):
if not in_django:
self.get_wsgi_application()


all_models = [model for model in apps.get_models() if model._meta.app_label in self.apps_to_include]
nb_models = len(all_models)

if nb_models == 0:
print("No models found.")
return

print("Generating TypeScript interfaces...")
print(f"{nb_models} models found.")

def generate_interfaces(self):
all_models = apps.get_models()
os.makedirs(os.path.dirname(self.path_for_interfaces), exist_ok=True)

# Collect relationships between models
self.collect_model_relations(all_models)

if self.separated_files:
for model in all_models:
if model._meta.app_label in self.apps_to_include:
with Progress(
TextColumn("[bold green]Processing", justify="right"),
BarColumn(bar_width=None, complete_style="green", finished_style="green"),
"[progress.percentage]{task.percentage:>3.0f}%",
TimeRemainingColumn(),
expand=True
) as progress:
generate_ts_models = progress.add_task("[red]Converting Django Models to TypeScript Models...", total=len(all_models))
for model in all_models:
filename = model.__name__.lower() + ".ts"
progress.console.print(f"Generating {filename}")
self.generate_interface_file(model)
progress.update(generate_ts_models, advance=1)
else:
self.generate_single_interface_file(all_models)

def main():
# Configuration du parseur d'arguments
parser = argparse.ArgumentParser(description='Convert Django Models to TypeScript Models')
parser.add_argument('--apps_to_include', default='app', help='Comma separated list of apps to include')
parser.add_argument('--path_for_interfaces', default='/tmp/tsinterface/', help='Path for the TypeScript interfaces')
parser.add_argument('--separated_files', action='store_true', help='Generate separated files for each model')
parser.add_argument('--verbose', action='store_true', help='Verbose output')
args = parser.parse_args()

# Conversion des arguments de ligne de commande
apps_to_include = args.apps_to_include
path_for_interfaces = args.path_for_interfaces
separated_files = args.separated_files
verbose = args.verbose

# Création et exécution du convertisseur
converter = ModelToTypeScriptConverter(apps_to_include, path_for_interfaces, separated_files, verbose)
converter.generate_interfaces(in_django=False)

if __name__ == "__main__":
main()


11 changes: 8 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@
install_requires=[
'django',
],
description='A package to create your Typescript types/models from your Django models.',
description='A package to create your Typescript Types/Models from your Django Models.',
long_description=long_description,
long_description_content_type="text/markdown",
author='Horou and Enzo_frnt',
url='https://github.com/Horou/djangorestframework-deepserializer',
author='Enzo_frnt',
url='https://github.com/enzofrnt/Django-Model-to-TypeScript',
classifiers=[
'Framework :: Django',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
],
entry_points={
'console_scripts': [
'django2ts=django_model_to_typescript_types:main'
],
},
)

0 comments on commit 2b4ed07

Please sign in to comment.