Merge pull request 'cpl g <schematic> customizable (#137)' (#138) from #137 into 2022.12

Reviewed-on: #138
Closes #137
This commit is contained in:
Sven Heidemann 2022-12-05 20:34:45 +01:00
commit 6b8491eea2
37 changed files with 504 additions and 601 deletions

View File

View File

@ -0,0 +1,30 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class ABC(GenerateSchematicABC):
def __init__(self, *args):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
from abc import ABC, abstractmethod
class $Name(ABC):
@abstractmethod
def __init__(self): pass
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'abc',
['a', 'A']
)

View File

@ -0,0 +1,28 @@
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
from cpl_core.utils import String
class Class(GenerateSchematicABC):
def __init__(self, name: str, path: str, schematic: str):
GenerateSchematicABC.__init__(self, name, path, schematic)
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}'
def get_code(self) -> str:
code = """\
class $Name:
def __init__(self):
pass
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'class',
['c', 'C']
)

View File

@ -0,0 +1,46 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class ConfigModel(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
import traceback
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.console import Console
class $Name(ConfigurationModelABC):
def __init__(self):
ConfigurationModelABC.__init__(self)
self._atr = ''
@property
def atr(self) -> str:
return self._atr
def from_dict(self, settings: dict):
try:
self._atr = settings['atr']
except Exception as e:
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings')
Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}')
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'settings',
['st', 'ST']
)

View File

@ -0,0 +1,29 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Enum(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
from enum import Enum
class $Name(Enum):
atr = 0
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'enum',
['e', 'E']
)

View File

@ -0,0 +1,25 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Init(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
self._name = f'__init__.py'
def get_code(self) -> str:
code = """\
# imports
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'init',
[]
)

View File

@ -0,0 +1,32 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Pipe(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
from cpl_core.pipes.pipe_abc import PipeABC
class $Name(PipeABC):
def __init__(self): pass
def transform(self, value: any, *args):
return value
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'pipe',
['p', 'P']
)

View File

@ -0,0 +1,27 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Service(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
class $Name:
def __init__(self):
pass
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'service',
['s', 'S']
)

View File

@ -0,0 +1,33 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class TestCase(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
import unittest
class $Name(unittest.TestCase):
def setUp(self):
pass
def test_equal(self):
pass
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'test-case',
['tc', 'TC']
)

View File

@ -0,0 +1,33 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Thread(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
import threading
class $Name(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self) -> None:
pass
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'thread',
['t', 'T']
)

View File

@ -0,0 +1,33 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Validator(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
from cpl_core.configuration.validator_abc import ValidatorABC
class $Name(ValidatorABC):
def __init__(self):
ValidatorABC.__init__(self)
def validate(self) -> bool:
return True
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'validator',
['v', 'V']
)

View File

@ -1,26 +0,0 @@
# -*- coding: utf-8 -*-
"""
cpl-cli sh-edraft Common Python library CLI
~~~~~~~~~~~~~~~~~~~
sh-edraft Common Python library Command Line Interface
:copyright: (c) 2020 - 2022 sh-edraft.de
:license: MIT, see LICENSE for more details.
"""
__title__ = 'cpl_cli._templates.generate'
__author__ = 'Sven Heidemann'
__license__ = 'MIT'
__copyright__ = 'Copyright (c) 2020 - 2022 sh-edraft.de'
__version__ = '2022.12.0'
from collections import namedtuple
# imports:
VersionInfo = namedtuple('VersionInfo', 'major minor micro')
version_info = VersionInfo(major='2022', minor='12', micro='0')

View File

@ -1,44 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ABCTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
from abc import ABC, abstractmethod
class $Name(ABC):
@abstractmethod
def __init__(self): pass
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,35 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ClassTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
class $Name:
def __init__(self):
pass
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,60 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ConfigModelTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
import traceback
from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC
from cpl_core.console import Console
class $Name(ConfigurationModelABC):
def __init__(self):
ConfigurationModelABC.__init__(self)
self._atr = ''
@property
def atr(self) -> str:
return self._atr
def from_dict(self, settings: dict):
try:
self._atr = settings['atr']
except Exception as e:
Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {type(self).__name__} settings')
Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}')
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,43 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class EnumTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
from enum import Enum
class $Name(Enum):
atr = 0
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,35 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class InitTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'__init__.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
# imports
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,46 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class PipeTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
from cpl_core.pipes.pipe_abc import PipeABC
class $Name(PipeABC):
def __init__(self): pass
def transform(self, value: any, *args):
return value
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,41 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ServiceTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
class $Name:
def __init__(self):
pass
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,47 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class TestCaseTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
import unittest
class $Name(unittest.TestCase):
def setUp(self):
pass
def test_equal(self):
pass
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,47 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ThreadTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
import threading
class $Name(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self) -> None:
pass
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -1,47 +0,0 @@
import textwrap
from string import Template
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ValidatorTemplate(TemplateFileABC):
def __init__(self, name: str, schematic: str, schematic_upper: str, path: str):
TemplateFileABC.__init__(self)
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{schematic_upper}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
self._path = path
self._value = textwrap.dedent("""\
from cpl_core.configuration.validator_abc import ValidatorABC
class $Name(ValidatorABC):
def __init__(self):
ValidatorABC.__init__(self)
def validate(self) -> bool:
return True
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return Template(self._value).substitute(
Name=self._class_name
)

View File

@ -0,0 +1 @@
# imports

View File

@ -0,0 +1,28 @@
from abc import ABC, abstractmethod
from cpl_core.utils import String
class FileTemplateABC(ABC):
@abstractmethod
def __init__(self, name: str, path: str, code: str):
self._name = f'{String.convert_to_snake_case(name)}.py'
self._path = path
self._code = code
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self.get_code()
@abstractmethod
def get_code(self) -> str:
return self._code

View File

@ -0,0 +1,37 @@
import textwrap
from abc import abstractmethod
from string import Template
from cpl_cli.abc.file_template_abc import FileTemplateABC
from cpl_cli.configuration.schematic_collection import SchematicCollection
from cpl_core.utils import String
class GenerateSchematicABC(FileTemplateABC):
def __init__(self, name: str, schematic: str, path: str):
FileTemplateABC.__init__(self, name, path, '')
self._name = f'{String.convert_to_snake_case(name)}_{schematic}.py'
if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{String.first_to_upper(schematic)}'
if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}'
@property
def class_name(self) -> str:
return self._class_name
@abstractmethod
def get_code(self) -> str: pass
@classmethod
def build_code_str(cls, code: str, **kwargs) -> str:
text = textwrap.dedent(code)
return Template(text).substitute(**kwargs)
@classmethod
@abstractmethod
def register(cls, *args):
SchematicCollection.register(*args)

View File

@ -2,19 +2,10 @@ import os
import sys import sys
import textwrap import textwrap
from cpl_cli._templates.generate.abc_template import ABCTemplate from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
from cpl_cli._templates.generate.class_template import ClassTemplate
from cpl_cli._templates.generate.configmodel_template import ConfigModelTemplate
from cpl_cli._templates.generate.enum_template import EnumTemplate
from cpl_cli._templates.generate.init_template import InitTemplate
from cpl_cli._templates.generate.pipe_template import PipeTemplate
from cpl_cli._templates.generate.service_template import ServiceTemplate
from cpl_cli._templates.generate.test_case_template import TestCaseTemplate
from cpl_cli._templates.generate.thread_template import ThreadTemplate
from cpl_cli._templates.generate.validator_template import ValidatorTemplate
from cpl_cli._templates.template_file_abc import TemplateFileABC
from cpl_cli.command_abc import CommandABC from cpl_cli.command_abc import CommandABC
from cpl_cli.configuration import WorkspaceSettings from cpl_cli.configuration import WorkspaceSettings
from cpl_cli.configuration.schematic_collection import SchematicCollection
from cpl_core.configuration.configuration_abc import ConfigurationABC from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.console import Console from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum from cpl_core.console.foreground_color_enum import ForegroundColorEnum
@ -37,51 +28,28 @@ class GenerateService(CommandABC):
self._config = configuration self._config = configuration
self._workspace = workspace self._workspace = workspace
self._schematics = {
"abc": {
"Upper": "ABC",
"Template": ABCTemplate
},
"class": {
"Upper": "Class",
"Template": ClassTemplate
},
"enum": {
"Upper": "Enum",
"Template": EnumTemplate
},
"pipe": {
"Upper": "Pipe",
"Template": PipeTemplate
},
"service": {
"Upper": "Service",
"Template": ServiceTemplate
},
"settings": {
"Upper": "Settings",
"Template": ConfigModelTemplate
},
"test_case": {
"Upper": "TestCase",
"Template": TestCaseTemplate
},
"thread": {
"Upper": "Thread",
"Template": ThreadTemplate
},
"validator": {
"Upper": "Validator",
"Template": ValidatorTemplate
}
}
self._config = configuration self._config = configuration
self._env = self._config.environment self._env = self._config.environment
self._schematics = {}
self._read_custom_schematics_from_path(self._env.runtime_directory)
self._read_custom_schematics_from_path(self._env.working_directory)
for schematic in GenerateSchematicABC.__subclasses__():
schematic.register()
self._schematics = SchematicCollection.get_schematics()
@property @property
def help_message(self) -> str: def help_message(self) -> str:
return textwrap.dedent("""\ schematics = []
for schematic in self._schematics:
aliases = '|'.join(self._schematics[schematic]['Aliases'])
schematic_str = schematic
if len(aliases) > 0:
schematic_str = f'{schematic} ({aliases})'
schematics.append(schematic_str)
help_msg = textwrap.dedent("""\
Generate a file based on schematic. Generate a file based on schematic.
Usage: cpl generate <schematic> <name> Usage: cpl generate <schematic> <name>
@ -89,41 +57,11 @@ class GenerateService(CommandABC):
schematic: The schematic to generate. schematic: The schematic to generate.
name: The name of the generated file name: The name of the generated file
Schematics: Schematics:""")
abc
class
enum
pipe
service
settings
test_case
thread
validator
""")
@staticmethod for schematic in schematics:
def _help(message: str): help_msg += f'\n {schematic}'
""" return help_msg
Internal help output
:param message:
:return:
"""
Console.error(message)
schematics = [
'abc (a|A)',
'class (c|C)',
'enum (e|E)',
'pipe (p|P)',
'service (s|S)',
'settings (st|ST)',
'test-case (tc|TC)',
'thread (t|T)',
'validator (v|V)'
]
Console.write_line('Available Schematics:')
for name in schematics:
Console.write(f'\n\t{name} ')
@staticmethod @staticmethod
def _create_file(file_path: str, value: str): def _create_file(file_path: str, value: str):
@ -137,7 +75,7 @@ class GenerateService(CommandABC):
template.write(value) template.write(value)
template.close() template.close()
def _create_init_files(self, file_path: str, template: TemplateFileABC, class_name: str, schematic: str, rel_path: str): def _create_init_files(self, file_path: str, template: GenerateSchematicABC, class_name: str, schematic: str, rel_path: str):
if not os.path.isdir(os.path.dirname(file_path)): if not os.path.isdir(os.path.dirname(file_path)):
os.makedirs(os.path.dirname(file_path)) os.makedirs(os.path.dirname(file_path))
directory = '' directory = ''
@ -146,7 +84,7 @@ class GenerateService(CommandABC):
if subdir == 'src': if subdir == 'src':
continue continue
file = InitTemplate(class_name, schematic, self._schematics[schematic]["Upper"], rel_path) file = self._schematics['init']['Template'](class_name, 'init', rel_path)
if os.path.exists(os.path.join(os.path.abspath(directory), file.name)): if os.path.exists(os.path.join(os.path.abspath(directory), file.name)):
continue continue
@ -154,12 +92,12 @@ class GenerateService(CommandABC):
f'Creating {os.path.abspath(directory)}/{file.name}', f'Creating {os.path.abspath(directory)}/{file.name}',
self._create_file, self._create_file,
os.path.join(os.path.abspath(directory), file.name), os.path.join(os.path.abspath(directory), file.name),
file.value, file.get_code(),
text_foreground_color=ForegroundColorEnum.green, text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan spinner_foreground_color=ForegroundColorEnum.cyan
) )
def _generate(self, schematic: str, name: str, template: TemplateFileABC): def _generate(self, schematic: str, name: str, template: type):
""" """
Generates files by given schematic, name and template Generates files by given schematic, name and template
:param schematic: :param schematic:
@ -175,9 +113,9 @@ class GenerateService(CommandABC):
class_name = parts[len(parts) - 1] class_name = parts[len(parts) - 1]
if self._workspace is not None and parts[0] in self._workspace.projects: if self._workspace is not None and parts[0] in self._workspace.projects:
rel_path = os.path.dirname(self._workspace.projects[parts[0]]) rel_path = os.path.join(os.path.dirname(self._workspace.projects[parts[0]]), *parts[1:-1])
template = template(class_name, schematic, self._schematics[schematic]["Upper"], rel_path) template = template(class_name, String.convert_to_snake_case(schematic), rel_path)
file_path = os.path.join(self._env.working_directory, template.path, template.name) file_path = os.path.join(self._env.working_directory, template.path, template.name)
self._create_init_files(file_path, template, class_name, schematic, rel_path) self._create_init_files(file_path, template, class_name, schematic, rel_path)
@ -194,11 +132,35 @@ class GenerateService(CommandABC):
message, message,
self._create_file, self._create_file,
file_path, file_path,
template.value, template.get_code(),
text_foreground_color=ForegroundColorEnum.green, text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan spinner_foreground_color=ForegroundColorEnum.cyan
) )
@staticmethod
def _read_custom_schematics_from_path(path: str):
if not os.path.exists(os.path.join(path, '.cpl')):
return
for r, d, f in os.walk(os.path.join(path, '.cpl')):
for file in f:
if not file.endswith('_schematic.py'):
continue
code = ''
with open(os.path.join(r, file), 'r') as py_file:
code = py_file.read()
py_file.close()
exec(code)
def _get_schematic_by_alias(self, schematic: str) -> str:
for key in self._schematics:
if schematic in self._schematics[key]['Aliases']:
return key
return schematic
def execute(self, args: list[str]): def execute(self, args: list[str]):
""" """
Entry point of command Entry point of command
@ -213,9 +175,15 @@ class GenerateService(CommandABC):
schematic = s schematic = s
break break
schematic_by_alias = self._get_schematic_by_alias(args[0])
if schematic is None and len(args) >= 1 and (args[0] in self._schematics or schematic_by_alias != args[0]):
schematic = schematic_by_alias
self._config.add_configuration(schematic, args[1])
value = args[1]
if schematic is None: if schematic is None:
self._help('Usage: cpl generate <schematic> [options]') Console.error(f'Schematic not found')
Console.write_line() Console.write_line(self.help_message)
sys.exit() sys.exit()
name = value name = value

View File

@ -67,29 +67,11 @@ class NewService(CommandABC):
name Name of the workspace or the project name Name of the workspace or the project
Types: Types:
console console (c|C)
library library (l|L)
unittest unittest (ut|UT)
""") """)
@staticmethod
def _help(message: str):
"""
Internal help output
:param message:
:return:
"""
Console.error(message)
schematics = [
'console (c|C) <name>',
'library (l|L) <name>',
'unittest (ut|UT) <name>',
]
Console.write_line('Available Schematics:')
for name in schematics:
Console.write(f'\n\t{name} ')
def _create_project_settings(self): def _create_project_settings(self):
self._rel_path = os.path.dirname(self._name) self._rel_path = os.path.dirname(self._name)
self._project_dict = { self._project_dict = {
@ -369,5 +351,6 @@ class NewService(CommandABC):
self._create_venv() self._create_venv()
else: else:
self._help('Usage: cpl new <schematic> [options]') Console.error(f'Project type not found')
Console.write_line(self.help_message)
return return

View File

@ -0,0 +1,16 @@
from cpl_core.utils import String
class SchematicCollection:
_schematics: dict = {}
@classmethod
def register(cls, template: type, schematic: str, aliases: list[str]):
cls._schematics[schematic] = {
"Template": template,
"Aliases": aliases
}
@classmethod
def get_schematics(cls) -> dict:
return cls._schematics

View File

@ -29,16 +29,7 @@ class StartupArgumentExtension(StartupExtensionABC):
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'add', ['a', 'A'], AddService, True, validators=[WorkspaceValidator]) \ config.create_console_argument(ArgumentTypeEnum.Executable, '', 'add', ['a', 'A'], AddService, True, validators=[WorkspaceValidator]) \
.add_console_argument(ArgumentTypeEnum.Flag, '--', 'simulate', ['s', 'S']) .add_console_argument(ArgumentTypeEnum.Flag, '--', 'simulate', ['s', 'S'])
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'build', ['b', 'B'], BuildService, True, validators=[ProjectValidator]) config.create_console_argument(ArgumentTypeEnum.Executable, '', 'build', ['b', 'B'], BuildService, True, validators=[ProjectValidator])
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'generate', ['g', 'G'], GenerateService, True) \ config.create_console_argument(ArgumentTypeEnum.Executable, '', 'generate', ['g', 'G'], GenerateService, True)
.add_console_argument(ArgumentTypeEnum.Variable, '', 'abc', ['a', 'A'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'class', ['c', 'C'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'enum', ['e', 'E'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'pipe', ['p', 'P'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'service', ['s', 'S'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'settings', ['st', 'ST'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'test_case', ['tc', 'TC'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'thread', ['t', 'T'], ' ') \
.add_console_argument(ArgumentTypeEnum.Variable, '', 'validator', ['v', 'V'], ' ')
config.create_console_argument(ArgumentTypeEnum.Executable, '', 'install', ['i', 'I'], InstallService, True, validators=[ProjectValidator]) \ config.create_console_argument(ArgumentTypeEnum.Executable, '', 'install', ['i', 'I'], InstallService, True, validators=[ProjectValidator]) \
.add_console_argument(ArgumentTypeEnum.Flag, '--', 'dev', ['d', 'D']) \ .add_console_argument(ArgumentTypeEnum.Flag, '--', 'dev', ['d', 'D']) \
.add_console_argument(ArgumentTypeEnum.Flag, '--', 'virtual', ['v', 'V']) \ .add_console_argument(ArgumentTypeEnum.Flag, '--', 'virtual', ['v', 'V']) \

1
src/cpl_cli/test_enum.py Normal file
View File

@ -0,0 +1 @@
# imports

1
src/cpl_cli/test_init.py Normal file
View File

@ -0,0 +1 @@
# imports

View File

@ -7,4 +7,4 @@ class ArgumentExecutableABC(ABC):
def __init__(self): pass def __init__(self): pass
@abstractmethod @abstractmethod
def execute(self, args: list[str]): pass def run(self, args: list[str]): pass

View File

@ -341,7 +341,7 @@ class Configuration(ConfigurationABC):
continue continue
self._additional_arguments.append(arg) self._additional_arguments.append(arg)
cmd.execute(self._additional_arguments) cmd.run(self._additional_arguments)
self._handle_pre_or_post_executables(False, exe, services) self._handle_pre_or_post_executables(False, exe, services)
prevent = exe.prevent_next_executable prevent = exe.prevent_next_executable
success = True success = True

View File

@ -0,0 +1,27 @@
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
class Custom(GenerateSchematicABC):
def __init__(self, *args: str):
GenerateSchematicABC.__init__(self, *args)
def get_code(self) -> str:
code = """\
class $Name:
def __init__(self):
print('hello')
"""
x = self.build_code_str(code, Name=self._class_name)
return x
@classmethod
def register(cls):
GenerateSchematicABC.register(
cls,
'custom',
['cm', 'CM']
)

View File

@ -0,0 +1 @@
# imports

View File

@ -0,0 +1,4 @@
class Custom:
def __init__(self):
print('hello')

View File

@ -78,8 +78,8 @@ class GenerateTestCase(CommandTestCase):
self._test_file_with_project('settings', '_settings', path=self._project) self._test_file_with_project('settings', '_settings', path=self._project)
def test_test_case(self): def test_test_case(self):
self._test_file('test_case', '_test_case') self._test_file('test-case', '_test_case')
self._test_file_with_project('test_case', '_test_case', path=self._project) self._test_file_with_project('test-case', '_test_case', path=self._project)
def test_thread(self): def test_thread(self):
self._test_file('thread', '_thread') self._test_file('thread', '_thread')