Skip to content

Instantly share code, notes, and snippets.

@aranega
Created July 3, 2018 16:09
Show Gist options
  • Save aranega/881559dc4d58baf29d0869a14c8cdb8f to your computer and use it in GitHub Desktop.
Save aranega/881559dc4d58baf29d0869a14c8cdb8f to your computer and use it in GitHub Desktop.
from pyecore.resources import ResourceSet
import pyecore.ecore as ecore
import multigen
from pyecoregen.ecore import EcoreTask
class RenameTask(EcoreTask):
template_name = 'update_name.py.tpl'
element_type = ecore.EPackage
@staticmethod
def filename_for_element(package):
return 'update_name.py'
@staticmethod
def all_structural_features(package):
return (f for f in package.eAllContents()
if isinstance(f, ecore.EStructuralFeature))
def create_template_context(self, element, **kwargs):
return super().create_template_context(
element=element,
all_features=self.all_structural_features(element)
)
def create_environment(self, element, **kwargs):
environment = super().create_environment(
element=element,
all_features=self.all_structural_features(element)
)
environment.filters['extended_name'] = self.filter_extended_name
return environment
class UpdateNameGenerator(multigen.jinja.JinjaGenerator):
templates_path = '.'
@staticmethod
def filter_extended_name(value: ecore.ENamedElement) -> str:
annotation = value.getEAnnotation('http:///org/eclipse/emf/ecore/util/ExtendedMetaData')
new_name = annotation.details.get('name', '') if annotation else None
return new_name
def __init__(self, **kwargs):
self.tasks = [RenameTask()]
super().__init__(**kwargs)
def create_environment(self, **kwargs):
environment = super().create_environment(**kwargs)
environment.filters['extended_name'] = self.filter_extended_name
return environment
# Load your .ecore and launch the code generation
rset = ResourceSet()
root = rset.get_resource('A.ecore').contents[0]
generator = UpdateNameGenerator()
generator.generate(root, '.')
from .{{ element.name }} import *
{% for feature in all_features -%}
{%- if feature | extended_name -%}
{{ feature.eContainingClass.name }}.{{ feature.name }}.name = '{{ feature | extended_name }}'
setattr({{ feature.eContainingClass.name }}, '{{ feature | extended_name }}', {{ feature.eContainingClass.name }}.{{ feature.name }})
{% endif %}
{%- endfor %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment