Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import pyecore.ecore as Ecore
from pyecore.resources import global_registry, ResourceSet, URI, Resource
# Register static Ecore metamodel
global_registry.setdefault(Ecore.nsURI, Ecore)
def _build_path(obj):
if not obj.eContainmentFeature():
return '/'
feat = obj.eContainmentFeature()
parent = obj.eContainer()
name = feat.name
# TODO decode root names (non '@' prefixed)
if feat.many:
index = parent.__getattribute__(name).index(obj)
return '{0}/@{1}.{2}'.format(_build_path(parent), name, str(index))
else:
return '{0}/{1}'.format(_build_path(parent), name)
if __name__ == '__main__':
rset = ResourceSet()
def test_json_save_multiple_roots_roundtrip(tmpdir):
A = Ecore.EClass('A')
A.eStructuralFeatures.append(Ecore.EAttribute('name', Ecore.EString))
pack = Ecore.EPackage('pack', 'packuri', 'pack')
pack.eClassifiers.append(A)
f = tmpdir.mkdir('pyecore-tmp').join('multiple.json')
resource = JsonResource(URI(str(f)))
resource.append(A(name='root1'))
resource.append(A(name='root2'))
resource.save()
global_registry[pack.nsURI] = pack
resource = JsonResource(URI(str(f)))
resource.load()
assert len(resource.contents) == 2
assert resource.contents[0].name == 'root1'
assert resource.contents[1].name == 'root2'
del global_registry[pack.nsURI]
def test_xmiresource_load_ecore_testEMF():
xmi_file = path.join('tests', 'xmi', 'xmi-tests', 'testEMF.xmi')
resource = XMIResource(URI(xmi_file))
resource.load()
assert resource.contents != []
root = resource.contents[0]
A = root.getEClassifier('A')
assert A
B = root.getEClassifier('B')
assert B
TInterface = root.getEClassifier('TInterface')
assert TInterface
TClass = root.getEClassifier('TClass')
assert TClass
a = A()
assert Ecore.EcoreUtils.isinstance(a, TClass)
assert Ecore.EcoreUtils.isinstance(a, TInterface)
assert A.findEStructuralFeature('abstract')
assert A.findEStructuralFeature('isAbs')
assert a.isAbs is False
assert a.abstract is False
assert a.eResource is None
assert A.eResource is resource
from functools import partial
import pyecore.ecore as Ecore
from pyecore.ecore import *
name = 'library'
nsURI = 'http://emf.wikipedia.org/2011/Library'
nsPrefix = 'lib'
eClass = EPackage(name=name, nsURI=nsURI, nsPrefix=nsPrefix)
eClassifiers = {}
getEClassifier = partial(Ecore.getEClassifier, searchspace=eClassifiers)
BookCategory = EEnum('BookCategory', literals=['ScienceFiction', 'Biographie', 'Mistery']) # noqa
class Employee(EObject, metaclass=MetaEClass):
name = EAttribute(eType=EString)
age = EAttribute(eType=EInt)
def __init__(self, name=None, age=None, **kwargs):
if kwargs:
raise AttributeError('unexpected arguments: {}'.format(kwargs))
super().__init__()
if name is not None:
self.name = name
from .resource import ResourceSet, Resource, URI, global_registry
from . import xmi
from .. import ecore as Ecore
# Register basic resource factory
ResourceSet.resource_factory = {'xmi': lambda uri: xmi.XMIResource(uri),
'ecore': lambda uri: xmi.XMIResource(uri),
'*': lambda uri: xmi.XMIResource(uri)}
global_registry[Ecore.nsURI] = Ecore
__all__ = ['ResourceSet', 'Resource', 'URI', 'global_registry']
@staticmethod
def filename_for_element(package: ecore.EPackage):
"""Returns generated file name."""
raise NotImplementedError
def relative_path_for_element(self, element: ecore.EPackage):
path = os.path.join(self.folder_path_for_package(element),
self.filename_for_element(element))
return path
class EcorePackageInitTask(EcoreTask):
"""Generation of package init file from Ecore model with Jinja2."""
template_name = 'package.py.tpl'
element_type = ecore.EPackage
@staticmethod
def filename_for_element(package: ecore.EPackage):
return '__init__.py'
@staticmethod
def imported_classifiers_package(p: ecore.EPackage):
"""Determines which classifiers have to be imported into given package."""
classes = {c for c in p.eClassifiers if isinstance(c, ecore.EClass)}
references = itertools.chain(*(c.eAllReferences() for c in classes))
references_types = (r.eType for r in references)
imported = {c for c in references_types if getattr(c, 'ePackage', p) is not p}
imported_dict = {}
for classifier in imported:
import inspect
from . import ecore
def meta_behavior(self, fun):
setattr(self, fun.__name__, fun)
return fun
def behavior(self, fun):
setattr(self.python_class, fun.__name__, fun)
return fun
ecore.MetaEClass.behavior = meta_behavior
ecore.EClass.behavior = behavior
def main(fun):
fun.main = True
return fun
def run(eclass, *args, **kwargs):
cls = eclass.eClass.python_class
for _, attr in cls.__dict__.items():
if inspect.isfunction(attr) and getattr(attr, 'main', False):
return attr(eclass, *args, **kwargs)
raise NotImplementedError('No @main entry point found for {}'
.format(cls))
from lxml import etree
import pyecore.ecore as Ecore
from pyecore.resources import global_registry, ResourceSet, URI, Resource
# Register static Ecore metamodel
global_registry.setdefault(Ecore.nsURI, Ecore)
def _build_path(obj):
if not obj.eContainmentFeature():
return '/'
feat = obj.eContainmentFeature()
parent = obj.eContainer()
name = feat.name
# TODO decode root names (non '@' prefixed)
if feat.many:
index = parent.__getattribute__(name).index(obj)
return '{0}/@{1}.{2}'.format(_build_path(parent), name, str(index))
else:
return '{0}/{1}'.format(_build_path(parent), name)
elif isinstance(feat, Ecore.EReference) and not feat.containment:
if feat.many:
node.attrib[feat.name] = ' '.join(list(map(_build_path, value)))
else:
node.attrib[feat.name] = _build_path(value)
if isinstance(feat, Ecore.EReference) and feat.containment and feat.many:
children = root.__getattribute__(feat.name)
for child in children:
node.append(go_accross(child))
elif isinstance(feat, Ecore.EReference) and feat.containment:
child = root.__getattribute__(feat.name)
node.append(go_accross(child))
return node
if __name__ == '__main__':
global_registry[Ecore.nsURI] = Ecore
rset = ResourceSet()
# # UMLPrimitiveTypes Creation
# umltypes = Ecore.EPackage('umltypes')
# String = Ecore.EDataType('String', str)
# Boolean = Ecore.EDataType('Boolean', bool, False)
# Integer = Ecore.EDataType('Integer', int, 0)
# UnlimitedNatural = Ecore.EDataType('UnlimitedNatural', int, 0)
# Real = Ecore.EDataType('Real', float, 0.0)
# umltypes.eClassifiers.extend([String, Boolean, Integer, UnlimitedNatural, Real])
# rset.resources['platform:/plugin/org.eclipse.uml2.types/model/Types.ecore'] = umltypes
# # Register Ecore metamodel instance
# resource = rset.get_resource(URI('tests/xmi/xmi-tests/Ecore.ecore'))
# rset.resources['platform:/plugin/org.eclipse.emf.ecore/model/Ecore.ecore'] = resource.contents[0]
# resource = rset.get_resource(URI('tests/xmi/xmi-tests/UML.ecore'))
# expe2