Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XML generation and parsing #43

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions cimgen/cimgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ def as_json(self) -> dict[str, str]:
json_object = {}
if self.about():
json_object["about"] = self.about()
if self.namespace():
json_object["namespace"] = self.namespace()
if self.comment():
json_object["comment"] = self.comment()
if self.datatype():
Expand Down Expand Up @@ -52,6 +54,13 @@ def about(self) -> str:
else:
return ""

def namespace(self) -> str:
if "$rdf:about" in self.json_definition:
about = RDFSEntry._get_about_or_resource(self.json_definition["$rdf:about"])
return about[: -len(self.about())]
else:
return ""

# Capitalized True/False is valid in python but not in json.
# Do not use this function in combination with json.load()
def is_used(self) -> bool:
Expand Down Expand Up @@ -194,6 +203,7 @@ def __init__(self, rdfs_entry: RDFSEntry):
self.superclass: str = rdfs_entry.subclass_of()
self.subclass_list: list[str] = []
self.stereotype: str = rdfs_entry.stereotype()
self.namespace = rdfs_entry.namespace()

def attributes(self) -> list[dict]:
return self.attribute_list
Expand Down Expand Up @@ -391,6 +401,13 @@ def _parse_rdf(input_dic: dict, version: str) -> dict[str, dict[str, CIMComponen
for instance in enum_instances:
clarse = _get_rid_of_hash(instance["type"])
if clarse and clarse in classes_map:
if instance.get("comment"):
instance["wrapped_comment"] = _wrap_and_clean(
instance["comment"],
width=100,
initial_indent="# ",
subsequent_indent=(" # "),
)
classes_map[clarse].add_enum_instance(instance)
else:
logger.info("Class {} for enum instance {} not found.".format(clarse, instance))
Expand All @@ -417,6 +434,7 @@ def _write_all_files(
"class_location": lang_pack.get_class_location(class_name, elem_dict, version),
"class_name": class_name,
"class_origin": elem_dict[class_name].origins(),
"class_namespace": _get_namespace(elem_dict[class_name].namespace),
"enum_instances": elem_dict[class_name].enum_instances(),
"is_an_enum_class": elem_dict[class_name].is_an_enum_class(),
"is_a_primitive_class": elem_dict[class_name].is_a_primitive_class(),
Expand Down Expand Up @@ -455,6 +473,7 @@ def _write_all_files(
attribute["is_primitive_attribute"] = _get_bool_string(attribute_type == "primitive")
attribute["is_datatype_attribute"] = _get_bool_string(attribute_type == "datatype")
attribute["attribute_class"] = attribute_class
attribute["attribute_namespace"] = _get_namespace(attribute["namespace"])

class_details["attributes"].sort(key=lambda d: d["label"])
_write_files(class_details, output_path)
Expand Down Expand Up @@ -738,6 +757,14 @@ def _get_attribute_type(attribute: dict, class_infos: CIMComponentDefinition) ->
return attribute_type


def _get_namespace(parsed_namespace: str) -> str:
if parsed_namespace == "#":
namespace = cim_namespace
else:
namespace = parsed_namespace
return namespace


def _get_bool_string(bool_value: bool) -> str:
"""Convert boolean value into a string which is usable in both Python and Json.

Expand Down
21 changes: 10 additions & 11 deletions cimgen/languages/modernpython/lang_pack.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def _get_type_and_default(text: str, render: Callable[[str], str]) -> tuple[str,
attribute_txt = render(text)
attribute_json = eval(attribute_txt)
if attribute_json["is_class_attribute"]:
return ("Optional[str]", "default=None")
return ("str | None", "default=None")
elif attribute_json["is_list_attribute"]:
return ("list", "default_factory=list")
elif attribute_json["is_datatype_attribute"]:
Expand Down Expand Up @@ -88,14 +88,6 @@ def _get_python_type(datatype: str) -> str:
return "float"


def _set_imports(attributes: list[dict]) -> list[str]:
import_set = set()
for attribute in attributes:
if attribute["is_datatype_attribute"] or attribute["is_primitive_attribute"]:
import_set.add(attribute["attribute_class"])
return sorted(import_set)


def _set_datatype_attributes(attributes: list[dict]) -> dict:
datatype_attributes = {}
datatype_attributes["python_type"] = "None"
Expand Down Expand Up @@ -137,13 +129,20 @@ def run_template(output_path: str, class_details: dict) -> None:
template = class_template_file
class_details["set_default"] = _set_default
class_details["set_type"] = _set_type
class_details["imports"] = _set_imports(class_details["attributes"])
HUG0-D marked this conversation as resolved.
Show resolved Hide resolved
resource_file = _create_file(output_path, class_details, template)
_write_templated_file(resource_file, class_details, template["filename"])


def _create_file(output_path: str, class_details: dict, template: dict[str, str]) -> Path:
resource_file = Path(output_path) / "resources" / (class_details["class_name"] + template["ext"])
if (
class_details["is_a_primitive_class"]
or class_details["is_a_datatype_class"]
or class_details["is_an_enum_class"]
):
class_category = "types"
else:
class_category = ""
resource_file = Path(output_path) / "resources" / class_category / (class_details["class_name"] + template["ext"])
resource_file.parent.mkdir(exist_ok=True)
return resource_file

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ Generated from the CGMES files via cimgen: https://github.com/sogno-platform/cim
"""

from functools import cached_property
from typing import Optional

from pydantic import Field
from pydantic.dataclasses import dataclass
Expand Down Expand Up @@ -35,16 +34,17 @@ class {{class_name}}({{subclass_of}}):
{{/attr_origin}}
],
"is_used": {{#is_used}}True{{/is_used}}{{^is_used}}False{{/is_used}},
"namespace": "{{attribute_namespace}}", # NOSONAR
"is_class_attribute": {{#is_class_attribute}}True{{/is_class_attribute}}{{^is_class_attribute}}False{{/is_class_attribute}},
"is_datatype_attribute": {{#is_datatype_attribute}}True{{/is_datatype_attribute}}{{^is_datatype_attribute}}False{{/is_datatype_attribute}},
"is_enum_attribute": {{#is_enum_attribute}}True{{/is_enum_attribute}}{{^is_enum_attribute}}False{{/is_enum_attribute}},
"is_list_attribute": {{#is_list_attribute}}True{{/is_list_attribute}}{{^is_list_attribute}}False{{/is_list_attribute}},
"is_primitive_attribute": {{#is_primitive_attribute}}True{{/is_primitive_attribute}}{{^is_primitive_attribute}}False{{/is_primitive_attribute}},
{{#is_datatype_attribute}}
"attribute_class": {{attribute_class}},
"attribute_class": "{{attribute_class}}",
{{/is_datatype_attribute}}
{{#is_primitive_attribute}}
"attribute_class": {{attribute_class}},
"attribute_class": "{{attribute_class}}",
{{/is_primitive_attribute}}
},
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
Generated from the CGMES files via cimgen: https://github.com/sogno-platform/cimgen
"""

from ..utils.datatypes import CIMDatatype
from ..utils.profile import Profile
from ...utils.datatypes import CIMDatatype
from ...utils.profile import Profile
{{#is_fixed_imports}}
from .{{.}} import {{.}}
{{/is_fixed_imports}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ Generated from the CGMES files via cimgen: https://github.com/sogno-platform/cim
"""

from datetime import date, datetime, time
from ..utils.datatypes import Primitive
from ..utils.profile import Profile
from ...utils.datatypes import Primitive
from ...utils.profile import Profile

{{class_name}} = Primitive(
name="{{class_name}}",
Expand Down
Loading
Loading