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

Moderpython simplification + Attribute NS #21

Merged
merged 6 commits into from
Nov 15, 2023
Merged
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
2 changes: 1 addition & 1 deletion CIMgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def _write_python_files(elem_dict, langPack, outputPath, version):

class_details = {
"attributes": _find_multiple_attributes(elem_dict[class_name].attributes()),
"ClassLocation": langPack.get_class_location(class_name, elem_dict, outputPath),
"class_location": langPack.get_class_location(class_name, elem_dict, outputPath),
"class_name": class_name,
"class_origin": elem_dict[class_name].origins(),
"instances": elem_dict[class_name].instances(),
Expand Down
105 changes: 46 additions & 59 deletions modernpython/langPack.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import glob
import logging
import os
import re
import sys
import textwrap
from distutils.dir_util import copy_tree
from pathlib import Path

import chevron
Expand All @@ -16,15 +14,19 @@
# cgmes_profile_info details which uri belongs in each profile.
# We don't use that here because we aren't creating the header
# data for the separate profiles.
def setup(version_path, cgmes_profile_info): # NOSONAR
if not os.path.exists(version_path):
os.makedirs(version_path)
_create_init(version_path)
_create_base(version_path)
def setup(version_path, cgmes_profile_info): # NOSONAR
# version_path is actually the output_path

# Add all hardcoded utils and create parent dir
source_dir=Path(__file__).parent/"utils"
dest_dir=Path(version_path)/"utils"

copy_tree(str(source_dir), str(dest_dir))



def location(version):
return "cimpy." + version + ".Base"
return "..utils.base"


base = {"base_class": "Base", "class_location": location}
Expand All @@ -33,14 +35,7 @@ def location(version):


def get_class_location(class_name, class_map, version):
# Check if the current class has a parent class
if class_map[class_name].superClass():
if class_map[class_name].superClass() in class_map:
return "cimpy." + version + "." + class_map[class_name].superClass()
elif class_map[class_name].superClass() == "Base" or class_map[class_name].superClass() == None:
return location(version)
else:
return location(version)
return f".{class_map[class_name].superClass()}"


partials = {}
Expand Down Expand Up @@ -90,9 +85,14 @@ def set_float_classes(new_float_classes):

def run_template(version_path, class_details):
for template_info in template_files:
class_file = os.path.join(version_path, class_details["class_name"] + template_info["ext"])
if not os.path.exists(class_file):
with open(class_file, "w", encoding="utf-8") as file:

resource_file = Path(os.path.join(version_path, "resources", class_details["class_name"] + template_info["ext"]))
if not resource_file.exists() :
if not (parent:=resource_file.parent).exists():
parent.mkdir()

with open(resource_file, "w", encoding="utf-8") as file:

template_path = os.path.join(os.getcwd(), "modernpython/templates", template_info["filename"])
class_details["setDefault"] = _set_default
class_details["setType"] = _set_type
Expand All @@ -106,51 +106,38 @@ def run_template(version_path, class_details):
file.write(output)


def _create_init(path):
init_file = path + "/__init__.py"

with open(init_file, "w", encoding="utf-8") as init:
init.write("# pylint: disable=too-many-lines,missing-module-docstring\n")


# creates the Base class file, all classes inherit from this class
def _create_base(path):
# TODO: Check export priority of OP en SC, see Profile class
base_path = path + "/Base.py"
with open(Path(__file__).parent / "Base.py", encoding="utf-8") as src, open(
base_path, "w", encoding="utf-8"
) as dst:
dst.write(src.read())


def resolve_headers(dest: str, version: str):
"""Add all classes in __init__.py"""
if match := re.search(r"(?P<num>\d+_\d+_\d+)", version): # NOSONAR

if match := re.search(r"(?P<num>\d+_\d+_\d+)", version): # NOSONAR
version_number = match.group("num").replace("_", ".")
else:
raise ValueError(f"Cannot parse {version} to extract a number.")

dest = Path(dest)
dest = Path(dest)/"resources"
with open(dest / "__init__.py", "a", encoding="utf-8") as header_file:
_all = []
for include_name in sorted(dest.glob("*.py")):
stem = include_name.stem
if stem == "__init__":
continue
_all.append(stem)
header_file.write(f"from .{stem} import {stem}\n")

header_file.write("# pylint: disable=too-many-lines,missing-module-docstring\n")
header_file.write(f"CGMES_VERSION='{version_number}'\n")
_all.append("CGMES_VERSION")

header_file.write(
"\n".join(
[
"# This is not needed per se, but by referencing all imports",
"# this prevents a potential autoflake from cleaning up the whole file.",
"# FYA, if __all__ is present, only what's in there will be import with a import *",
"",
]
)
)
header_file.write(f"__all__={_all}")

# # Under this, add all imports in init. Disabled becasue loading 600 unneeded classes is slow.
# _all = ["CGMES_VERSION"]

# for include_name in sorted(dest.glob("*.py")):
# stem = include_name.stem
# if stem in[ "__init__", "Base"]:
# continue
# _all.append(stem)
# header_file.write(f"from .{stem} import {stem}\n")

# header_file.write(
# "\n".join(
# [
# "# This is not needed per se, but by referencing all imports",
# "# this prevents a potential autoflake from cleaning up the whole file.",
# "# FYA, if __all__ is present, only what's in there will be import with a import *",
# "",
# ]
# )
# )
# header_file.write(f"__all__={_all}")
8 changes: 5 additions & 3 deletions modernpython/templates/cimpy_class_template.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ from functools import cached_property
from typing import Optional
from pydantic import Field
from pydantic.dataclasses import dataclass
from .Base import DataclassConfig, Profile
from .{{sub_class_of}} import {{sub_class_of}}
from ..utils.dataclassconfig import DataclassConfig
from ..utils.profile import BaseProfile, Profile

from {{class_location}} import {{sub_class_of}}

@dataclass(config=DataclassConfig)
class {{class_name}}({{sub_class_of}}):
Expand All @@ -31,7 +33,7 @@ class {{class_name}}({{sub_class_of}}):


@cached_property
def possible_profiles(self)->set[Profile]:
def possible_profiles(self)->set[BaseProfile]:
"""
A resource can be used by multiple profiles. This is the set of profiles
where this element can be found.
Expand Down
Empty file added modernpython/utils/__init__.py
Empty file.
Loading