cpl n <project-type> name (#139) #140

Merged
edraft merged 6 commits from #139 into 2022.12 2022-12-07 16:16:14 +01:00
71 changed files with 726 additions and 2252 deletions

View File

@ -0,0 +1,49 @@
import os
from cpl_cli.abc.project_type_abc import ProjectTypeABC
from cpl_cli.configuration import WorkspaceSettings
from cpl_core.utils import String
class Console(ProjectTypeABC):
def __init__(
self,
base_path: str,
project_name: str,
workspace: WorkspaceSettings,
use_application_api: bool,
use_startup: bool,
use_service_providing: bool,
use_async: bool,
project_file_data: dict,
):
from project_file import ProjectFile
from project_file_appsettings import ProjectFileAppsettings
from project_file_code_application import ProjectFileApplication
from project_file_code_main import ProjectFileMain
from project_file_code_startup import ProjectFileStartup
from project_file_readme import ProjectFileReadme
from project_file_license import ProjectFileLicense
from schematic_init import Init
ProjectTypeABC.__init__(self, base_path, project_name, workspace, use_application_api, use_startup, use_service_providing, use_async, project_file_data)
project_path = f'{base_path}{String.convert_to_snake_case(project_name.split("/")[-1])}/'
self.add_template(ProjectFile(project_name.split('/')[-1], project_path, project_file_data))
if workspace is None:
self.add_template(ProjectFileLicense(''))
self.add_template(ProjectFileReadme(''))
self.add_template(Init('', 'init', f'{base_path}tests/'))
self.add_template(Init('', 'init', project_path))
self.add_template(ProjectFileAppsettings(project_path))
if use_application_api:
self.add_template(ProjectFileApplication(project_path, use_application_api, use_startup, use_service_providing, use_async))
if use_startup:
self.add_template(ProjectFileStartup(project_path, use_application_api, use_startup, use_service_providing, use_async))
self.add_template(ProjectFileMain(project_name.split('/')[-1], project_path, use_application_api, use_startup, use_service_providing, use_async))

View File

@ -0,0 +1,14 @@
import json
from cpl_cli.abc.file_template_abc import FileTemplateABC
class ProjectFile(FileTemplateABC):
def __init__(self, name: str, path: str, code: dict):
FileTemplateABC.__init__(self, '', path, '{}')
self._name = f'{name}.json'
self._code = code
def get_code(self) -> str:
return json.dumps(self._code, indent=2)

View File

@ -0,0 +1,11 @@
from cpl_cli.abc.file_template_abc import FileTemplateABC
class ProjectFileAppsettings(FileTemplateABC):
def __init__(self, path: str):
FileTemplateABC.__init__(self, '', path, '{}')
self._name = 'appsettings.json'
def get_code(self) -> str:
return self._code

View File

@ -0,0 +1,49 @@
from cpl_cli.abc.code_file_template_abc import CodeFileTemplateABC
class ProjectFileApplication(CodeFileTemplateABC):
def __init__(self, path: str, use_application_api: bool, use_startup: bool, use_service_providing: bool, use_async: bool):
CodeFileTemplateABC.__init__(self, 'application', path, '', use_application_api, use_startup, use_service_providing, use_async)
def get_code(self) -> str:
import textwrap
if self._use_async:
return textwrap.dedent("""\
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceProviderABC
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
async def configure(self):
pass
async def main(self):
Console.write_line('Hello World')
""")
return textwrap.dedent("""\
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceProviderABC
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
def configure(self):
pass
def main(self):
Console.write_line('Hello World')
""")

View File

@ -0,0 +1,92 @@
from cpl_cli.abc.code_file_template_abc import CodeFileTemplateABC
from cpl_core.utils import String
class ProjectFileMain(CodeFileTemplateABC):
def __init__(self, name: str, path: str, use_application_api: bool, use_startup: bool, use_service_providing: bool, use_async: bool):
CodeFileTemplateABC.__init__(self, 'main', path, '', use_application_api, use_startup, use_service_providing, use_async)
import textwrap
import_pkg = f'{String.convert_to_snake_case(name)}.'
self._main_with_application_host_and_startup = textwrap.dedent(f"""\
{"import asyncio" if self._use_async else ''}
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
from {import_pkg}startup import Startup
{self._async()}def main():
app_builder = ApplicationBuilder(Application)
app_builder.use_startup(Startup)
{"app: Application = await app_builder.build_async()" if self._use_async else ""}
{"await app.run_async()" if self._use_async else "app_builder.build().run()"}
if __name__ == '__main__':
{"asyncio.run(main())" if self._use_async else "main()"}
""")
self._main_with_application_base = textwrap.dedent(f"""\
{"import asyncio" if self._use_async else ''}
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
{self._async()}def main():
app_builder = ApplicationBuilder(Application)
{"app: Application = await app_builder.build_async()" if self._use_async else ""}
{"await app.run_async()" if self._use_async else "app_builder.build().run()"}
if __name__ == '__main__':
{"asyncio.run(main())" if self._use_async else "main()"}
""")
self._main_with_dependency_injection = textwrap.dedent(f"""\
{"import asyncio" if self._use_async else ''}
from cpl_core.application import ApplicationBuilder
{self._async()}def configure_configuration() -> ConfigurationABC:
config = Configuration()
return config
{self._async()}def configure_services(config: ConfigurationABC) -> ServiceProviderABC:
services = ServiceCollection(config)
return services.build_service_provider()
{self._async()}def main():
config = {self._async()}configure_configuration()
provider = {self._async()}configure_services(config)
Console.write_line('Hello World')
if __name__ == '__main__':
{"asyncio.run(main())" if self._use_async else "main()"}
""")
def _async(self) -> str:
if self._use_async:
return 'async '
return ''
def get_code(self) -> str:
if self._use_application_api and self._use_startup:
return self._main_with_application_host_and_startup
if self._use_application_api:
return self._main_with_application_base
if self._use_service_providing:
return self._main_with_dependency_injection
return self._main_with_application_base

View File

@ -0,0 +1,29 @@
from cpl_cli.abc.code_file_template_abc import CodeFileTemplateABC
class ProjectFileStartup(CodeFileTemplateABC):
def __init__(self, path: str, use_application_api: bool, use_startup: bool, use_service_providing: bool, use_async: bool):
CodeFileTemplateABC.__init__(self, 'startup', path, '', use_application_api, use_startup, use_service_providing, use_async)
def get_code(self) -> str:
import textwrap
return textwrap.dedent("""\
from cpl_core.application import StartupABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC, ServiceCollectionABC
from cpl_core.environment import ApplicationEnvironment
class Startup(StartupABC):
def __init__(self):
StartupABC.__init__(self)
def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironment) -> ConfigurationABC:
return configuration
def configure_services(self, services: ServiceCollectionABC, environment: ApplicationEnvironment) -> ServiceProviderABC:
return services.build_service_provider()
""")

View File

@ -0,0 +1,59 @@
from cpl_cli.abc.code_file_template_abc import CodeFileTemplateABC
class ProjectFileTestApplication(CodeFileTemplateABC):
def __init__(self, path: str, use_application_api: bool, use_startup: bool, use_service_providing: bool, use_async: bool):
CodeFileTemplateABC.__init__(self, 'application', path, '', use_application_api, use_startup, use_service_providing, use_async)
def get_code(self) -> str:
import textwrap
if self._use_async:
return textwrap.dedent("""\
import unittest
from unittest import TestSuite
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from unittests.test_case import TestCase
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
self._suite: TestSuite = unittest.TestSuite()
async def configure(self):
self._suite.addTest(TestCase('test_equal'))
async def main(self):
runner = unittest.TextTestRunner()
runner.run(self._suite)
""")
return textwrap.dedent("""\
import unittest
from unittest import TestSuite
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from unittests.test_case import TestCase
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
self._suite: TestSuite = unittest.TestSuite()
def configure(self):
self._suite.addTest(TestCase('test_equal'))
def main(self):
runner = unittest.TextTestRunner()
runner.run(self._suite)
""")

View File

@ -0,0 +1,37 @@
from cpl_cli.abc.code_file_template_abc import CodeFileTemplateABC
class ProjectFileTestCase(CodeFileTemplateABC):
def __init__(self, path: str, use_application_api: bool, use_startup: bool, use_service_providing: bool, use_async: bool):
CodeFileTemplateABC.__init__(self, 'test_case', path, '', use_application_api, use_startup, use_service_providing, use_async)
def get_code(self) -> str:
import textwrap
if self._use_async:
return textwrap.dedent("""\
import unittest
class TestCase(unittest.TestCase):
async def setUp(self) -> None:
pass
async def test_equal(self):
self.assertEqual(True, True)
""")
return textwrap.dedent("""\
import unittest
class TestCase(unittest.TestCase):
def setUp(self) -> None:
pass
def test_equal(self):
self.assertEqual(True, True)
""")

View File

@ -0,0 +1,11 @@
from cpl_cli.abc.file_template_abc import FileTemplateABC
class ProjectFileLicense(FileTemplateABC):
def __init__(self, path: str):
FileTemplateABC.__init__(self, '', path, '')
self._name = 'LICENSE'
def get_code(self) -> str:
return self._code

View File

@ -0,0 +1,11 @@
from cpl_cli.abc.file_template_abc import FileTemplateABC
class ProjectFileReadme(FileTemplateABC):
def __init__(self, path: str):
FileTemplateABC.__init__(self, '', path, '')
self._name = 'README.md'
def get_code(self) -> str:
return self._code

View File

@ -0,0 +1,49 @@
import os
from cpl_cli.abc.project_type_abc import ProjectTypeABC
from cpl_cli.configuration import WorkspaceSettings
from cpl_core.utils import String
class Library(ProjectTypeABC):
def __init__(
self,
base_path: str,
project_name: str,
workspace: WorkspaceSettings,
use_application_api: bool,
use_startup: bool,
use_service_providing: bool,
use_async: bool,
project_file_data: dict,
):
from project_file import ProjectFile
from project_file_appsettings import ProjectFileAppsettings
from project_file_code_application import ProjectFileApplication
from project_file_code_main import ProjectFileMain
from project_file_code_startup import ProjectFileStartup
from project_file_readme import ProjectFileReadme
from project_file_license import ProjectFileLicense
from schematic_init import Init
ProjectTypeABC.__init__(self, base_path, project_name, workspace, use_application_api, use_startup, use_service_providing, use_async, project_file_data)
project_path = f'{base_path}{String.convert_to_snake_case(project_name.split("/")[-1])}/'
self.add_template(ProjectFile(project_name.split('/')[-1], project_path, project_file_data))
if workspace is None:
self.add_template(ProjectFileLicense(''))
self.add_template(ProjectFileReadme(''))
self.add_template(Init('', 'init', f'{base_path}tests/'))
self.add_template(Init('', 'init', project_path))
self.add_template(ProjectFileAppsettings(project_path))
if use_application_api:
self.add_template(ProjectFileApplication(project_path, use_application_api, use_startup, use_service_providing, use_async))
if use_startup:
self.add_template(ProjectFileStartup(project_path, use_application_api, use_startup, use_service_providing, use_async))
self.add_template(ProjectFileMain(project_name.split('/')[-1], project_path, use_application_api, use_startup, use_service_providing, use_async))

View File

@ -0,0 +1,42 @@
import os
from cpl_cli.abc.project_type_abc import ProjectTypeABC
from cpl_cli.configuration import WorkspaceSettings
from cpl_core.utils import String
class Unittest(ProjectTypeABC):
def __init__(
self,
base_path: str,
project_name: str,
workspace: WorkspaceSettings,
use_application_api: bool,
use_startup: bool,
use_service_providing: bool,
use_async: bool,
project_file_data: dict,
):
from project_file import ProjectFile
from project_file_code_application import ProjectFileApplication
from project_file_code_main import ProjectFileMain
from project_file_code_test_case import ProjectFileTestCase
from project_file_readme import ProjectFileReadme
from project_file_license import ProjectFileLicense
from schematic_init import Init
ProjectTypeABC.__init__(self, base_path, project_name, workspace, use_application_api, use_startup, use_service_providing, use_async, project_file_data)
project_path = f'{base_path}{String.convert_to_snake_case(project_name.split("/")[-1])}/'
self.add_template(ProjectFile(project_name.split('/')[-1], project_path, project_file_data))
if workspace is None:
self.add_template(ProjectFileLicense(''))
self.add_template(ProjectFileReadme(''))
self.add_template(Init('', 'init', f'{base_path}tests/'))
self.add_template(Init('', 'init', project_path))
self.add_template(ProjectFileApplication(project_path, use_application_api, use_startup, use_service_providing, use_async))
self.add_template(ProjectFileMain(project_name.split('/')[-1], project_path, use_application_api, use_startup, use_service_providing, use_async))
self.add_template(ProjectFileTestCase(project_path, use_application_api, use_startup, use_service_providing, use_async))

View File

@ -1,5 +1,3 @@
import textwrap
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC

View File

@ -21,8 +21,7 @@ class TestCase(GenerateSchematicABC):
def test_equal(self): def test_equal(self):
pass pass
""" """
x = self.build_code_str(code, Name=self._class_name) return self.build_code_str(code, Name=self._class_name)
return x
@classmethod @classmethod
def register(cls): def register(cls):

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.new'
__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,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.new.console'
__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,41 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class AppsettingsTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'appsettings.json'
self._path = ''
self._value = textwrap.dedent("""\
{
"TimeFormatSettings": {
"DateFormat": "%Y-%m-%d",
"TimeFormat": "%H:%M:%S",
"DateTimeFormat": "%Y-%m-%d %H:%M:%S.%f",
"DateTimeLogFormat": "%Y-%m-%d_%H-%M-%S"
},
"LoggingSettings": {
"Path": "logs/",
"Filename": "log_$start_time.log",
"ConsoleLogLevel": "ERROR",
"FileLogLevel": "WARN"
}
}
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,23 +0,0 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class LicenseTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'LICENSE'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,23 +0,0 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ReadmeTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'README.md'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

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.new.console.source'
__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,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.new.console.source.name'
__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,64 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ApplicationTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'application.py'
self._path = path
self._use_async = use_async
if self._use_async:
self._value = textwrap.dedent("""\
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceProviderABC
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
async def configure(self):
pass
async def main(self):
Console.write_line('Hello World')
""")
else:
self._value = textwrap.dedent("""\
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceProviderABC
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
def configure(self):
pass
def main(self):
Console.write_line('Hello World')
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,27 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainInitTemplate(TemplateFileABC):
def __init__(self, name: str, path: str):
TemplateFileABC.__init__(self)
self._name = '__init__.py'
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 self._value

View File

@ -1,254 +0,0 @@
import textwrap
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainWithApplicationHostAndStartupTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
name = String.convert_to_snake_case(name)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if use_async:
self._value = textwrap.dedent(f"""\
import asyncio
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
from {import_pkg}startup import Startup
async def main():
app_builder = ApplicationBuilder(Application)
app_builder.use_startup(Startup)
app: Application = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent(f"""\
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
from {import_pkg}startup import Startup
def main():
app_builder = ApplicationBuilder(Application)
app_builder.use_startup(Startup)
app_builder.build().run()
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value
class MainWithApplicationBaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
name = String.convert_to_snake_case(name)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if use_async:
self._value = textwrap.dedent(f"""\
import asyncio
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
async def main():
app_builder = ApplicationBuilder(Application)
app: Application = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent(f"""\
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
def main():
app_builder = ApplicationBuilder(Application)
app_builder.build().run()
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value
class MainWithoutApplicationBaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
name = String.convert_to_snake_case(name)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if use_async:
self._value = textwrap.dedent("""\
import asyncio
from cpl_core.console import Console
async def main():
Console.write_line('Hello World')
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent("""\
from cpl_core.console import Console
def main():
Console.write_line('Hello World')
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value
class MainWithDependencyInjection(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
name = String.convert_to_snake_case(name)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if use_async:
self._value = textwrap.dedent("""\
import asyncio
from cpl_core.configuration import Configuration, ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceCollection, ServiceProviderABC
async def configure_configuration() -> ConfigurationABC:
config = Configuration()
return config
async def configure_services(config: ConfigurationABC) -> ServiceProviderABC:
services = ServiceCollection(config)
return services.build_service_provider()
async def main():
config = await configure_configuration()
provider = await configure_services(config)
Console.write_line('Hello World')
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent("""\
from cpl_core.configuration import Configuration, ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceCollection, ServiceProviderABC
def configure_configuration() -> ConfigurationABC:
config = Configuration()
return config
def configure_services(config: ConfigurationABC) -> ServiceProviderABC:
services = ServiceCollection(config)
return services.build_service_provider()
def main():
config = configure_configuration()
provider = configure_services(config)
Console.write_line('Hello World')
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,43 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class StartupTemplate(TemplateFileABC):
def __init__(self, name: str, path: str):
TemplateFileABC.__init__(self)
self._name = 'startup.py'
self._path = path
self._value = textwrap.dedent("""\
from cpl_core.application import StartupABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC, ServiceCollectionABC
from cpl_core.environment import ApplicationEnvironment
class Startup(StartupABC):
def __init__(self):
StartupABC.__init__(self)
def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironment) -> ConfigurationABC:
return configuration
def configure_services(self, services: ServiceCollectionABC, environment: ApplicationEnvironment) -> ServiceProviderABC:
return services.build_service_provider()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

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.new.console.source.tests'
__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,27 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class TestsInitTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = '__init__.py'
self._path = 'src/tests/'
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 self._value

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.new.library'
__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,41 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class AppsettingsTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'appsettings.json'
self._path = ''
self._value = textwrap.dedent("""\
{
"TimeFormatSettings": {
"DateFormat": "%Y-%m-%d",
"TimeFormat": "%H:%M:%S",
"DateTimeFormat": "%Y-%m-%d %H:%M:%S.%f",
"DateTimeLogFormat": "%Y-%m-%d_%H-%M-%S"
},
"LoggingSettings": {
"Path": "logs/",
"Filename": "log_$start_time.log",
"ConsoleLogLevel": "ERROR",
"FileLogLevel": "WARN"
}
}
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,23 +0,0 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class LicenseTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'LICENSE'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,23 +0,0 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ReadmeTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'README.md'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

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.new.library.source'
__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,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.new.library.source.name'
__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,63 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ApplicationTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'application.py'
self._path = path
if use_async:
self._value = textwrap.dedent("""\
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceProviderABC
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
async def configure(self):
pass
async def main(self):
Console.write_line('Hello World')
""")
else:
self._value = textwrap.dedent("""\
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceProviderABC
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
def configure(self):
pass
def main(self):
Console.write_line('Hello World')
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,27 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class NameInitTemplate(TemplateFileABC):
def __init__(self, name: str, path: str):
TemplateFileABC.__init__(self)
self._name = '__init__.py'
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 self._value

View File

@ -1,249 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainWithApplicationHostAndStartupTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if name == '':
import_pkg = ''
if use_async:
self._value = textwrap.dedent(f"""\
import asyncio
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
from {import_pkg}startup import Startup
async def main():
app_builder = ApplicationBuilder(Application)
app_builder.use_startup(Startup)
app: Application = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent(f"""\
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
from {import_pkg}startup import Startup
def main():
app_builder = ApplicationBuilder(Application)
app_builder.use_startup(Startup)
app_builder.build().run()
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value
class MainWithApplicationBaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if name == '':
import_pkg = ''
if use_async:
self._value = textwrap.dedent(f"""\
import asyncio
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
async def main():
app_builder = ApplicationBuilder(Application)
app: Application = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent(f"""\
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
def main():
app_builder = ApplicationBuilder(Application)
app_builder.build().run()
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value
class MainWithoutApplicationBaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'main.py'
self._path = path
if use_async:
self._value = textwrap.dedent("""\
import asyncio
from cpl_core.console import Console
async def main():
Console.write_line('Hello World')
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent("""\
from cpl_core.console import Console
def main():
Console.write_line('Hello World')
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value
class MainWithDependencyInjection(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'main.py'
self._path = path
if use_async:
self._value = textwrap.dedent("""\
import asyncio
from cpl_core.configuration import Configuration, ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceCollection, ServiceProviderABC
async def configure_configuration() -> ConfigurationABC:
config = Configuration()
return config
async def configure_services(config: ConfigurationABC) -> ServiceProviderABC:
services = ServiceCollection(config)
return services.build_service_provider()
async def main():
config = await configure_configuration()
provider = await configure_services(config)
Console.write_line('Hello World')
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent("""\
from cpl_core.configuration import Configuration, ConfigurationABC
from cpl_core.console import Console
from cpl_core.dependency_injection import ServiceCollection, ServiceProviderABC
def configure_configuration() -> ConfigurationABC:
config = Configuration()
return config
def configure_services(config: ConfigurationABC) -> ServiceProviderABC:
services = ServiceCollection(config)
return services.build_service_provider()
def main():
config = configure_configuration()
provider = configure_services(config)
Console.write_line('Hello World')
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,42 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class StartupTemplate(TemplateFileABC):
def __init__(self, name: str, path: str):
TemplateFileABC.__init__(self)
self._name = 'startup.py'
self._path = path
self._value = textwrap.dedent("""\
from cpl_core.application import StartupABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC, ServiceCollectionABC
from cpl_core.environment import ApplicationEnvironment
class Startup(StartupABC):
def __init__(self):
StartupABC.__init__(self)
def configure_configuration(self, configuration: ConfigurationABC, environment: ApplicationEnvironment) -> ConfigurationABC:
return configuration
def configure_services(self, services: ServiceCollectionABC, environment: ApplicationEnvironment) -> ServiceProviderABC:
return services.build_service_provider()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

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.new.library.source.tests'
__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,27 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class TestsInitTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = '__init__.py'
self._path = 'src/tests/'
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 self._value

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.new.unittest'
__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,23 +0,0 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class LicenseTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'LICENSE'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,23 +0,0 @@
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ReadmeTemplate(TemplateFileABC):
def __init__(self):
TemplateFileABC.__init__(self)
self._name = 'README.md'
self._path = ''
self._value = """"""
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

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.new.unittest.source'
__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,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.new.unittest.source.name'
__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,74 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ApplicationTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'application.py'
self._path = path
self._use_async = use_async
if self._use_async:
self._value = textwrap.dedent("""\
import unittest
from unittest import TestSuite
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from unittests.test_case import TestCase
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
self._suite: TestSuite = unittest.TestSuite()
async def configure(self):
self._suite.addTest(TestCase('test_equal'))
async def main(self):
runner = unittest.TextTestRunner()
runner.run(self._suite)
""")
else:
self._value = textwrap.dedent("""\
import unittest
from unittest import TestSuite
from cpl_core.application import ApplicationABC
from cpl_core.configuration import ConfigurationABC
from cpl_core.dependency_injection import ServiceProviderABC
from unittests.test_case import TestCase
class Application(ApplicationABC):
def __init__(self, config: ConfigurationABC, services: ServiceProviderABC):
ApplicationABC.__init__(self, config, services)
self._suite: TestSuite = unittest.TestSuite()
def configure(self):
self._suite.addTest(TestCase('test_equal'))
def main(self):
runner = unittest.TextTestRunner()
runner.run(self._suite)
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,27 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainInitTemplate(TemplateFileABC):
def __init__(self, name: str, path: str):
TemplateFileABC.__init__(self)
self._name = '__init__.py'
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 self._value

View File

@ -1,62 +0,0 @@
import textwrap
from cpl_core.utils.string import String
from cpl_cli._templates.template_file_abc import TemplateFileABC
class MainWithApplicationBaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
name = String.convert_to_snake_case(name)
self._name = 'main.py'
self._path = path
import_pkg = f'{name}.'
if use_async:
self._value = textwrap.dedent(f"""\
import asyncio
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
async def main():
app_builder = ApplicationBuilder(Application)
app: Application = await app_builder.build_async()
await app.run_async()
if __name__ == '__main__':
asyncio.run(main())
""")
else:
self._value = textwrap.dedent(f"""\
from cpl_core.application import ApplicationBuilder
from {import_pkg}application import Application
def main():
app_builder = ApplicationBuilder(Application)
app_builder.build().run()
if __name__ == '__main__':
main()
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -1,52 +0,0 @@
import textwrap
from cpl_cli._templates.template_file_abc import TemplateFileABC
class TestCaseTemplate(TemplateFileABC):
def __init__(self, name: str, path: str, use_async: bool):
TemplateFileABC.__init__(self)
self._name = 'test_case.py'
self._path = path
self._use_async = use_async
if self._use_async:
self._value = textwrap.dedent("""\
import unittest
class TestCase(unittest.TestCase):
async def setUp(self) -> None:
pass
async def test_equal(self):
self.assertEqual(True, True)
""")
else:
self._value = textwrap.dedent("""\
import unittest
class TestCase(unittest.TestCase):
def setUp(self) -> None:
pass
def test_equal(self):
self.assertEqual(True, True)
""")
@property
def name(self) -> str:
return self._name
@property
def path(self) -> str:
return self._path
@property
def value(self) -> str:
return self._value

View File

@ -0,0 +1,24 @@
from abc import ABC, abstractmethod
from cpl_cli.abc.file_template_abc import FileTemplateABC
from cpl_core.utils import String
class CodeFileTemplateABC(FileTemplateABC):
@abstractmethod
def __init__(
self,
name: str,
path: str,
code: str,
use_application_api: bool,
use_startup: bool,
use_service_providing: bool,
use_async: bool,
):
FileTemplateABC.__init__(self, name, path, code)
self._use_application_api = use_application_api
self._use_startup = use_startup
self._use_service_providing = use_service_providing
self._use_async = use_async

View File

@ -11,6 +11,9 @@ class FileTemplateABC(ABC):
self._path = path self._path = path
self._code = code self._code = code
def __repr__(self):
return f'<{type(self).__name__} {self._path}{self._name}>'
@property @property
def name(self) -> str: def name(self) -> str:
return self._name return self._name
@ -19,10 +22,13 @@ class FileTemplateABC(ABC):
def path(self) -> str: def path(self) -> str:
return self._path return self._path
@path.setter
def path(self, value: str):
self._path = value
@property @property
def value(self) -> str: def value(self) -> str:
return self.get_code() return self.get_code()
@abstractmethod @abstractmethod
def get_code(self) -> str: def get_code(self) -> str: pass
return self._code

View File

@ -15,7 +15,10 @@ class GenerateSchematicABC(FileTemplateABC):
if schematic in name.lower(): if schematic in name.lower():
self._name = f'{String.convert_to_snake_case(name)}.py' self._name = f'{String.convert_to_snake_case(name)}.py'
self._class_name = f'{String.first_to_upper(name)}{String.first_to_upper(schematic)}' self._class_name = name
if name != '':
self._class_name = f'{String.first_to_upper(name)}{String.first_to_upper(schematic)}'
if schematic in name.lower(): if schematic in name.lower():
self._class_name = f'{String.first_to_upper(name)}' self._class_name = f'{String.first_to_upper(name)}'
@ -24,7 +27,8 @@ class GenerateSchematicABC(FileTemplateABC):
return self._class_name return self._class_name
@abstractmethod @abstractmethod
def get_code(self) -> str: pass def get_code(self) -> str:
pass
@classmethod @classmethod
def build_code_str(cls, code: str, **kwargs) -> str: def build_code_str(cls, code: str, **kwargs) -> str:

View File

@ -0,0 +1,37 @@
from abc import ABC, abstractmethod
from typing import Optional
from cpl_cli.abc.file_template_abc import FileTemplateABC
from cpl_cli.configuration import WorkspaceSettings
class ProjectTypeABC(ABC):
@abstractmethod
def __init__(
self,
base_path: str,
project_name: str,
workspace: Optional[WorkspaceSettings],
use_application_api: bool,
use_startup: bool,
use_service_providing: bool,
use_async: bool,
project_file_data: dict,
):
self._templates: list[FileTemplateABC] = []
self._base_path = base_path
self._project_name = project_name
self._workspace = workspace
self._use_application_api = use_application_api
self._use_startup = use_startup
self._use_service_providing = use_service_providing
self._use_async = use_async
self._project_file_data = project_file_data
@property
def templates(self) -> list[FileTemplateABC]:
return self._templates
def add_template(self, t: FileTemplateABC):
self._templates.append(t)

View File

@ -1,6 +1,7 @@
import os import os
import sys import sys
import textwrap import textwrap
import traceback
from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC from cpl_cli.abc.generate_schematic_abc import GenerateSchematicABC
from cpl_cli.command_abc import CommandABC from cpl_cli.command_abc import CommandABC
@ -34,6 +35,10 @@ class GenerateService(CommandABC):
self._read_custom_schematics_from_path(self._env.runtime_directory) self._read_custom_schematics_from_path(self._env.runtime_directory)
self._read_custom_schematics_from_path(self._env.working_directory) self._read_custom_schematics_from_path(self._env.working_directory)
if len(GenerateSchematicABC.__subclasses__()) == 0:
Console.error(f'No schematics found in template directory: .cpl')
sys.exit()
for schematic in GenerateSchematicABC.__subclasses__(): for schematic in GenerateSchematicABC.__subclasses__():
schematic.register() schematic.register()
@ -142,17 +147,17 @@ class GenerateService(CommandABC):
if not os.path.exists(os.path.join(path, '.cpl')): if not os.path.exists(os.path.join(path, '.cpl')):
return return
sys.path.insert(0, os.path.join(path, '.cpl'))
for r, d, f in os.walk(os.path.join(path, '.cpl')): for r, d, f in os.walk(os.path.join(path, '.cpl')):
for file in f: for file in f:
if not file.endswith('_schematic.py'): if not file.startswith('schematic_') or not file.endswith('.py'):
continue continue
code = '' try:
with open(os.path.join(r, file), 'r') as py_file: exec(open(os.path.join(r, file), 'r').read())
code = py_file.read() except Exception as e:
py_file.close() Console.error(str(e), traceback.format_exc())
sys.exit(-1)
exec(code)
def _get_schematic_by_alias(self, schematic: str) -> str: def _get_schematic_by_alias(self, schematic: str) -> str:
for key in self._schematics: for key in self._schematics:

View File

@ -1,29 +1,28 @@
import os import os
import sys import sys
import textwrap import textwrap
import traceback
from typing import Optional from typing import Optional
from packaging import version from packaging import version
import cpl_cli import cpl_cli
import cpl_core import cpl_core
from cpl_cli.configuration.venv_helper_service import VenvHelper from cpl_cli.abc.project_type_abc import ProjectTypeABC
from cpl_cli.source_creator.unittest_builder import UnittestBuilder
from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.console.console import Console
from cpl_core.utils.string import String
from cpl_cli.command_abc import CommandABC from cpl_cli.command_abc import CommandABC
from cpl_cli.configuration.build_settings import BuildSettings from cpl_cli.configuration.build_settings import BuildSettings
from cpl_cli.configuration.build_settings_name_enum import BuildSettingsNameEnum from cpl_cli.configuration.build_settings_name_enum import BuildSettingsNameEnum
from cpl_cli.configuration.project_settings import ProjectSettings from cpl_cli.configuration.project_settings import ProjectSettings
from cpl_cli.configuration.project_settings_name_enum import ProjectSettingsNameEnum from cpl_cli.configuration.project_settings_name_enum import ProjectSettingsNameEnum
from cpl_cli.configuration.project_type_enum import ProjectTypeEnum from cpl_cli.configuration.project_type_enum import ProjectTypeEnum
from cpl_cli.configuration.venv_helper_service import VenvHelper
from cpl_cli.configuration.version_settings_name_enum import VersionSettingsNameEnum from cpl_cli.configuration.version_settings_name_enum import VersionSettingsNameEnum
from cpl_cli.configuration.workspace_settings import WorkspaceSettings from cpl_cli.configuration.workspace_settings import WorkspaceSettings
from cpl_cli.source_creator.console_builder import ConsoleBuilder from cpl_cli.source_creator.template_builder import TemplateBuilder
from cpl_cli.source_creator.library_builder import LibraryBuilder from cpl_core.configuration.configuration_abc import ConfigurationABC
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.utils.string import String
class NewService(CommandABC): class NewService(CommandABC):
@ -43,11 +42,10 @@ class NewService(CommandABC):
self._project_dict = {} self._project_dict = {}
self._build: BuildSettings = BuildSettings() self._build: BuildSettings = BuildSettings()
self._build_dict = {} self._build_dict = {}
self._project_json = {}
self._name: str = '' self._name: str = ''
self._rel_path: str = '' self._rel_path: str = ''
self._schematic: ProjectTypeEnum = ProjectTypeEnum.console self._project_type: ProjectTypeEnum = ProjectTypeEnum.console
self._use_nothing: bool = False self._use_nothing: bool = False
self._use_application_api: bool = False self._use_application_api: bool = False
self._use_startup: bool = False self._use_startup: bool = False
@ -105,9 +103,9 @@ class NewService(CommandABC):
self._project.from_dict(self._project_dict) self._project.from_dict(self._project_dict)
def _create_build_settings(self): def _create_build_settings(self, project_type: ProjectTypeEnum):
self._build_dict = { self._build_dict = {
BuildSettingsNameEnum.project_type.value: self._schematic, BuildSettingsNameEnum.project_type.value: project_type.value,
BuildSettingsNameEnum.source_path.value: '', BuildSettingsNameEnum.source_path.value: '',
BuildSettingsNameEnum.output_path.value: '../../dist', BuildSettingsNameEnum.output_path.value: '../../dist',
BuildSettingsNameEnum.main.value: f'{String.convert_to_snake_case(self._project.name)}.main', BuildSettingsNameEnum.main.value: f'{String.convert_to_snake_case(self._project.name)}.main',
@ -176,99 +174,7 @@ class NewService(CommandABC):
Console.set_foreground_color(ForegroundColorEnum.default) Console.set_foreground_color(ForegroundColorEnum.default)
def _console(self, args: list[str]):
"""
Generates new console project
:param args:
:return:
"""
self._create_project_settings()
self._create_build_settings()
self._create_project_json()
path = self._get_project_path()
if path is None:
return
self._get_project_information()
project_name = self._project.name
if self._rel_path != '':
project_name = f'{self._rel_path}/{project_name}'
try:
ConsoleBuilder.build(
path,
self._use_application_api,
self._use_startup,
self._use_service_providing,
self._use_async,
project_name,
self._project_json,
self._workspace
)
except Exception as e:
Console.error('Could not create project', str(e))
def _unittest(self, args: list[str]):
"""
Generates new unittest project
:param args:
:return:
"""
self._create_project_settings()
self._create_build_settings()
self._create_project_json()
path = self._get_project_path()
if path is None:
return
self._get_project_information(is_unittest=True)
project_name = self._project.name
if self._rel_path != '':
project_name = f'{self._rel_path}/{project_name}'
try:
UnittestBuilder.build(
path,
self._use_application_api,
self._use_async,
project_name,
self._project_json,
self._workspace
)
except Exception as e:
Console.error('Could not create project', str(e))
def _library(self, args: list[str]):
"""
Generates new library project
:param args:
:return:
"""
self._create_project_settings()
self._create_build_settings()
self._create_project_json()
path = self._get_project_path()
if path is None:
return
self._get_project_information()
project_name = self._project.name
if self._rel_path != '':
project_name = f'{self._rel_path}/{project_name}'
try:
LibraryBuilder.build(
path,
self._use_application_api,
self._use_startup,
self._use_service_providing,
self._use_async,
project_name,
self._project_json,
self._workspace
)
except Exception as e:
Console.error('Could not create project', str(e))
def _create_venv(self): def _create_venv(self):
project = self._project.name project = self._project.name
if self._workspace is not None: if self._workspace is not None:
project = self._workspace.default_project project = self._workspace.default_project
@ -286,6 +192,110 @@ class NewService(CommandABC):
explicit_path=os.path.join(self._env.working_directory, project, self._project.python_executable.replace('../', '')) explicit_path=os.path.join(self._env.working_directory, project, self._project.python_executable.replace('../', ''))
) )
@staticmethod
def _read_custom_project_types_from_path(path: str):
if not os.path.exists(os.path.join(path, '.cpl')):
return
sys.path.insert(0, os.path.join(path, '.cpl'))
for r, d, f in os.walk(os.path.join(path, '.cpl')):
for file in f:
if file.startswith('project_file_') or not file.startswith('project_') or not file.endswith('.py'):
continue
try:
exec(open(os.path.join(r, file), 'r').read())
except Exception as e:
Console.error(str(e), traceback.format_exc())
sys.exit(-1)
def _create_project(self, project_type: ProjectTypeEnum):
self._read_custom_project_types_from_path(self._env.runtime_directory)
self._read_custom_project_types_from_path(self._env.working_directory)
if len(ProjectTypeABC.__subclasses__()) == 0:
Console.error(f'No project types found in template directory: .cpl')
sys.exit()
self._create_project_settings()
self._create_build_settings(project_type)
self._create_project_json()
path = self._get_project_path()
if path is None:
return
self._get_project_information()
project_name = self._project.name
if self._rel_path != '':
project_name = f'{self._rel_path}/{project_name}'
project_class = None
for p in ProjectTypeABC.__subclasses__():
if p.__name__.lower() != project_type.value and p.__name__.lower()[0] != project_type.value[0]:
continue
project_class = p
if project_class is None:
Console.error(f'Project type {project_type.value} not found in template directory: .cpl/')
sys.exit()
base = 'src/'
split_project_name = project_name.split('/')
if self._use_base and len(split_project_name) > 0:
base = f'{split_project_name[0]}/'
project = project_class(
base if self._workspace is not None else 'src/',
project_name,
self._workspace,
self._use_application_api,
self._use_startup,
self._use_service_providing,
self._use_async,
self._project_json
)
if self._workspace is None:
TemplateBuilder.create_workspace(
f'{project_name}/cpl-workspace.json',
project_name.split('/')[-1],
{
project_name: f'{base if self._workspace is not None else "src/"}{String.convert_to_snake_case(project_name)}/{project_name}.json'
},
{}
)
else:
self._workspace.projects[project_name] = f'{base if self._workspace is not None else "src/"}{String.convert_to_snake_case(project_name)}/{project_name}.json'
TemplateBuilder.create_workspace('cpl-workspace.json', self._workspace.default_project, self._workspace.projects, self._workspace.scripts)
for template in project.templates:
rel_base = '/'.join(project_name.split('/')[:-1])
template_path_base = template.path.split('/')[0]
if not self._use_base and rel_base != '' and template_path_base != '' and template_path_base != rel_base:
template.path = template.path.replace(f'{template_path_base}/', f'{template_path_base}/{rel_base}/')
if template.name.endswith(f'{project_name.split("/")[-1]}.json'):
pass
file_path = os.path.join(
project_name if self._workspace is None else '',
template.path,
template.name
)
Console.spinner(
f'Creating {file_path}',
TemplateBuilder.build,
file_path,
template,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
if self._use_venv:
self._create_venv()
def execute(self, args: list[str]): def execute(self, args: list[str]):
""" """
Entry point of command Entry point of command
@ -331,24 +341,15 @@ class NewService(CommandABC):
unittest = self._config.get_configuration(ProjectTypeEnum.unittest.value) unittest = self._config.get_configuration(ProjectTypeEnum.unittest.value)
if console is not None and library is None and unittest is None: if console is not None and library is None and unittest is None:
self._name = console self._name = console
self._schematic = ProjectTypeEnum.console.value self._create_project(ProjectTypeEnum.console)
self._console(args)
if self._use_venv:
self._create_venv()
elif console is None and library is not None and unittest is None: elif console is None and library is not None and unittest is None:
self._name = library self._name = library
self._schematic = ProjectTypeEnum.library.value self._create_project(ProjectTypeEnum.library)
self._library(args)
if self._use_venv:
self._create_venv()
elif console is None and library is None and unittest is not None: elif console is None and library is None and unittest is not None:
self._name = unittest self._name = unittest
self._schematic = ProjectTypeEnum.unittest.value self._create_project(ProjectTypeEnum.unittest)
self._unittest(args)
if self._use_venv:
self._create_venv()
else: else:
Console.error(f'Project type not found') Console.error(f'Project type not found')

View File

@ -1,182 +0,0 @@
import json
import os
from typing import Optional
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.console.console import Console
from cpl_core.utils.string import String
from cpl_cli.configuration.workspace_settings import WorkspaceSettings
from cpl_cli.configuration.workspace_settings_name_enum import WorkspaceSettingsNameEnum
from cpl_cli.source_creator.template_builder import TemplateBuilder
from cpl_cli._templates.new.console.appsettings_json import AppsettingsTemplate
from cpl_cli._templates.new.console.license import LicenseTemplate
from cpl_cli._templates.new.console.readme_py import ReadmeTemplate
from cpl_cli._templates.new.console.source.name.application import ApplicationTemplate
from cpl_cli._templates.new.console.source.name.init import MainInitTemplate
from cpl_cli._templates.new.console.source.name.main import MainWithApplicationHostAndStartupTemplate, \
MainWithoutApplicationBaseTemplate, MainWithApplicationBaseTemplate, MainWithDependencyInjection
from cpl_cli._templates.new.console.source.name.startup import StartupTemplate
from cpl_cli._templates.new.console.source.tests.init import TestsInitTemplate
from cpl_cli._templates.template_file_abc import TemplateFileABC
class ConsoleBuilder:
def __init__(self):
pass
@staticmethod
def _create_file(file_name: str, content: dict):
if not os.path.isabs(file_name):
file_name = os.path.abspath(file_name)
path = os.path.dirname(file_name)
if not os.path.isdir(path):
os.makedirs(path)
with open(file_name, 'w') as project_json:
project_json.write(json.dumps(content, indent=2))
project_json.close()
@classmethod
def _create_workspace(cls, path: str, project_name, projects: dict, scripts: dict):
ws_dict = {
WorkspaceSettings.__name__: {
WorkspaceSettingsNameEnum.default_project.value: project_name,
WorkspaceSettingsNameEnum.projects.value: projects,
WorkspaceSettingsNameEnum.scripts.value: scripts
}
}
Console.spinner(
f'Creating {path}',
cls._create_file,
path,
ws_dict,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
@classmethod
def build(cls, project_path: str, use_application_api: bool, use_startup: bool, use_service_providing: bool,
use_async: bool, project_name: str, project_settings: dict, workspace: Optional[WorkspaceSettings]):
"""
Builds the console project files
:param project_path:
:param use_application_api:
:param use_startup:
:param use_service_providing:
:param use_async:
:param project_name:
:param project_settings:
:param workspace:
:return:
"""
pj_name = project_name
if '/' in pj_name:
pj_name = pj_name.split('/')[len(pj_name.split('/')) - 1]
project_name_snake = String.convert_to_snake_case(pj_name)
if workspace is None:
templates: list[TemplateFileABC] = [
LicenseTemplate(),
ReadmeTemplate(),
TestsInitTemplate(),
AppsettingsTemplate(),
MainInitTemplate(project_name, os.path.join('src/', project_name_snake))
]
else:
project_path = os.path.join(
os.path.dirname(project_path),
project_name_snake
)
templates: list[TemplateFileABC] = [
AppsettingsTemplate(),
MainInitTemplate('', '')
]
if not os.path.isdir(project_path):
os.makedirs(project_path)
py_src_rel_path = ''
src_name = project_name_snake
if workspace is None:
py_src_rel_path = f'src/{src_name}'
if use_application_api:
templates.append(ApplicationTemplate(src_name, py_src_rel_path, use_async))
if use_startup:
templates.append(StartupTemplate(src_name, py_src_rel_path))
templates.append(MainWithApplicationHostAndStartupTemplate(src_name, py_src_rel_path, use_async))
else:
templates.append(MainWithApplicationBaseTemplate(src_name, py_src_rel_path, use_async))
else:
if use_service_providing:
templates.append(MainWithDependencyInjection(src_name, py_src_rel_path, use_async))
else:
templates.append(MainWithoutApplicationBaseTemplate(src_name, py_src_rel_path, use_async))
src_rel_path = ''
if '/' in project_name:
old_pj_name = project_name
parts = project_name.split('/')
project_name = parts[len(parts) - 1]
src_rel_path = old_pj_name.split(project_name)[0]
proj_name = project_name
if src_rel_path.endswith('/'):
src_rel_path = src_rel_path[:len(src_rel_path) - 1]
if src_rel_path != '':
proj_name = f'{src_rel_path}/{project_name}'
if workspace is not None:
proj_name = project_name_snake
if src_rel_path != '':
project_file_path = f'{src_rel_path}/{project_name_snake}/{project_name}.json'
else:
project_file_path = f'{project_name_snake}/{project_name}.json'
if workspace is None:
src_path = f'src/{project_name_snake}'
workspace_file_path = f'{proj_name}/cpl-workspace.json'
project_file_rel_path = f'{src_path}/{project_name}.json'
project_file_path = f'{proj_name}/{src_path}/{project_name}.json'
cls._create_workspace(
workspace_file_path,
project_name,
{
project_name: project_file_rel_path
},
{}
)
else:
workspace.projects[project_name] = f'src/{project_file_path}'
cls._create_workspace('cpl-workspace.json', workspace.default_project, workspace.projects, workspace.scripts)
Console.spinner(
f'Creating {project_file_path}',
cls._create_file,
project_file_path if workspace is None else f'src/{project_file_path}',
project_settings,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
for template in templates:
divider = ''
if template.path != '' and not template.path.endswith('/'):
divider = '/'
Console.spinner(
f'Creating {proj_name}/{template.path}{divider}{template.name}',
TemplateBuilder.build,
project_path,
template,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)

View File

@ -1,186 +0,0 @@
import json
import os
from typing import Optional
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.console.console import Console
from cpl_core.utils.string import String
from cpl_cli.configuration.workspace_settings import WorkspaceSettings
from cpl_cli.configuration.workspace_settings_name_enum import WorkspaceSettingsNameEnum
from cpl_cli.source_creator.template_builder import TemplateBuilder
from cpl_cli._templates.new.library.appsettings_json import AppsettingsTemplate
from cpl_cli._templates.new.library.license import LicenseTemplate
from cpl_cli._templates.new.library.readme_py import ReadmeTemplate
from cpl_cli._templates.new.library.source.name.application import ApplicationTemplate
from cpl_cli._templates.new.library.source.name.init import NameInitTemplate
from cpl_cli._templates.new.library.source.name.main import MainWithApplicationHostAndStartupTemplate, \
MainWithoutApplicationBaseTemplate, MainWithApplicationBaseTemplate, MainWithDependencyInjection
from cpl_cli._templates.new.library.source.name.startup import StartupTemplate
from cpl_cli._templates.new.library.source.tests.init import TestsInitTemplate
from cpl_cli._templates.template_file_abc import TemplateFileABC
class LibraryBuilder:
def __init__(self):
pass
@staticmethod
def _create_file(file_name: str, content: dict):
if not os.path.isabs(file_name):
file_name = os.path.abspath(file_name)
path = os.path.dirname(file_name)
if not os.path.isdir(path):
os.makedirs(path)
with open(file_name, 'w') as project_json:
project_json.write(json.dumps(content, indent=2))
project_json.close()
@classmethod
def _create_workspace(cls, path: str, project_name, projects: dict, scripts: dict):
ws_dict = {
WorkspaceSettings.__name__: {
WorkspaceSettingsNameEnum.default_project.value: project_name,
WorkspaceSettingsNameEnum.projects.value: projects,
WorkspaceSettingsNameEnum.scripts.value: scripts,
}
}
Console.spinner(
f'Creating {path}',
cls._create_file,
path,
ws_dict,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
@classmethod
def build(cls, project_path: str, use_application_api: bool, use_startup: bool,
use_async: bool, use_service_providing: bool, project_name: str, project_settings: dict,
workspace: Optional[WorkspaceSettings]):
"""
Builds the library project files
:param project_path:
:param use_application_api:
:param use_startup:
:param use_service_providing:
:param use_async:
:param project_name:
:param project_settings:
:param workspace:
:return:
"""
pj_name = project_name
if '/' in pj_name:
pj_name = pj_name.split('/')[len(pj_name.split('/')) - 1]
project_name_snake = String.convert_to_snake_case(pj_name)
if workspace is None:
templates: list[TemplateFileABC] = [
LicenseTemplate(),
ReadmeTemplate(),
TestsInitTemplate(),
NameInitTemplate(project_name, os.path.join(
'src/', project_name_snake)),
AppsettingsTemplate()
]
else:
project_path = os.path.join(
os.path.dirname(project_path),
project_name_snake
)
templates: list[TemplateFileABC] = [
LicenseTemplate(),
ReadmeTemplate(),
NameInitTemplate('', ''),
AppsettingsTemplate()
]
if not os.path.isdir(project_path):
os.makedirs(project_path)
py_src_rel_path = ''
src_name = project_name_snake
if workspace is None:
py_src_rel_path = f'src/{src_name}'
if use_application_api:
templates.append(ApplicationTemplate(src_name, py_src_rel_path, use_async))
if use_startup:
templates.append(StartupTemplate(src_name, py_src_rel_path))
templates.append(MainWithApplicationHostAndStartupTemplate(src_name, py_src_rel_path, use_async))
else:
templates.append(MainWithApplicationBaseTemplate(src_name, py_src_rel_path, use_async))
else:
if use_service_providing:
templates.append(MainWithDependencyInjection(src_name, py_src_rel_path, use_async))
else:
templates.append(MainWithoutApplicationBaseTemplate(src_name, py_src_rel_path, use_async))
src_rel_path = ''
if '/' in project_name:
old_pj_name = project_name
parts = project_name.split('/')
project_name = parts[len(parts) - 1]
src_rel_path = old_pj_name.split(project_name)[0]
proj_name = project_name
if src_rel_path.endswith('/'):
src_rel_path = src_rel_path[:len(src_rel_path) - 1]
if src_rel_path != '':
proj_name = f'{src_rel_path}/{project_name}'
if workspace is not None:
proj_name = project_name_snake
if src_rel_path != '':
project_file_path = f'{src_rel_path}/{project_name_snake}/{project_name}.json'
else:
project_file_path = f'{project_name_snake}/{project_name}.json'
if workspace is None:
src_path = f'src/{project_name_snake}'
workspace_file_path = f'{proj_name}/cpl-workspace.json'
project_file_rel_path = f'{src_path}/{project_name}.json'
project_file_path = f'{proj_name}/{src_path}/{project_name}.json'
cls._create_workspace(
workspace_file_path,
project_name,
{
project_name: project_file_rel_path
},
{}
)
else:
workspace.projects[project_name] = f'src/{project_file_path}'
cls._create_workspace('cpl-workspace.json', workspace.default_project, workspace.projects, workspace.scripts)
Console.spinner(
f'Creating {project_file_path}',
cls._create_file,
project_file_path if workspace is None else f'src/{project_file_path}',
project_settings,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
for template in templates:
divider = ''
if template.path != '' and not template.path.endswith('/'):
divider = '/'
Console.spinner(
f'Creating {proj_name}/{template.path}{divider}{template.name}',
TemplateBuilder.build,
project_path,
template,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)

View File

@ -1,23 +1,55 @@
import json
import os import os
from cpl_cli._templates.template_file_abc import TemplateFileABC from cpl_cli.abc.file_template_abc import FileTemplateABC
from cpl_cli.configuration import WorkspaceSettings, WorkspaceSettingsNameEnum
from cpl_core.console import Console, ForegroundColorEnum
class TemplateBuilder: class TemplateBuilder:
@staticmethod @staticmethod
def build(project_path: str, template: TemplateFileABC): def build_cpl_file(file_name: str, content: dict):
if not os.path.isabs(file_name):
file_name = os.path.abspath(file_name)
path = os.path.dirname(file_name)
if not os.path.isdir(path):
os.makedirs(path)
with open(file_name, 'w') as project_json:
project_json.write(json.dumps(content, indent=2))
project_json.close()
@classmethod
def create_workspace(cls, path: str, project_name, projects: dict, scripts: dict):
ws_dict = {
WorkspaceSettings.__name__: {
WorkspaceSettingsNameEnum.default_project.value: project_name,
WorkspaceSettingsNameEnum.projects.value: projects,
WorkspaceSettingsNameEnum.scripts.value: scripts
}
}
Console.spinner(
f'Creating {path}',
cls.build_cpl_file,
path,
ws_dict,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
@staticmethod
def build(file_path: str, template: FileTemplateABC):
""" """
Creates template Creates template
:param project_path: :param file_path:
:param template: :param template:
:return: :return:
""" """
file_path = os.path.join(project_path, template.path, template.name) if not os.path.isdir(os.path.dirname(file_path)):
file_rel_path = os.path.join(project_path, template.path) os.makedirs(os.path.dirname(file_path))
if not os.path.isdir(file_rel_path):
os.makedirs(file_rel_path)
with open(file_path, 'w') as file: with open(file_path, 'w') as file:
file.write(template.value) file.write(template.value)

View File

@ -1,164 +0,0 @@
import json
import os
from typing import Optional
from cpl_cli._templates.new.unittest.license import LicenseTemplate
from cpl_cli._templates.new.unittest.readme_py import ReadmeTemplate
from cpl_cli._templates.new.unittest.source.name.application import ApplicationTemplate
from cpl_cli._templates.new.unittest.source.name.init import MainInitTemplate
from cpl_cli._templates.new.unittest.source.name.main import MainWithApplicationBaseTemplate
from cpl_cli._templates.new.unittest.source.name.test_case import TestCaseTemplate
from cpl_cli._templates.template_file_abc import TemplateFileABC
from cpl_cli.configuration.workspace_settings import WorkspaceSettings
from cpl_cli.configuration.workspace_settings_name_enum import WorkspaceSettingsNameEnum
from cpl_cli.source_creator.template_builder import TemplateBuilder
from cpl_core.console.console import Console
from cpl_core.console.foreground_color_enum import ForegroundColorEnum
from cpl_core.utils.string import String
class UnittestBuilder:
def __init__(self):
pass
@staticmethod
def _create_file(file_name: str, content: dict):
if not os.path.isabs(file_name):
file_name = os.path.abspath(file_name)
path = os.path.dirname(file_name)
if not os.path.isdir(path):
os.makedirs(path)
with open(file_name, 'w') as project_json:
project_json.write(json.dumps(content, indent=2))
project_json.close()
@classmethod
def _create_workspace(cls, path: str, project_name, projects: dict, scripts: dict):
ws_dict = {
WorkspaceSettings.__name__: {
WorkspaceSettingsNameEnum.default_project.value: project_name,
WorkspaceSettingsNameEnum.projects.value: projects,
WorkspaceSettingsNameEnum.scripts.value: scripts
}
}
Console.spinner(
f'Creating {path}',
cls._create_file,
path,
ws_dict,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
@classmethod
def build(cls, project_path: str, use_application_api: bool,
use_async: bool, project_name: str, project_settings: dict, workspace: Optional[WorkspaceSettings]):
"""
Builds the console project files
:param project_path:
:param use_application_api:
:param use_async:
:param project_name:
:param project_settings:
:param workspace:
:return:
"""
pj_name = project_name
if '/' in pj_name:
pj_name = pj_name.split('/')[len(pj_name.split('/')) - 1]
project_name_snake = String.convert_to_snake_case(pj_name)
if workspace is None:
templates: list[TemplateFileABC] = [
LicenseTemplate(),
ReadmeTemplate(),
MainInitTemplate(project_name, os.path.join('src/', project_name_snake))
]
else:
project_path = os.path.join(
os.path.dirname(project_path),
project_name_snake
)
templates: list[TemplateFileABC] = [
MainInitTemplate('', '')
]
if not os.path.isdir(project_path):
os.makedirs(project_path)
py_src_rel_path = ''
src_name = project_name_snake
if workspace is None:
py_src_rel_path = f'src/{src_name}'
templates.append(ApplicationTemplate(src_name, py_src_rel_path, use_async))
templates.append(MainWithApplicationBaseTemplate(src_name, py_src_rel_path, use_async))
templates.append(TestCaseTemplate(src_name, py_src_rel_path, use_async))
src_rel_path = ''
if '/' in project_name:
old_pj_name = project_name
parts = project_name.split('/')
project_name = parts[len(parts) - 1]
src_rel_path = old_pj_name.split(project_name)[0]
proj_name = project_name
if src_rel_path.endswith('/'):
src_rel_path = src_rel_path[:len(src_rel_path) - 1]
if src_rel_path != '':
proj_name = f'{src_rel_path}/{project_name}'
if workspace is not None:
proj_name = project_name_snake
if src_rel_path != '':
project_file_path = f'{src_rel_path}/{project_name_snake}/{project_name}.json'
else:
project_file_path = f'{project_name_snake}/{project_name}.json'
if workspace is None:
src_path = f'src/{project_name_snake}'
workspace_file_path = f'{proj_name}/cpl-workspace.json'
project_file_rel_path = f'{src_path}/{project_name}.json'
project_file_path = f'{proj_name}/{src_path}/{project_name}.json'
cls._create_workspace(
workspace_file_path,
project_name,
{
project_name: project_file_rel_path
},
{}
)
else:
workspace.projects[project_name] = f'src/{project_file_path}'
cls._create_workspace('cpl-workspace.json', workspace.default_project, workspace.projects, workspace.scripts)
Console.spinner(
f'Creating {project_file_path}',
cls._create_file,
project_file_path if workspace is None else f'src/{project_file_path}',
project_settings,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)
for template in templates:
divider = ''
if template.path != '' and not template.path.endswith('/'):
divider = '/'
Console.spinner(
f'Creating {proj_name}/{template.path}{divider}{template.name}',
TemplateBuilder.build,
project_path,
template,
text_foreground_color=ForegroundColorEnum.green,
spinner_foreground_color=ForegroundColorEnum.cyan
)

View File

@ -7,6 +7,7 @@ from unittests_cli.constants import PLAYGROUND_PATH
class CommandTestCase(unittest.TestCase): class CommandTestCase(unittest.TestCase):
_skip_tear_down = False
def __init__(self, method_name: str): def __init__(self, method_name: str):
unittest.TestCase.__init__(self, method_name) unittest.TestCase.__init__(self, method_name)
@ -18,7 +19,8 @@ class CommandTestCase(unittest.TestCase):
if os.path.exists(PLAYGROUND_PATH): if os.path.exists(PLAYGROUND_PATH):
shutil.rmtree(os.path.abspath(os.path.join(PLAYGROUND_PATH))) shutil.rmtree(os.path.abspath(os.path.join(PLAYGROUND_PATH)))
os.makedirs(PLAYGROUND_PATH) if not os.path.exists(PLAYGROUND_PATH):
os.makedirs(PLAYGROUND_PATH)
os.chdir(PLAYGROUND_PATH) os.chdir(PLAYGROUND_PATH)
except Exception as e: except Exception as e:
print(f'Setup of {__name__} failed: {traceback.format_exc()}') print(f'Setup of {__name__} failed: {traceback.format_exc()}')
@ -28,6 +30,8 @@ class CommandTestCase(unittest.TestCase):
@classmethod @classmethod
def tearDownClass(cls): def tearDownClass(cls):
if cls._skip_tear_down:
return
try: try:
if os.path.exists(PLAYGROUND_PATH): if os.path.exists(PLAYGROUND_PATH):
shutil.rmtree(os.path.abspath(os.path.join(PLAYGROUND_PATH))) shutil.rmtree(os.path.abspath(os.path.join(PLAYGROUND_PATH)))

View File

@ -28,7 +28,7 @@ class AddTestCase(CommandTestCase):
# create projects # create projects
CLICommands.new('console', self._source, '--ab', '--s') CLICommands.new('console', self._source, '--ab', '--s')
os.chdir(os.path.join(os.getcwd(), self._source)) os.chdir(os.path.join(os.getcwd(), self._source))
CLICommands.new('console', self._target, '--ab', '--s') CLICommands.new('library', self._target, '--ab', '--s')
def test_add(self): def test_add(self):
CLICommands.add(self._source, self._target) CLICommands.add(self._source, self._target)

View File

@ -1,5 +1,6 @@
import json import json
import os import os
import unittest
from cpl_core.utils import String from cpl_core.utils import String
from unittests_cli.abc.command_test_case import CommandTestCase from unittests_cli.abc.command_test_case import CommandTestCase
@ -32,8 +33,8 @@ class NewTestCase(CommandTestCase):
project_path = os.path.abspath(os.path.join(PLAYGROUND_PATH, base, name, 'src/', String.convert_to_snake_case(name))) project_path = os.path.abspath(os.path.join(PLAYGROUND_PATH, base, name, 'src/', String.convert_to_snake_case(name)))
self.assertTrue(os.path.exists(project_path)) self.assertTrue(os.path.exists(project_path))
self.assertTrue(os.path.join(project_path, f'{name}.json')) self.assertTrue(os.path.exists(os.path.join(project_path, f'{name}.json')))
self.assertTrue(os.path.join(project_path, f'main.py')) self.assertTrue(os.path.exists(os.path.join(project_path, f'main.py')))
if '--ab' in args: if '--ab' in args:
self.assertTrue(os.path.isfile(os.path.join(project_path, f'application.py'))) self.assertTrue(os.path.isfile(os.path.join(project_path, f'application.py')))
@ -110,23 +111,23 @@ class NewTestCase(CommandTestCase):
def test_console_without_anything(self): def test_console_without_anything(self):
self._test_project('console', 'test-console-without-anything', '--n') self._test_project('console', 'test-console-without-anything', '--n')
def test_sub_console(self): def test_console_sub(self):
self._test_sub_project('console', 'test-sub-console', 'test-console', '--ab', '--s', '--sp', '--venv', test_venv=True) self._test_sub_project('console', 'test-sub-console', 'test-console', '--ab', '--s', '--sp', '--venv', test_venv=True)
def test_sub_console_with_other_base(self): def test_console_sub_with_other_base(self):
self._test_sub_project('console', 'tools/test-sub-console', 'test-console', '--ab', '--s', '--sp', '--venv', '--base', test_venv=True) self._test_sub_project('console', 'tools/test-sub-console', 'test-console', '--ab', '--s', '--sp', '--venv', '--base', test_venv=True)
def test_library(self): def test_library(self):
self._test_project('library', 'test-library', '--ab', '--s', '--sp') self._test_project('library', 'test-library', '--ab', '--s', '--sp')
def test_sub_library(self): def test_library_sub(self):
self._test_sub_project('library', 'test-sub-library', 'test-console', '--ab', '--s', '--sp') self._test_sub_project('library', 'test-sub-library', 'test-console', '--ab', '--s', '--sp')
def test_sub_directory_library(self): def test_library_sub_directory(self):
self._test_sub_directory_project('library', 'directory', 'test-sub-library', 'test-console', '--ab', '--s', '--sp') self._test_sub_directory_project('library', 'directory', 'test-sub-library', 'test-console', '--ab', '--s', '--sp')
def test_unittest(self): def test_unittest(self):
self._test_project('unittest', 'test-unittest', '--ab') self._test_project('unittest', 'test-unittest', '--ab')
def test_sub_unittest(self): def test_unittest_sub(self):
self._test_sub_project('unittest', 'test-unittest', 'test-console', '--ab', '--s', '--sp') self._test_sub_project('unittest', 'test-unittest', 'test-console', '--ab', '--s', '--sp')

View File

@ -26,6 +26,14 @@ class PublishTestCase(CommandTestCase):
return project_json return project_json
def _get_appsettings(self):
with open(os.path.join(os.getcwd(), os.path.dirname(self._project_file), 'appsettings.json'), 'r', encoding='utf-8') as cfg:
# load json
project_json = json.load(cfg)
cfg.close()
return project_json
def _save_project_settings(self, settings: dict): def _save_project_settings(self, settings: dict):
with open(os.path.join(os.getcwd(), self._project_file), 'w', encoding='utf-8') as project_file: with open(os.path.join(os.getcwd(), self._project_file), 'w', encoding='utf-8') as project_file:
project_file.write(json.dumps(settings, indent=2)) project_file.write(json.dumps(settings, indent=2))
@ -86,4 +94,8 @@ class PublishTestCase(CommandTestCase):
with open(f'{full_dist_path}/{self._source}.json', 'w') as file: with open(f'{full_dist_path}/{self._source}.json', 'w') as file:
file.write(json.dumps(self._get_project_settings(), indent=2)) file.write(json.dumps(self._get_project_settings(), indent=2))
file.close() file.close()
with open(f'{full_dist_path}/appsettings.json', 'w') as file:
file.write(json.dumps(self._get_appsettings(), indent=2))
file.close()
self.assertTrue(self._are_dir_trees_equal(f'./src/{String.convert_to_snake_case(self._source)}', full_dist_path)) self.assertTrue(self._are_dir_trees_equal(f'./src/{String.convert_to_snake_case(self._source)}', full_dist_path))