Skip to content

Commit

Permalink
Fixes #59
Browse files Browse the repository at this point in the history
  • Loading branch information
Semprini committed Dec 5, 2023
1 parent 7d92d91 commit f94aa28
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 37 deletions.
32 changes: 29 additions & 3 deletions mdg/generate/__init__.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,46 @@
#!/usr/bin/python
import logging

from mdg.tools.validate import validate_package
from mdg.uml.validate import validate_package
from mdg.generate.render import output_model, output_test_cases
from mdg.parse import parse, ParseError
from mdg.parse import parse, ParseError, PARSERS
from mdg.config import settings

from mdg import generation_fields

logger = logging.getLogger('mdg')


def validate_settings():
logger.debug("Validating settings")

errors = []
if settings['generation_type'] not in generation_fields.keys():
errors.append( f"Settings generation_type of '{settings['generation_type']}' is not valid. Generation types are a dictionay of how to map UML attrribute types to physical types. Options are: {generation_fields.keys()}" )

if settings['parser'] not in PARSERS.keys():
errors.append( f"Settings parser of '{settings['parser']}' is not valid. Parser must match the input modelling tool type defined in 'source'. Options are: {PARSERS.keys()}" )

for template_definition in settings['model_templates']:
levels = ["root","copy","class","package","enumeration","assocication"]
if template_definition["level"] not in levels:
errors.append( f"Template level of '{template_definition['level']}' is not valid. Level defines how many times the output will be rendered and the objects passed to the template. Options are: {levels}" )

if errors != []:
logger.error(f"Errors in settings: {errors}")
return False

return True


def generate():
""" Loads XMI file from settings as an etree
Calls XMI parser to turn model and tests into python native (see UML metamodel)
Calls output functions to render for model and tests
"""
if not validate_settings():
logger.error("Due to errors in settings, not parsing or generating.")
return

logger.debug("generate begin")
try:
model_package, test_cases = parse()
Expand Down
49 changes: 26 additions & 23 deletions mdg/generate/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import Dict, Optional, List, Any

from jinja2 import Environment, FileSystemLoader, Template, BaseLoader

from jinja2.exceptions import TemplateNotFound

from mdg.config import settings
from mdg.tools.filters import get_filters
Expand Down Expand Up @@ -148,28 +148,31 @@ def output_model(package: UMLPackage) -> None:
output_level_copy(source_file, dest_file_template, package)
else:
# Create jinja2 teemplates for the source file and dest file name
source_template: Template = source_env.get_template(template_definition['source'])

# Filter template is optional and used to skip a file generation.
filter_template: Optional[Template] = None
if 'filter' in template_definition.keys():
filter_template = Template(template_definition['filter'])

# Select the output renderer based on the level requested
if template_definition['level'] == 'package':
if filter_template is None or filter_template.render(package=package) == "True":
output_level_package(source_template, dest_file_template, package)
elif template_definition['level'] == 'class':
output_level_class(source_template, dest_file_template, filter_template, package)
elif template_definition['level'] == 'enumeration':
output_level_enum(source_template, dest_file_template, filter_template, package)
elif template_definition['level'] == 'assocication':
output_level_assoc(source_template, dest_file_template, filter_template, package)
elif template_definition['level'] == 'root':
if package.parent is None:
output_level_package(source_template, dest_file_template, package)
else:
raise ValueError("'{}' is not a valid template level".format(template_definition['level']))
try:
source_template: Template = source_env.get_template(template_definition['source'])

# Filter template is optional and used to skip a file generation.
filter_template: Optional[Template] = None
if 'filter' in template_definition.keys():
filter_template = Template(template_definition['filter'])

# Select the output renderer based on the level requested
if template_definition['level'] == 'package':
if filter_template is None or filter_template.render(package=package) == "True":
output_level_package(source_template, dest_file_template, package)
elif template_definition['level'] == 'class':
output_level_class(source_template, dest_file_template, filter_template, package)
elif template_definition['level'] == 'enumeration':
output_level_enum(source_template, dest_file_template, filter_template, package)
elif template_definition['level'] == 'assocication':
output_level_assoc(source_template, dest_file_template, filter_template, package)
elif template_definition['level'] == 'root':
if package.parent is None:
output_level_package(source_template, dest_file_template, package)
else:
raise ValueError("'{}' is not a valid template level".format(template_definition['level']))
except TemplateNotFound:
logger.error(f"Could not find template to render from '{template_definition['source']}' in either the configured templates folder or the default templates folder. Check your templates_folder and source in settings.")

# Walk through the package hierarchy and recurse output
child: UMLPackage
Expand Down
17 changes: 8 additions & 9 deletions mdg/parse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@

logger = logging.getLogger(__name__)

PARSERS = {
'sparx': sparx_parse_uml,
'sparxdb': sparx_db_parse_uml,
'drawio': drawio_parse_uml,
'bouml': bouml_parse_uml,
'erwin': erwin_parse_uml,
}


class ParseError(Exception):
pass
Expand All @@ -21,15 +29,6 @@ def parse():
"""
logger.debug("parse begin")

# TODO: change to using a registration decorator
PARSERS = {
'sparx': sparx_parse_uml,
'sparxdb': sparx_db_parse_uml,
'drawio': drawio_parse_uml,
'bouml': bouml_parse_uml,
'erwin': erwin_parse_uml,
}

# Find the parser
parser = None
try:
Expand Down
2 changes: 1 addition & 1 deletion mdg/tests/test_sample.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import unittest

from mdg.parse import parse
from mdg.tools.validate import validate_package
from mdg.uml.validate import validate_package
from mdg.generate.render import output_model


Expand Down
2 changes: 1 addition & 1 deletion mdg/tools/mdg_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def generate(args):

def validate(args):
os.environ.setdefault("PYMDG_SETTINGS_MODULE", args.recipe_path)
from mdg.tools.validate import validate
from ..uml.validate import validate
validate()


Expand Down
File renamed without changes.

0 comments on commit f94aa28

Please sign in to comment.