From 5f25400bcdea8dcbfef004ee564f34d0cc69f989 Mon Sep 17 00:00:00 2001 From: edraft Date: Tue, 16 Sep 2025 08:39:00 +0200 Subject: [PATCH] Updated config & environment --- .../cpl/core/application/application_abc.py | 8 +- .../core/application/application_builder.py | 42 +-- .../application/application_extension_abc.py | 4 +- .../async_application_extension_abc.py | 4 +- .../cpl/core/application/async_startup_abc.py | 15 +- .../async_startup_extension_abc.py | 10 +- .../cpl/core/application/startup_abc.py | 9 +- .../core/application/startup_extension_abc.py | 10 +- .../cpl/core/configuration/__init__.py | 10 - .../cpl/core/configuration/argument_abc.py | 64 ---- .../core/configuration/argument_builder.py | 30 -- .../configuration/argument_executable_abc.py | 11 - .../core/configuration/argument_type_enum.py | 7 - .../cpl/core/configuration/configuration.py | 273 ++---------------- .../core/configuration/configuration_abc.py | 140 --------- .../configuration_variable_name_enum.py | 11 - .../core/configuration/executable_argument.py | 40 --- .../cpl/core/configuration/flag_argument.py | 13 - .../cpl/core/configuration/validator_abc.py | 11 - .../core/configuration/variable_argument.py | 28 -- src/cpl-core/cpl/core/database/db_logger.py | 2 +- .../service_collection.py | 7 +- .../dependency_injection/service_provider.py | 19 +- src/cpl-core/cpl/core/environment/__init__.py | 5 +- .../environment/application_environment.py | 95 ------ .../application_environment_abc.py | 98 ------- .../cpl/core/environment/environment.py | 46 ++- ...nment_name_enum.py => environment_enum.py} | 2 +- src/cpl-core/cpl/core/log/_log_writer.py | 4 +- src/cpl-core/cpl/core/pipes/bool_pipe.py | 14 +- .../cpl/core/pipes/ip_address_pipe.py | 30 +- src/cpl-core/cpl/core/pipes/pipe_abc.py | 11 +- src/cpl-core/cpl/core/pipes/version_pipe.py | 17 -- src/cpl-core/cpl/core/typing.py | 1 + src/cpl-core/cpl/core/utils/__init__.py | 4 +- src/cpl-core/cpl/core/utils/b64.py | 43 +++ src/cpl-core/cpl/core/utils/get_value.py | 13 +- src/cpl-core/cpl/core/utils/json_processor.py | 4 +- src/cpl-core/cpl/core/utils/string.py | 36 ++- src/cpl-core/requirements.txt | 1 + src/cpl-mail/cpl/mail/email_client.py | 6 +- tests/custom/async/src/async/startup.py | 6 +- tests/custom/database/src/startup.py | 6 +- tests/custom/di/src/di/startup.py | 6 +- .../custom/general/src/general/application.py | 36 +-- .../general/src/general/arguments/__init__.py | 1 - .../general/arguments/generate_argument.py | 14 - .../src/general/arguments/install_argument.py | 10 - tests/custom/general/src/general/main.py | 2 - .../general/src/general/parameter_startup.py | 38 --- tests/custom/general/src/general/startup.py | 16 +- .../general/src/general/test_extension.py | 4 +- .../general/src/general/test_service.py | 5 +- .../src/general/test_startup_extension.py | 8 +- .../translation/src/translation/startup.py | 6 +- tests/generated/simple-app/LICENSE | 0 tests/generated/simple-app/README.md | 0 tests/generated/simple-app/appsettings.json | 15 - tests/generated/simple-app/cpl-workspace.json | 8 - tests/generated/simple-app/cpl.json | 40 --- tests/generated/simple-app/src/application.py | 15 - tests/generated/simple-app/src/main.py | 12 - .../simple-app/src/simple_app/__init__.py | 0 .../simple-app/src/simple_app/application.py | 15 - .../simple-app/src/simple_app/main.py | 12 - .../simple-app/src/simple_app/simple-app.json | 41 --- .../simple-app/src/tests/__init__.py | 0 tests/generated/simple-console/LICENSE | 0 tests/generated/simple-console/README.md | 0 .../generated/simple-console/appsettings.json | 15 - .../simple-console/cpl-workspace.json | 8 - tests/generated/simple-console/cpl.json | 40 --- tests/generated/simple-console/src/main.py | 9 - .../src/simple_console/__init__.py | 0 .../simple-console/src/simple_console/main.py | 9 - .../src/simple_console/simple-console.json | 41 --- .../simple-console/src/tests/__init__.py | 0 tests/generated/simple-di/LICENSE | 0 tests/generated/simple-di/README.md | 0 tests/generated/simple-di/appsettings.json | 15 - tests/generated/simple-di/cpl-workspace.json | 8 - tests/generated/simple-di/cpl.json | 40 --- tests/generated/simple-di/src/main.py | 23 -- .../simple-di/src/simple_di/__init__.py | 0 .../generated/simple-di/src/simple_di/main.py | 23 -- .../simple-di/src/simple_di/simple-di.json | 41 --- .../generated/simple-di/src/tests/__init__.py | 0 tests/generated/simple-startup-app/LICENSE | 0 tests/generated/simple-startup-app/README.md | 0 .../simple-startup-app/appsettings.json | 15 - .../simple-startup-app/cpl-workspace.json | 8 - .../src/simple_startup_app/__init__.py | 0 .../src/simple_startup_app/application.py | 15 - .../src/simple_startup_app/main.py | 14 - .../simple-startup-app.json | 41 --- .../src/simple_startup_app/startup.py | 18 -- .../simple-startup-app/src/tests/__init__.py | 0 tests/generated/startup-app/LICENSE | 0 tests/generated/startup-app/README.md | 0 tests/generated/startup-app/cpl.json | 40 --- .../generated/startup-app/src/application.py | 15 - tests/generated/startup-app/src/main.py | 14 - tests/generated/startup-app/src/startup.py | 18 -- .../startup-app/src/tests/__init__.py | 0 tools/set_pip_urls/__init__.py | 1 - tools/set_pip_urls/application.py | 45 --- tools/set_pip_urls/appsettings.json | 7 - tools/set_pip_urls/main.py | 14 - tools/set_pip_urls/pip_settings.py | 22 -- tools/set_pip_urls/set-pip-urls.json | 42 --- tools/set_pip_urls/startup.py | 21 -- tools/set_version/__init__.py | 1 - tools/set_version/application.py | 124 -------- tools/set_version/git_service.py | 17 -- tools/set_version/main.py | 14 - tools/set_version/set-version.json | 43 --- tools/set_version/startup.py | 34 --- tools/set_version/version_setter_service.py | 62 ---- unittests/unittests_cli/add_test_case.py | 4 +- unittests/unittests_cli/build_test_case.py | 8 +- unittests/unittests_cli/generate_test_case.py | 8 +- unittests/unittests_cli/install_test_case.py | 2 +- unittests/unittests_cli/new_test_case.py | 10 +- unittests/unittests_cli/publish_test_case.py | 10 +- unittests/unittests_cli/remove_test_case.py | 6 +- unittests/unittests_cli/run_test_case.py | 22 +- unittests/unittests_cli/start_test_case.py | 12 +- .../unittests_cli/uninstall_test_case.py | 2 +- unittests/unittests_cli/update_test_case.py | 2 +- .../configuration/environment_test_case.py | 16 +- .../pipes/bool_pipe_test_case.py | 6 +- .../pipes/ip_address_pipe_test_case.py | 16 +- .../pipes/version_pipe_test_case.py | 16 - .../unittests_core/utils/string_test_case.py | 28 +- 134 files changed, 366 insertions(+), 2233 deletions(-) delete mode 100644 src/cpl-core/cpl/core/configuration/argument_abc.py delete mode 100644 src/cpl-core/cpl/core/configuration/argument_builder.py delete mode 100644 src/cpl-core/cpl/core/configuration/argument_executable_abc.py delete mode 100644 src/cpl-core/cpl/core/configuration/argument_type_enum.py delete mode 100644 src/cpl-core/cpl/core/configuration/configuration_abc.py delete mode 100644 src/cpl-core/cpl/core/configuration/configuration_variable_name_enum.py delete mode 100644 src/cpl-core/cpl/core/configuration/executable_argument.py delete mode 100644 src/cpl-core/cpl/core/configuration/flag_argument.py delete mode 100644 src/cpl-core/cpl/core/configuration/validator_abc.py delete mode 100644 src/cpl-core/cpl/core/configuration/variable_argument.py delete mode 100644 src/cpl-core/cpl/core/environment/application_environment.py delete mode 100644 src/cpl-core/cpl/core/environment/application_environment_abc.py rename src/cpl-core/cpl/core/environment/{environment_name_enum.py => environment_enum.py} (80%) delete mode 100644 src/cpl-core/cpl/core/pipes/version_pipe.py create mode 100644 src/cpl-core/cpl/core/utils/b64.py delete mode 100644 tests/custom/general/src/general/arguments/__init__.py delete mode 100644 tests/custom/general/src/general/arguments/generate_argument.py delete mode 100644 tests/custom/general/src/general/arguments/install_argument.py delete mode 100644 tests/custom/general/src/general/parameter_startup.py delete mode 100644 tests/generated/simple-app/LICENSE delete mode 100644 tests/generated/simple-app/README.md delete mode 100644 tests/generated/simple-app/appsettings.json delete mode 100644 tests/generated/simple-app/cpl-workspace.json delete mode 100644 tests/generated/simple-app/cpl.json delete mode 100644 tests/generated/simple-app/src/application.py delete mode 100644 tests/generated/simple-app/src/main.py delete mode 100644 tests/generated/simple-app/src/simple_app/__init__.py delete mode 100644 tests/generated/simple-app/src/simple_app/application.py delete mode 100644 tests/generated/simple-app/src/simple_app/main.py delete mode 100644 tests/generated/simple-app/src/simple_app/simple-app.json delete mode 100644 tests/generated/simple-app/src/tests/__init__.py delete mode 100644 tests/generated/simple-console/LICENSE delete mode 100644 tests/generated/simple-console/README.md delete mode 100644 tests/generated/simple-console/appsettings.json delete mode 100644 tests/generated/simple-console/cpl-workspace.json delete mode 100644 tests/generated/simple-console/cpl.json delete mode 100644 tests/generated/simple-console/src/main.py delete mode 100644 tests/generated/simple-console/src/simple_console/__init__.py delete mode 100644 tests/generated/simple-console/src/simple_console/main.py delete mode 100644 tests/generated/simple-console/src/simple_console/simple-console.json delete mode 100644 tests/generated/simple-console/src/tests/__init__.py delete mode 100644 tests/generated/simple-di/LICENSE delete mode 100644 tests/generated/simple-di/README.md delete mode 100644 tests/generated/simple-di/appsettings.json delete mode 100644 tests/generated/simple-di/cpl-workspace.json delete mode 100644 tests/generated/simple-di/cpl.json delete mode 100644 tests/generated/simple-di/src/main.py delete mode 100644 tests/generated/simple-di/src/simple_di/__init__.py delete mode 100644 tests/generated/simple-di/src/simple_di/main.py delete mode 100644 tests/generated/simple-di/src/simple_di/simple-di.json delete mode 100644 tests/generated/simple-di/src/tests/__init__.py delete mode 100644 tests/generated/simple-startup-app/LICENSE delete mode 100644 tests/generated/simple-startup-app/README.md delete mode 100644 tests/generated/simple-startup-app/appsettings.json delete mode 100644 tests/generated/simple-startup-app/cpl-workspace.json delete mode 100644 tests/generated/simple-startup-app/src/simple_startup_app/__init__.py delete mode 100644 tests/generated/simple-startup-app/src/simple_startup_app/application.py delete mode 100644 tests/generated/simple-startup-app/src/simple_startup_app/main.py delete mode 100644 tests/generated/simple-startup-app/src/simple_startup_app/simple-startup-app.json delete mode 100644 tests/generated/simple-startup-app/src/simple_startup_app/startup.py delete mode 100644 tests/generated/simple-startup-app/src/tests/__init__.py delete mode 100644 tests/generated/startup-app/LICENSE delete mode 100644 tests/generated/startup-app/README.md delete mode 100644 tests/generated/startup-app/cpl.json delete mode 100644 tests/generated/startup-app/src/application.py delete mode 100644 tests/generated/startup-app/src/main.py delete mode 100644 tests/generated/startup-app/src/startup.py delete mode 100644 tests/generated/startup-app/src/tests/__init__.py delete mode 100644 tools/set_pip_urls/__init__.py delete mode 100644 tools/set_pip_urls/application.py delete mode 100644 tools/set_pip_urls/appsettings.json delete mode 100644 tools/set_pip_urls/main.py delete mode 100644 tools/set_pip_urls/pip_settings.py delete mode 100644 tools/set_pip_urls/set-pip-urls.json delete mode 100644 tools/set_pip_urls/startup.py delete mode 100644 tools/set_version/__init__.py delete mode 100644 tools/set_version/application.py delete mode 100644 tools/set_version/git_service.py delete mode 100644 tools/set_version/main.py delete mode 100644 tools/set_version/set-version.json delete mode 100644 tools/set_version/startup.py delete mode 100644 tools/set_version/version_setter_service.py delete mode 100644 unittests/unittests_core/pipes/version_pipe_test_case.py diff --git a/src/cpl-core/cpl/core/application/application_abc.py b/src/cpl-core/cpl/core/application/application_abc.py index 087d8b48..0ca27398 100644 --- a/src/cpl-core/cpl/core/application/application_abc.py +++ b/src/cpl-core/cpl/core/application/application_abc.py @@ -1,10 +1,10 @@ from abc import ABC, abstractmethod from typing import Optional -from cpl.core.configuration.configuration_abc import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.console.console import Console from cpl.core.dependency_injection.service_provider_abc import ServiceProviderABC -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC +from cpl.core.environment import Environment class ApplicationABC(ABC): @@ -18,9 +18,7 @@ class ApplicationABC(ABC): """ @abstractmethod - def __init__(self, config: ConfigurationABC, services: ServiceProviderABC): - self._configuration: Optional[ConfigurationABC] = config - self._environment: Optional[ApplicationEnvironmentABC] = self._configuration.environment + def __init__(self, services: ServiceProviderABC): self._services: Optional[ServiceProviderABC] = services def run(self): diff --git a/src/cpl-core/cpl/core/application/application_builder.py b/src/cpl-core/cpl/core/application/application_builder.py index 90bebfdf..3583b023 100644 --- a/src/cpl-core/cpl/core/application/application_builder.py +++ b/src/cpl-core/cpl/core/application/application_builder.py @@ -10,6 +10,7 @@ from cpl.core.application.startup_abc import StartupABC from cpl.core.application.startup_extension_abc import StartupExtensionABC from cpl.core.configuration.configuration import Configuration from cpl.core.dependency_injection.service_collection import ServiceCollection +from cpl.core.environment import Environment class ApplicationBuilder(ApplicationBuilderABC): @@ -25,9 +26,7 @@ class ApplicationBuilder(ApplicationBuilderABC): self._app = app self._startup: Optional[StartupABC | AsyncStartupABC] = None - self._configuration = Configuration() - self._environment = self._configuration.environment - self._services = ServiceCollection(self._configuration) + self._services = ServiceCollection() self._app_extensions: list[Type[ApplicationExtensionABC | AsyncApplicationExtensionABC]] = [] self._startup_extensions: list[Type[StartupExtensionABC | AsyncStartupABC]] = [] @@ -37,11 +36,18 @@ class ApplicationBuilder(ApplicationBuilderABC): return self def use_extension( - self, extension: Type[ApplicationExtensionABC | AsyncApplicationExtensionABC | StartupExtensionABC | AsyncStartupExtensionABC] + self, + extension: Type[ + ApplicationExtensionABC | AsyncApplicationExtensionABC | StartupExtensionABC | AsyncStartupExtensionABC + ], ) -> "ApplicationBuilder": - if (issubclass(extension, ApplicationExtensionABC) or issubclass(extension, AsyncApplicationExtensionABC)) and extension not in self._app_extensions: + if ( + issubclass(extension, ApplicationExtensionABC) or issubclass(extension, AsyncApplicationExtensionABC) + ) and extension not in self._app_extensions: self._app_extensions.append(extension) - elif (issubclass(extension, StartupExtensionABC) or issubclass(extension, AsyncStartupExtensionABC)) and extension not in self._startup_extensions: + elif ( + issubclass(extension, StartupExtensionABC) or issubclass(extension, AsyncStartupExtensionABC) + ) and extension not in self._startup_extensions: self._startup_extensions.append(extension) return self @@ -49,43 +55,43 @@ class ApplicationBuilder(ApplicationBuilderABC): def _build_startup(self): for ex in self._startup_extensions: extension = ex() - extension.configure_configuration(self._configuration, self._environment) - extension.configure_services(self._services, self._environment) + extension.configure_configuration(Configuration, Environment) + extension.configure_services(self._services, Environment) if self._startup is not None: - self._startup.configure_configuration(self._configuration, self._environment) - self._startup.configure_services(self._services, self._environment) + self._startup.configure_configuration(Configuration, Environment) + self._startup.configure_services(self._services, Environment) async def _build_async_startup(self): for ex in self._startup_extensions: extension = ex() - await extension.configure_configuration(self._configuration, self._environment) - await extension.configure_services(self._services, self._environment) + await extension.configure_configuration(Configuration, Environment) + await extension.configure_services(self._services, Environment) if self._startup is not None: - await self._startup.configure_configuration(self._configuration, self._environment) - await self._startup.configure_services(self._services, self._environment) + await self._startup.configure_configuration(Configuration, Environment) + await self._startup.configure_services(self._services, Environment) def build(self) -> ApplicationABC: self._build_startup() - config = self._configuration + config = Configuration services = self._services.build_service_provider() for ex in self._app_extensions: extension = ex() extension.run(config, services) - return self._app(config, services) + return self._app(services) async def build_async(self) -> ApplicationABC: await self._build_async_startup() - config = self._configuration + config = Configuration services = self._services.build_service_provider() for ex in self._app_extensions: extension = ex() await extension.run(config, services) - return self._app(config, services) + return self._app(services) diff --git a/src/cpl-core/cpl/core/application/application_extension_abc.py b/src/cpl-core/cpl/core/application/application_extension_abc.py index 71d46c70..111653a2 100644 --- a/src/cpl-core/cpl/core/application/application_extension_abc.py +++ b/src/cpl-core/cpl/core/application/application_extension_abc.py @@ -1,6 +1,6 @@ from abc import ABC, abstractmethod -from cpl.core.configuration import ConfigurationABC +from cpl.core.configuration.configuration import Configuration from cpl.core.dependency_injection import ServiceProviderABC @@ -10,5 +10,5 @@ class ApplicationExtensionABC(ABC): pass @abstractmethod - def run(self, config: ConfigurationABC, services: ServiceProviderABC): + def run(self, config: Configuration, services: ServiceProviderABC): pass diff --git a/src/cpl-core/cpl/core/application/async_application_extension_abc.py b/src/cpl-core/cpl/core/application/async_application_extension_abc.py index 4fbc1935..67378a08 100644 --- a/src/cpl-core/cpl/core/application/async_application_extension_abc.py +++ b/src/cpl-core/cpl/core/application/async_application_extension_abc.py @@ -1,6 +1,6 @@ from abc import ABC, abstractmethod -from cpl.core.configuration import ConfigurationABC +from cpl.core.configuration.configuration import Configuration from cpl.core.dependency_injection import ServiceProviderABC @@ -10,5 +10,5 @@ class AsyncApplicationExtensionABC(ABC): pass @abstractmethod - async def run(self, config: ConfigurationABC, services: ServiceProviderABC): + async def run(self, config: Configuration, services: ServiceProviderABC): pass diff --git a/src/cpl-core/cpl/core/application/async_startup_abc.py b/src/cpl-core/cpl/core/application/async_startup_abc.py index e8589dc5..2bbc7fac 100644 --- a/src/cpl-core/cpl/core/application/async_startup_abc.py +++ b/src/cpl-core/cpl/core/application/async_startup_abc.py @@ -1,9 +1,6 @@ from abc import ABC, abstractmethod -from cpl.core.configuration.configuration_abc import ConfigurationABC from cpl.core.dependency_injection.service_collection_abc import ServiceCollectionABC -from cpl.core.dependency_injection.service_provider_abc import ServiceProviderABC -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC class AsyncStartupABC(ABC): @@ -14,19 +11,13 @@ class AsyncStartupABC(ABC): pass @abstractmethod - async def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): - r"""Creates configuration of application - - Parameter: - config: :class:`cpl.core.configuration.configuration_abc.ConfigurationABC` - env: :class:`cpl.core.environment.application_environment_abc` - """ + async def configure_configuration(self): + r"""Creates configuration of application""" @abstractmethod - async def configure_services(self, service: ServiceCollectionABC, env: ApplicationEnvironmentABC): + async def configure_services(self, service: ServiceCollectionABC): r"""Creates service provider Parameter: services: :class:`cpl.core.dependency_injection.service_collection_abc` - env: :class:`cpl.core.environment.application_environment_abc` """ diff --git a/src/cpl-core/cpl/core/application/async_startup_extension_abc.py b/src/cpl-core/cpl/core/application/async_startup_extension_abc.py index 0fcbfa45..861c8b2a 100644 --- a/src/cpl-core/cpl/core/application/async_startup_extension_abc.py +++ b/src/cpl-core/cpl/core/application/async_startup_extension_abc.py @@ -1,8 +1,8 @@ from abc import ABC, abstractmethod -from cpl.core.configuration.configuration_abc import ConfigurationABC +from cpl.core.configuration.configuration import Configuration from cpl.core.dependency_injection.service_collection_abc import ServiceCollectionABC -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC +from cpl.core.environment.environment import Environment class AsyncStartupExtensionABC(ABC): @@ -13,16 +13,16 @@ class AsyncStartupExtensionABC(ABC): pass @abstractmethod - async def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): + async def configure_configuration(self, config: Configuration, env: Environment): r"""Creates configuration of application Parameter: - config: :class:`cpl.core.configuration.configuration_abc.ConfigurationABC` + config: :class:`cpl.core.configuration.configuration_abc.Configuration` env: :class:`cpl.core.environment.application_environment_abc` """ @abstractmethod - async def configure_services(self, service: ServiceCollectionABC, env: ApplicationEnvironmentABC): + async def configure_services(self, service: ServiceCollectionABC, env: Environment): r"""Creates service provider Parameter: diff --git a/src/cpl-core/cpl/core/application/startup_abc.py b/src/cpl-core/cpl/core/application/startup_abc.py index 54dca95b..cbad5f19 100644 --- a/src/cpl-core/cpl/core/application/startup_abc.py +++ b/src/cpl-core/cpl/core/application/startup_abc.py @@ -1,9 +1,8 @@ from abc import ABC, abstractmethod -from cpl.core.configuration.configuration_abc import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.dependency_injection.service_collection_abc import ServiceCollectionABC -from cpl.core.dependency_injection.service_provider_abc import ServiceProviderABC -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC +from cpl.core.environment import Environment class StartupABC(ABC): @@ -14,7 +13,7 @@ class StartupABC(ABC): pass @abstractmethod - def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): + def configure_configuration(self, config: Configuration, env: Environment): r"""Creates configuration of application Parameter: @@ -23,7 +22,7 @@ class StartupABC(ABC): """ @abstractmethod - def configure_services(self, service: ServiceCollectionABC, env: ApplicationEnvironmentABC): + def configure_services(self, service: ServiceCollectionABC, env: Environment): r"""Creates service provider Parameter: diff --git a/src/cpl-core/cpl/core/application/startup_extension_abc.py b/src/cpl-core/cpl/core/application/startup_extension_abc.py index 08760228..9d2db53e 100644 --- a/src/cpl-core/cpl/core/application/startup_extension_abc.py +++ b/src/cpl-core/cpl/core/application/startup_extension_abc.py @@ -1,8 +1,10 @@ from abc import ABC, abstractmethod -from cpl.core.configuration.configuration_abc import ConfigurationABC + +from cpl.core.configuration import Configuration from cpl.core.dependency_injection.service_collection_abc import ServiceCollectionABC -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC + +from cpl.core.environment.environment import Environment class StartupExtensionABC(ABC): @@ -13,7 +15,7 @@ class StartupExtensionABC(ABC): pass @abstractmethod - def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): + def configure_configuration(self, config: Configuration, env: Environment): r"""Creates configuration of application Parameter: @@ -22,7 +24,7 @@ class StartupExtensionABC(ABC): """ @abstractmethod - def configure_services(self, service: ServiceCollectionABC, env: ApplicationEnvironmentABC): + def configure_services(self, service: ServiceCollectionABC, env: Environment): r"""Creates service provider Parameter: diff --git a/src/cpl-core/cpl/core/configuration/__init__.py b/src/cpl-core/cpl/core/configuration/__init__.py index 7d525c43..c78c3b0e 100644 --- a/src/cpl-core/cpl/core/configuration/__init__.py +++ b/src/cpl-core/cpl/core/configuration/__init__.py @@ -1,12 +1,2 @@ -from .argument_abc import ArgumentABC -from .argument_builder import ArgumentBuilder -from .argument_executable_abc import ArgumentExecutableABC -from .argument_type_enum import ArgumentTypeEnum from .configuration import Configuration -from .configuration_abc import ConfigurationABC from .configuration_model_abc import ConfigurationModelABC -from .configuration_variable_name_enum import ConfigurationVariableNameEnum -from .executable_argument import ExecutableArgument -from .flag_argument import FlagArgument -from .validator_abc import ValidatorABC -from .variable_argument import VariableArgument diff --git a/src/cpl-core/cpl/core/configuration/argument_abc.py b/src/cpl-core/cpl/core/configuration/argument_abc.py deleted file mode 100644 index 588ff97b..00000000 --- a/src/cpl-core/cpl/core/configuration/argument_abc.py +++ /dev/null @@ -1,64 +0,0 @@ -from abc import ABC, abstractmethod - -from cpl.core.configuration.argument_type_enum import ArgumentTypeEnum - - -class ArgumentABC(ABC): - @abstractmethod - def __init__( - self, - token: str, - name: str, - aliases: list[str], - prevent_next_executable: bool = False, - console_arguments: list["ArgumentABC"] = None, - ): - r"""Representation of an console argument - - Parameter: - token: :class:`str` - name: :class:`str` - aliases: list[:class:`str`] - console_arguments: List[:class:`cpl.core.configuration.console_argument.ConsoleArgument`] - """ - self._token = token - self._name = name - self._aliases = aliases - self._prevent_next_executable = prevent_next_executable - self._console_arguments = console_arguments if console_arguments is not None else [] - - @property - def token(self) -> str: - return self._token - - @property - def name(self) -> str: - return self._name - - @property - def aliases(self) -> list[str]: - return self._aliases - - @property - def prevent_next_executable(self) -> bool: - return self._prevent_next_executable - - @property - def console_arguments(self) -> list["ArgumentABC"]: - return self._console_arguments - - def add_console_argument(self, arg_type: ArgumentTypeEnum, *args, **kwargs) -> "ArgumentABC": - r"""Creates and adds a console argument to known console arguments - - Parameter: - arg_type: :class:`str` - Specifies the specific type of the argument - - Returns: - self :class:`cpl.core.configuration.console_argument.ConsoleArgument` not created argument! - """ - from cpl.core.configuration.argument_builder import ArgumentBuilder - - argument = ArgumentBuilder.build_argument(arg_type, *args, *kwargs) - self._console_arguments.append(argument) - return self diff --git a/src/cpl-core/cpl/core/configuration/argument_builder.py b/src/cpl-core/cpl/core/configuration/argument_builder.py deleted file mode 100644 index 67b72d13..00000000 --- a/src/cpl-core/cpl/core/configuration/argument_builder.py +++ /dev/null @@ -1,30 +0,0 @@ -from typing import Union - -from cpl.core.configuration.argument_type_enum import ArgumentTypeEnum -from cpl.core.configuration.executable_argument import ExecutableArgument -from cpl.core.configuration.flag_argument import FlagArgument -from cpl.core.configuration.variable_argument import VariableArgument -from cpl.core.console import Console - - -class ArgumentBuilder: - @staticmethod - def build_argument( - arg_type: ArgumentTypeEnum, *args, **kwargs - ) -> Union[ExecutableArgument, FlagArgument, VariableArgument]: - argument = None - try: - match arg_type: - case ArgumentTypeEnum.Flag: - argument = FlagArgument(*args, **kwargs) - case ArgumentTypeEnum.Executable: - argument = ExecutableArgument(*args, **kwargs) - case ArgumentTypeEnum.Variable: - argument = VariableArgument(*args, **kwargs) - case _: - Console.error("Invalid argument type") - Console.close() - except TypeError as e: - Console.error(str(e)) - Console.close() - return argument diff --git a/src/cpl-core/cpl/core/configuration/argument_executable_abc.py b/src/cpl-core/cpl/core/configuration/argument_executable_abc.py deleted file mode 100644 index 99546498..00000000 --- a/src/cpl-core/cpl/core/configuration/argument_executable_abc.py +++ /dev/null @@ -1,11 +0,0 @@ -from abc import ABC, abstractmethod - - -class ArgumentExecutableABC(ABC): - @abstractmethod - def __init__(self): - pass - - @abstractmethod - def run(self, args: list[str]): - pass diff --git a/src/cpl-core/cpl/core/configuration/argument_type_enum.py b/src/cpl-core/cpl/core/configuration/argument_type_enum.py deleted file mode 100644 index 08972534..00000000 --- a/src/cpl-core/cpl/core/configuration/argument_type_enum.py +++ /dev/null @@ -1,7 +0,0 @@ -from enum import Enum - - -class ArgumentTypeEnum(Enum): - Flag = 0 - Executable = 1 - Variable = 3 diff --git a/src/cpl-core/cpl/core/configuration/configuration.py b/src/cpl-core/cpl/core/configuration/configuration.py index b68b82ea..93e8bed9 100644 --- a/src/cpl-core/cpl/core/configuration/configuration.py +++ b/src/cpl-core/cpl/core/configuration/configuration.py @@ -1,65 +1,19 @@ +import inspect import json import os import sys -import traceback -from collections.abc import Callable -from typing import Union, Optional +from typing import Any -from cpl.core.configuration.argument_abc import ArgumentABC -from cpl.core.configuration.argument_builder import ArgumentBuilder -from cpl.core.configuration.argument_type_enum import ArgumentTypeEnum -from cpl.core.configuration.configuration_abc import ConfigurationABC from cpl.core.configuration.configuration_model_abc import ConfigurationModelABC -from cpl.core.configuration.configuration_variable_name_enum import ( - ConfigurationVariableNameEnum, -) -from cpl.core.configuration.executable_argument import ExecutableArgument -from cpl.core.configuration.flag_argument import FlagArgument -from cpl.core.configuration.variable_argument import VariableArgument from cpl.core.console.console import Console from cpl.core.console.foreground_color_enum import ForegroundColorEnum -from cpl.core.dependency_injection.service_provider_abc import ServiceProviderABC -from cpl.core.environment.application_environment import ApplicationEnvironment -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC -from cpl.core.environment.environment_name_enum import EnvironmentNameEnum -from cpl.core.typing import T, R +from cpl.core.environment.environment import Environment +from cpl.core.typing import D, T from cpl.core.utils.json_processor import JSONProcessor -class Configuration(ConfigurationABC): - def __init__(self): - r"""Representation of configuration""" - ConfigurationABC.__init__(self) - - self._application_environment = ApplicationEnvironment() - self._config: dict[Union[type, str], Union[ConfigurationModelABC, str]] = {} - - self._argument_types: list[ArgumentABC] = [] - self._additional_arguments: list[str] = [] - - self._argument_error_function: Optional[Callable] = None - - self._handled_args = [] - - @property - def environment(self) -> ApplicationEnvironmentABC: - return self._application_environment - - @property - def additional_arguments(self) -> list[str]: - return self._additional_arguments - - @property - def argument_error_function(self) -> Optional[Callable]: - return self._argument_error_function - - @argument_error_function.setter - def argument_error_function(self, argument_error_function: Callable): - self._argument_error_function = argument_error_function - - @property - def arguments(self) -> list[ArgumentABC]: - return self._argument_types +class Configuration: + _config = {} @staticmethod def _print_info(message: str): @@ -72,7 +26,7 @@ class Configuration(ConfigurationABC): Info message """ Console.set_foreground_color(ForegroundColorEnum.green) - Console.write_line(f"[CONF] {message}") + Console.write_line(f"[CONFIG] {message}") Console.set_foreground_color(ForegroundColorEnum.default) @staticmethod @@ -86,7 +40,7 @@ class Configuration(ConfigurationABC): Warning message """ Console.set_foreground_color(ForegroundColorEnum.yellow) - Console.write_line(f"[CONF] {message}") + Console.write_line(f"[CONFIG] {message}") Console.set_foreground_color(ForegroundColorEnum.default) @staticmethod @@ -100,31 +54,11 @@ class Configuration(ConfigurationABC): Error message """ Console.set_foreground_color(ForegroundColorEnum.red) - Console.write_line(f"[CONF] {message}") + Console.write_line(f"[CONFIG] {message}") Console.set_foreground_color(ForegroundColorEnum.default) - def _set_variable(self, name: str, value: any): - r"""Sets variable to given value - - Parameter: - name: :class:`str` - Name of the variable - value: :class:`any` - Value of the variable - """ - if name == ConfigurationVariableNameEnum.environment.value: - self._application_environment.environment_name = EnvironmentNameEnum(value) - - elif name == ConfigurationVariableNameEnum.name.value: - self._application_environment.application_name = value - - elif name == ConfigurationVariableNameEnum.customer.value: - self._application_environment.customer = value - - else: - self._config[name] = value - - def _load_json_file(self, file: str, output: bool) -> dict: + @classmethod + def _load_json_file(cls, file: str, output: bool) -> dict: r"""Reads the json file Parameter: @@ -142,90 +76,19 @@ class Configuration(ConfigurationABC): # load json json_cfg = json.load(cfg) if output: - self._print_info(f"Loaded config file: {file}") + cls._print_info(f"Loaded config file: {file}") return json_cfg except Exception as e: - self._print_error(f"Cannot load config file: {file}! -> {e}") + cls._print_error(f"Cannot load config file: {file}! -> {e}") return {} - def _parse_arguments( - self, - executables: list[ArgumentABC], - arg_list: list[str], - args_types: list[ArgumentABC], - ): - for i in range(0, len(arg_list)): - arg_str = arg_list[i] - for n in range(0, len(args_types)): - arg = args_types[n] - arg_str_without_token = arg_str - if arg.token != "" and arg.token in arg_str: - arg_str_without_token = arg_str.split(arg.token)[1] - - # executable - if isinstance(arg, ExecutableArgument): - if ( - arg_str.startswith(arg.token) - and arg_str_without_token == arg.name - or arg_str_without_token in arg.aliases - ): - executables.append(arg) - self._handled_args.append(arg_str) - self._parse_arguments(executables, arg_list[i + 1 :], arg.console_arguments) - - # variables - elif isinstance(arg, VariableArgument): - arg_str_without_value = arg_str_without_token - if arg.value_token in arg_str_without_value: - arg_str_without_value = arg_str_without_token.split(arg.value_token)[0] - - if ( - arg_str.startswith(arg.token) - and arg_str_without_value == arg.name - or arg_str_without_value in arg.aliases - ): - if arg.value_token != " ": - value = arg_str_without_token.split(arg.value_token)[1] - else: - value = arg_list[i + 1] - self._set_variable(arg.name, value) - self._handled_args.append(arg_str) - self._handled_args.append(value) - self._parse_arguments(executables, arg_list[i + 1 :], arg.console_arguments) - - # flags - elif isinstance(arg, FlagArgument): - if ( - arg_str.startswith(arg.token) - and arg_str_without_token == arg.name - or arg_str_without_token in arg.aliases - ): - if arg_str in self._additional_arguments: - self._additional_arguments.remove(arg_str) - self._additional_arguments.append(arg.name) - self._handled_args.append(arg_str) - self._parse_arguments(executables, arg_list[i + 1 :], arg.console_arguments) - - # add left over values to args - if arg_str not in self._additional_arguments and arg_str not in self._handled_args: - self._additional_arguments.append(arg_str) - - def add_environment_variables(self, prefix: str): - for env_var in os.environ.keys(): - if not env_var.startswith(prefix): - continue - - self._set_variable(env_var.replace(prefix, ""), os.environ[env_var]) - - def add_console_argument(self, argument: ArgumentABC): - self._argument_types.append(argument) - - def add_json_file(self, name: str, optional: bool = None, output: bool = True, path: str = None): + @classmethod + def add_json_file(cls, name: str, optional: bool = None, output: bool = True, path: str = None): if os.path.isabs(name): file_path = name else: - path_root = self._application_environment.working_directory + path_root = Environment.get_cwd() if path is not None: path_root = path @@ -237,16 +100,16 @@ class Configuration(ConfigurationABC): if not os.path.isfile(file_path): if optional is not True: if output: - self._print_error(f"File not found: {file_path}") + cls._print_error(f"File not found: {file_path}") sys.exit() if output: - self._print_warn(__name__, f"Not Loaded config file: {file_path}") + cls._print_warn(f"Not Loaded config file: {file_path}") return None - config_from_file = self._load_json_file(file_path, output) + config_from_file = cls._load_json_file(file_path, output) for sub in ConfigurationModelABC.__subclasses__(): for key, value in config_from_file.items(): if sub.__name__ != key and sub.__name__.replace("Settings", "") != key: @@ -265,94 +128,18 @@ class Configuration(ConfigurationABC): else: configuration = JSONProcessor.process(sub, value) - self.add_configuration(sub, configuration) + cls.set(sub, configuration) - def add_configuration(self, key_type: T, value: any): - self._config[key_type] = value + @classmethod + def set(cls, key: Any, value: T): + if inspect.isclass(key): + key = key.__name__ - def create_console_argument( - self, - arg_type: ArgumentTypeEnum, - token: str, - name: str, - aliases: list[str], - *args, - **kwargs, - ) -> ArgumentABC: - argument = ArgumentBuilder.build_argument(arg_type, token, name, aliases, *args, **kwargs) - self._argument_types.append(argument) - return argument + cls._config[key] = value - def for_each_argument(self, call: Callable): - for arg in self._argument_types: - call(arg) + @classmethod + def get(cls, key: Any, default: D = None) -> T | D: + if inspect.isclass(key): + key = key.__name__ - def get_configuration(self, search_type: T) -> Optional[R]: - if type(search_type) is str: - if search_type == ConfigurationVariableNameEnum.environment.value: - return self._application_environment.environment_name - - elif search_type == ConfigurationVariableNameEnum.name.value: - return self._application_environment.application_name - - elif search_type == ConfigurationVariableNameEnum.customer.value: - return self._application_environment.customer - - if search_type not in self._config: - return None - - for config_model in self._config: - if config_model == search_type: - return self._config[config_model] - - def parse_console_arguments(self, services: ServiceProviderABC, error: bool = None) -> bool: - # sets environment variables as possible arguments as: --VAR=VALUE - for arg_name in ConfigurationVariableNameEnum.to_list(): - self.add_console_argument(VariableArgument("--", str(arg_name).upper(), [str(arg_name).lower()], "=")) - - success = False - try: - arg_list = sys.argv[1:] - executables: list[ExecutableArgument] = [] - self._parse_arguments(executables, arg_list, self._argument_types) - except Exception: - Console.error("An error occurred while parsing arguments.", traceback.format_exc()) - sys.exit() - - try: - prevent = False - for exe in executables: - if prevent: - continue - - if exe.validators is not None: - abort = False - for validator_type in exe.validators: - validator = services.get_service(validator_type) - result = validator.validate() - abort = not result - if abort: - break - - if abort: - sys.exit() - - cmd = services.get_service(exe.executable_type) - self._handle_pre_or_post_executables(True, exe, services) - self._set_variable("ACTIVE_EXECUTABLE", exe.name) - args = self.get_configuration("ARGS") - if args is not None: - for arg in args.split(" "): - if arg == "": - continue - self._additional_arguments.append(arg) - - cmd.run(self._additional_arguments) - self._handle_pre_or_post_executables(False, exe, services) - prevent = exe.prevent_next_executable - success = True - except Exception: - Console.error("An error occurred while executing arguments.", traceback.format_exc()) - sys.exit() - - return success + return cls._config.get(key, default) diff --git a/src/cpl-core/cpl/core/configuration/configuration_abc.py b/src/cpl-core/cpl/core/configuration/configuration_abc.py deleted file mode 100644 index aabc2a53..00000000 --- a/src/cpl-core/cpl/core/configuration/configuration_abc.py +++ /dev/null @@ -1,140 +0,0 @@ -from abc import abstractmethod, ABC -from collections.abc import Callable -from typing import Optional - -from cpl.core.configuration.argument_abc import ArgumentABC -from cpl.core.configuration.argument_type_enum import ArgumentTypeEnum -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC -from cpl.core.typing import T, R - - -class ConfigurationABC(ABC): - @abstractmethod - def __init__(self): - r"""ABC for the :class:`cpl.core.configuration.configuration.Configuration`""" - - @property - @abstractmethod - def environment(self) -> ApplicationEnvironmentABC: - pass - - @property - @abstractmethod - def additional_arguments(self) -> list[str]: - pass - - @property - @abstractmethod - def argument_error_function(self) -> Optional[Callable]: - pass - - @argument_error_function.setter - @abstractmethod - def argument_error_function(self, argument_error_function: Callable): - pass - - @property - @abstractmethod - def arguments(self) -> list[ArgumentABC]: - pass - - @abstractmethod - def add_environment_variables(self, prefix: str): - r"""Reads the environment variables - - Parameter: - prefix: :class:`str` - Prefix of the variables - """ - - @abstractmethod - def add_console_argument(self, argument: ArgumentABC): - r"""Adds console argument to known console arguments - - Parameter: - argument: :class:`cpl.core.configuration.console_argument.ConsoleArgumentABC` - Specifies the console argument - """ - - @abstractmethod - def add_json_file(self, name: str, optional: bool = None, output: bool = True, path: str = None): - r"""Reads and saves settings from given json file - - Parameter: - name: :class:`str` - Name of the file - optional: :class:`str` - Specifies whether an error should occur if the file was not found - output: :class:`bool` - Specifies whether an output should take place - path: :class:`str` - Path in which the file should be stored - """ - - @abstractmethod - def add_configuration(self, key_type: T, value: any): - r"""Add configuration object - - Parameter: - key_type: :class:`cpl.core.type.T` - Type of the value - value: any - Object of the value - """ - - @abstractmethod - def create_console_argument( - self, arg_type: ArgumentTypeEnum, token: str, name: str, aliases: list[str], *args, **kwargs - ) -> ArgumentABC: - r"""Creates and adds a console argument to known console arguments - - Parameter: - token: :class:`str` - Specifies optional beginning of argument - name :class:`str` - Specifies name of argument - aliases list[:class:`str`] - Specifies possible aliases of name - value_token :class:`str` - Specifies were the value begins - is_value_token_optional :class:`bool` - Specifies if values are optional - runnable: :class:`cpl.core.configuration.console_argument.ConsoleArgumentABC` - Specifies class to run when called if value is not None - - Returns: - Object of :class:`cpl.core.configuration.console_argument.ConsoleArgumentABC` - """ - - @abstractmethod - def for_each_argument(self, call: Callable): - r"""Iterates through all arguments and calls the call function - - Parameter: - call: :class:`Callable` - Call for each argument - """ - - @abstractmethod - def get_configuration(self, search_type: T) -> Optional[R]: - r"""Returns value from configuration by given type - - Parameter: - search_type: :class:`cpl.core.type.T` - Type to search for - - Returns: - Object of Union[:class:`str`, :class:`cpl.core.configuration.configuration_model_abc.ConfigurationModelABC`] - """ - - @abstractmethod - def parse_console_arguments(self, services: "ServiceProviderABC", error: bool = None) -> bool: - r"""Reads the console arguments - - Parameter: - error: :class:`bool` - Defines is invalid argument error will be shown or not - - Returns: - Bool to specify if executables were executed or not. - """ diff --git a/src/cpl-core/cpl/core/configuration/configuration_variable_name_enum.py b/src/cpl-core/cpl/core/configuration/configuration_variable_name_enum.py deleted file mode 100644 index 23a36206..00000000 --- a/src/cpl-core/cpl/core/configuration/configuration_variable_name_enum.py +++ /dev/null @@ -1,11 +0,0 @@ -from enum import Enum - - -class ConfigurationVariableNameEnum(Enum): - environment = "ENVIRONMENT" - name = "NAME" - customer = "CUSTOMER" - - @staticmethod - def to_list(): - return [var.value for var in ConfigurationVariableNameEnum] diff --git a/src/cpl-core/cpl/core/configuration/executable_argument.py b/src/cpl-core/cpl/core/configuration/executable_argument.py deleted file mode 100644 index 524fc7ec..00000000 --- a/src/cpl-core/cpl/core/configuration/executable_argument.py +++ /dev/null @@ -1,40 +0,0 @@ -from typing import Type, Optional - -from cpl.core.configuration.argument_executable_abc import ArgumentExecutableABC -from cpl.core.configuration.argument_abc import ArgumentABC -from cpl.core.configuration.validator_abc import ValidatorABC - - -class ExecutableArgument(ArgumentABC): - def __init__( - self, - token: str, - name: str, - aliases: list[str], - executable: Type[ArgumentExecutableABC], - prevent_next_executable: bool = False, - validators: list[Type[ValidatorABC]] = None, - console_arguments: list["ArgumentABC"] = None, - ): - self._executable_type = executable - self._validators = validators - self._executable: Optional[ArgumentExecutableABC] = None - - ArgumentABC.__init__(self, token, name, aliases, prevent_next_executable, console_arguments) - - @property - def executable_type(self) -> type: - return self._executable_type - - def set_executable(self, executable: ArgumentExecutableABC): - self._executable = executable - - @property - def validators(self) -> list[Type[ValidatorABC]]: - return self._validators - - def run(self, args: list[str]): - r"""Executes runnable if exists""" - if self._executable is None: - return - self._executable.execute(args) diff --git a/src/cpl-core/cpl/core/configuration/flag_argument.py b/src/cpl-core/cpl/core/configuration/flag_argument.py deleted file mode 100644 index a5d89f85..00000000 --- a/src/cpl-core/cpl/core/configuration/flag_argument.py +++ /dev/null @@ -1,13 +0,0 @@ -from cpl.core.configuration.argument_abc import ArgumentABC - - -class FlagArgument(ArgumentABC): - def __init__( - self, - token: str, - name: str, - aliases: list[str], - prevent_next_executable: bool = False, - console_arguments: list["ArgumentABC"] = None, - ): - ArgumentABC.__init__(self, token, name, aliases, prevent_next_executable, console_arguments) diff --git a/src/cpl-core/cpl/core/configuration/validator_abc.py b/src/cpl-core/cpl/core/configuration/validator_abc.py deleted file mode 100644 index 060d7898..00000000 --- a/src/cpl-core/cpl/core/configuration/validator_abc.py +++ /dev/null @@ -1,11 +0,0 @@ -from abc import ABC, abstractmethod - - -class ValidatorABC(ABC): - @abstractmethod - def __init__(self): - pass - - @abstractmethod - def validate(self) -> bool: - pass diff --git a/src/cpl-core/cpl/core/configuration/variable_argument.py b/src/cpl-core/cpl/core/configuration/variable_argument.py deleted file mode 100644 index 104e2166..00000000 --- a/src/cpl-core/cpl/core/configuration/variable_argument.py +++ /dev/null @@ -1,28 +0,0 @@ -from cpl.core.configuration.argument_abc import ArgumentABC - - -class VariableArgument(ArgumentABC): - def __init__( - self, - token: str, - name: str, - aliases: list[str], - value_token: str, - prevent_next_executable: bool = False, - console_arguments: list["ArgumentABC"] = None, - ): - self._value_token = value_token - self._value: str = "" - - ArgumentABC.__init__(self, token, name, aliases, prevent_next_executable, console_arguments) - - @property - def value_token(self) -> str: - return self._value_token - - @property - def value(self) -> str: - return self._value - - def set_value(self, value: str): - self._value = value diff --git a/src/cpl-core/cpl/core/database/db_logger.py b/src/cpl-core/cpl/core/database/db_logger.py index bca8b936..fdee274c 100644 --- a/src/cpl-core/cpl/core/database/db_logger.py +++ b/src/cpl-core/cpl/core/database/db_logger.py @@ -5,4 +5,4 @@ from cpl.core.typing import Source class DBLogger(Logger): def __init__(self, source: Source): - Logger.__init__(self, source, "db") \ No newline at end of file + Logger.__init__(self, source, "db") diff --git a/src/cpl-core/cpl/core/dependency_injection/service_collection.py b/src/cpl-core/cpl/core/dependency_injection/service_collection.py index 5abc9d9a..1f509cbb 100644 --- a/src/cpl-core/cpl/core/dependency_injection/service_collection.py +++ b/src/cpl-core/cpl/core/dependency_injection/service_collection.py @@ -1,6 +1,5 @@ from typing import Union, Type, Callable, Optional -from cpl.core.configuration.configuration_abc import ConfigurationABC from cpl.core.database.context.database_context_abc import DatabaseContextABC from cpl.core.database.database_settings import DatabaseSettings from cpl.core.dependency_injection.service_collection_abc import ServiceCollectionABC @@ -17,10 +16,8 @@ from cpl.core.typing import T, Service class ServiceCollection(ServiceCollectionABC): r"""Representation of the collection of services""" - def __init__(self, config: ConfigurationABC): + def __init__(self): ServiceCollectionABC.__init__(self) - self._configuration: ConfigurationABC = config - self._database_context: Optional[DatabaseContextABC] = None self._service_descriptors: list[ServiceDescriptor] = [] @@ -74,6 +71,6 @@ class ServiceCollection(ServiceCollectionABC): return self def build_service_provider(self) -> ServiceProviderABC: - sp = ServiceProvider(self._service_descriptors, self._configuration, self._database_context) + sp = ServiceProvider(self._service_descriptors, self._database_context) ServiceProviderABC.set_global_provider(sp) return sp diff --git a/src/cpl-core/cpl/core/dependency_injection/service_provider.py b/src/cpl-core/cpl/core/dependency_injection/service_provider.py index 84c21e9c..aefbebb5 100644 --- a/src/cpl-core/cpl/core/dependency_injection/service_provider.py +++ b/src/cpl-core/cpl/core/dependency_injection/service_provider.py @@ -3,7 +3,7 @@ import typing from inspect import signature, Parameter, Signature from typing import Optional -from cpl.core.configuration.configuration_abc import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.configuration.configuration_model_abc import ConfigurationModelABC from cpl.core.database.context.database_context_abc import DatabaseContextABC from cpl.core.dependency_injection.scope_abc import ScopeABC @@ -11,7 +11,7 @@ from cpl.core.dependency_injection.scope_builder import ScopeBuilder from cpl.core.dependency_injection.service_descriptor import ServiceDescriptor from cpl.core.dependency_injection.service_lifetime_enum import ServiceLifetimeEnum from cpl.core.dependency_injection.service_provider_abc import ServiceProviderABC -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC +from cpl.core.environment import Environment from cpl.core.typing import T, R, Source @@ -31,13 +31,11 @@ class ServiceProvider(ServiceProviderABC): def __init__( self, service_descriptors: list[ServiceDescriptor], - config: ConfigurationABC, db_context: Optional[DatabaseContextABC], ): ServiceProviderABC.__init__(self) self._service_descriptors: list[ServiceDescriptor] = service_descriptors - self._configuration: ConfigurationABC = config self._database_context = db_context self._scope: Optional[ScopeABC] = None @@ -94,17 +92,17 @@ class ServiceProvider(ServiceProviderABC): elif issubclass(parameter.annotation, ServiceProviderABC): params.append(self) - elif issubclass(parameter.annotation, ApplicationEnvironmentABC): - params.append(self._configuration.environment) + elif issubclass(parameter.annotation, Environment): + params.append(Environment) elif issubclass(parameter.annotation, DatabaseContextABC): params.append(self._database_context) elif issubclass(parameter.annotation, ConfigurationModelABC): - params.append(self._configuration.get_configuration(parameter.annotation)) + params.append(Configuration.get(parameter.annotation)) - elif issubclass(parameter.annotation, ConfigurationABC): - params.append(self._configuration) + elif issubclass(parameter.annotation, Configuration): + params.append(Configuration) else: params.append(self._get_service(parameter, origin_service_type)) @@ -115,7 +113,6 @@ class ServiceProvider(ServiceProviderABC): if origin_service_type is None: origin_service_type = service_type - for descriptor in self._service_descriptors: if descriptor.service_type == service_type or issubclass(descriptor.service_type, service_type): if descriptor.implementation is not None: @@ -142,7 +139,7 @@ class ServiceProvider(ServiceProviderABC): else: descriptors.append(copy.deepcopy(descriptor)) - sb = ScopeBuilder(ServiceProvider(descriptors, self._configuration, self._database_context)) + sb = ScopeBuilder(ServiceProvider(descriptors, self._database_context)) return sb.build() def get_service(self, service_type: T, *args, **kwargs) -> Optional[R]: diff --git a/src/cpl-core/cpl/core/environment/__init__.py b/src/cpl-core/cpl/core/environment/__init__.py index f891e575..72977748 100644 --- a/src/cpl-core/cpl/core/environment/__init__.py +++ b/src/cpl-core/cpl/core/environment/__init__.py @@ -1,3 +1,2 @@ -from .application_environment_abc import ApplicationEnvironmentABC -from .environment_name_enum import EnvironmentNameEnum -from .application_environment import ApplicationEnvironment +from .environment_enum import EnvironmentEnum +from .environment import Environment diff --git a/src/cpl-core/cpl/core/environment/application_environment.py b/src/cpl-core/cpl/core/environment/application_environment.py deleted file mode 100644 index 2f063efd..00000000 --- a/src/cpl-core/cpl/core/environment/application_environment.py +++ /dev/null @@ -1,95 +0,0 @@ -import os -from datetime import datetime -from socket import gethostname -from typing import Optional - -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC -from cpl.core.environment.environment_name_enum import EnvironmentNameEnum - - -class ApplicationEnvironment(ApplicationEnvironmentABC): - r"""Represents environment of the application - - Parameter: - name: :class:`cpl.core.environment.environment_name_enum.EnvironmentNameEnum` - """ - - def __init__(self, name: EnvironmentNameEnum = EnvironmentNameEnum.production): - ApplicationEnvironmentABC.__init__(self) - - self._environment_name: Optional[EnvironmentNameEnum] = name - self._app_name: Optional[str] = None - self._customer: Optional[str] = None - - self._start_time: datetime = datetime.now() - self._end_time: datetime = datetime.now() - self._runtime_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - self._working_directory = os.getcwd() - - @property - def environment_name(self) -> str: - return str(self._environment_name.value) - - @environment_name.setter - def environment_name(self, environment_name: str): - self._environment_name = EnvironmentNameEnum(environment_name) - - @property - def application_name(self) -> str: - return self._app_name if self._app_name is not None else "" - - @application_name.setter - def application_name(self, application_name: str): - self._app_name = application_name - - @property - def customer(self) -> str: - return self._customer if self._customer is not None else "" - - @customer.setter - def customer(self, customer: str): - self._customer = customer - - @property - def host_name(self): - return gethostname() - - @property - def start_time(self) -> datetime: - return self._start_time - - @property - def end_time(self) -> datetime: - return self._end_time - - @end_time.setter - def end_time(self, end_time: datetime): - self._end_time = end_time - - @property - def date_time_now(self) -> datetime: - return datetime.now() - - @property - def working_directory(self) -> str: - return str(self._working_directory) - - @property - def runtime_directory(self) -> str: - return str(self._runtime_directory) - - def set_runtime_directory(self, runtime_directory: str): - if runtime_directory != "": - self._runtime_directory = runtime_directory - return - - self._runtime_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - - def set_working_directory(self, working_directory: str): - if working_directory != "": - self._working_directory = working_directory - os.chdir(self._working_directory) - return - - self._working_directory = os.path.abspath("./") - os.chdir(self._working_directory) diff --git a/src/cpl-core/cpl/core/environment/application_environment_abc.py b/src/cpl-core/cpl/core/environment/application_environment_abc.py deleted file mode 100644 index eb1abcdd..00000000 --- a/src/cpl-core/cpl/core/environment/application_environment_abc.py +++ /dev/null @@ -1,98 +0,0 @@ -from abc import ABC, abstractmethod -from datetime import datetime - - -class ApplicationEnvironmentABC(ABC): - r"""ABC of the class :class:`cpl.core.environment.application_environment.ApplicationEnvironment`""" - - @abstractmethod - def __init__(self): - pass - - @property - @abstractmethod - def environment_name(self) -> str: - pass - - @environment_name.setter - @abstractmethod - def environment_name(self, environment_name: str): - pass - - @property - @abstractmethod - def application_name(self) -> str: - pass - - @application_name.setter - @abstractmethod - def application_name(self, application_name: str): - pass - - @property - @abstractmethod - def customer(self) -> str: - pass - - @customer.setter - @abstractmethod - def customer(self, customer: str): - pass - - @property - @abstractmethod - def host_name(self) -> str: - pass - - @property - @abstractmethod - def start_time(self) -> datetime: - pass - - @start_time.setter - @abstractmethod - def start_time(self, start_time: datetime): - pass - - @property - @abstractmethod - def end_time(self): - pass - - @end_time.setter - @abstractmethod - def end_time(self, end_time: datetime): - pass - - @property - @abstractmethod - def date_time_now(self) -> datetime: - pass - - @property - @abstractmethod - def working_directory(self) -> str: - pass - - @property - @abstractmethod - def runtime_directory(self) -> str: - pass - - @abstractmethod - def set_runtime_directory(self, runtime_directory: str): - r"""Sets the current runtime directory - - Parameter: - runtime_directory: :class:`str` - Path of the runtime directory - """ - - @abstractmethod - def set_working_directory(self, working_directory: str): - r"""Sets the current working directory - - Parameter: - working_directory: :class:`str` - Path of the current working directory - """ diff --git a/src/cpl-core/cpl/core/environment/environment.py b/src/cpl-core/cpl/core/environment/environment.py index b560cf6d..15576543 100644 --- a/src/cpl-core/cpl/core/environment/environment.py +++ b/src/cpl-core/cpl/core/environment/environment.py @@ -1,22 +1,58 @@ import os +from socket import gethostname from typing import Optional, Type +from cpl.core.environment.environment_enum import EnvironmentEnum from cpl.core.typing import T from cpl.core.utils.get_value import get_value class Environment: - _environment = "production" + r"""Represents environment of the application + + Parameter: + name: :class:`cpl.core.environment.environment_name_enum.EnvironmentNameEnum` + """ @classmethod def get_environment(cls): - return cls._environment + return cls.get("ENVIRONMENT", str, EnvironmentEnum.production.value) @classmethod def set_environment(cls, environment: str): - if environment not in ["development", "staging", "production"]: - raise ValueError("Invalid environment") - Environment._environment = environment + assert environment is not None and environment != "", "environment must not be None or empty" + assert environment.lower() in [ + e.value for e in EnvironmentEnum + ], f"environment must be one of {[e.value for e in EnvironmentEnum]}" + cls.set("ENVIRONMENT", environment.lower()) + + @classmethod + def get_app_name(cls) -> str: + return cls.get("APP_NAME", str) + + @classmethod + def set_app_name(cls, app_name: str): + cls.set("APP_NAME", app_name) + + @staticmethod + def get_host_name() -> str: + return gethostname() + + @staticmethod + def get_cwd() -> str: + return os.getcwd() + + @staticmethod + def set_cwd(working_directory: str): + assert working_directory is not None and working_directory != "", "working_directory must not be None or empty" + + os.chdir(working_directory) + + @staticmethod + def set(key: str, value: T): + assert key is not None and key != "", "key must not be None or empty" + + os.environ[key] = str(value) @staticmethod def get(key: str, cast_type: Type[T], default: Optional[T] = None) -> Optional[T]: diff --git a/src/cpl-core/cpl/core/environment/environment_name_enum.py b/src/cpl-core/cpl/core/environment/environment_enum.py similarity index 80% rename from src/cpl-core/cpl/core/environment/environment_name_enum.py rename to src/cpl-core/cpl/core/environment/environment_enum.py index f2ade14c..8c66c5ee 100644 --- a/src/cpl-core/cpl/core/environment/environment_name_enum.py +++ b/src/cpl-core/cpl/core/environment/environment_enum.py @@ -1,7 +1,7 @@ from enum import Enum -class EnvironmentNameEnum(Enum): +class EnvironmentEnum(Enum): production = "production" staging = "staging" testing = "testing" diff --git a/src/cpl-core/cpl/core/log/_log_writer.py b/src/cpl-core/cpl/core/log/_log_writer.py index 26b26419..a95d8e4d 100644 --- a/src/cpl-core/cpl/core/log/_log_writer.py +++ b/src/cpl-core/cpl/core/log/_log_writer.py @@ -59,9 +59,7 @@ class LogWriter: if content is None: # Shutdown signal break self._write_log_to_file(content) - Console.write_line( - f"{self._COLORS.get(self._level, '\033[0m')}{content}\033[0m" - ) + Console.write_line(f"{self._COLORS.get(self._level, '\033[0m')}{content}\033[0m") @property def log_file(self): diff --git a/src/cpl-core/cpl/core/pipes/bool_pipe.py b/src/cpl-core/cpl/core/pipes/bool_pipe.py index cd1bd6b9..faeb2cd7 100644 --- a/src/cpl-core/cpl/core/pipes/bool_pipe.py +++ b/src/cpl-core/cpl/core/pipes/bool_pipe.py @@ -1,9 +1,13 @@ from cpl.core.pipes.pipe_abc import PipeABC +from cpl.core.typing import T -class BoolPipe(PipeABC): - def __init__(self): - pass +class BoolPipe[bool](PipeABC): - def transform(self, value: bool, *args): - return "True" if value else "False" + @staticmethod + def to_str(value: T, *args): + return str(value).lower() + + @staticmethod + def from_str(value: str, *args) -> T: + return value in ("True", "true", "1", "yes", "y", "Y") diff --git a/src/cpl-core/cpl/core/pipes/ip_address_pipe.py b/src/cpl-core/cpl/core/pipes/ip_address_pipe.py index c01d79c9..8a654640 100644 --- a/src/cpl-core/cpl/core/pipes/ip_address_pipe.py +++ b/src/cpl-core/cpl/core/pipes/ip_address_pipe.py @@ -1,20 +1,19 @@ from cpl.core.pipes.pipe_abc import PipeABC +from cpl.core.typing import T -class IPAddressPipe(PipeABC): - def __init__(self): - pass - - def transform(self, value: list[int], *args): +class IPAddressPipe[list](PipeABC): + @staticmethod + def to_str(value: T, *args) -> str: string = "" if len(value) != 4: - raise Exception("Invalid IP") + raise ValueError("Invalid IP") for i in range(0, len(value)): byte = value[i] - if byte > 255 or byte < 0: - raise Exception("Invalid IP") + if not 0 <= byte <= 255: + raise ValueError("Invalid IP") if i == len(value) - 1: string += f"{byte}" @@ -22,3 +21,18 @@ class IPAddressPipe(PipeABC): string += f"{byte}." return string + + @staticmethod + def from_str(value: str, *args) -> T: + parts = value.split(".") + if len(parts) != 4: + raise Exception("Invalid IP") + + result = [] + for part in parts: + byte = int(part) + if not 0 <= byte <= 255: + raise Exception("Invalid IP") + result.append(byte) + + return result diff --git a/src/cpl-core/cpl/core/pipes/pipe_abc.py b/src/cpl-core/cpl/core/pipes/pipe_abc.py index 9795a9b5..08e10aae 100644 --- a/src/cpl-core/cpl/core/pipes/pipe_abc.py +++ b/src/cpl-core/cpl/core/pipes/pipe_abc.py @@ -1,11 +1,16 @@ from abc import ABC, abstractmethod +from typing import Generic + +from cpl.core.typing import T -class PipeABC(ABC): +class PipeABC(ABC, Generic[T]): + @staticmethod @abstractmethod - def __init__(self): + def to_str(value: T, *args) -> str: pass + @staticmethod @abstractmethod - def transform(self, value: any, *args): + def from_str(value: str, *args) -> T: pass diff --git a/src/cpl-core/cpl/core/pipes/version_pipe.py b/src/cpl-core/cpl/core/pipes/version_pipe.py deleted file mode 100644 index 10545559..00000000 --- a/src/cpl-core/cpl/core/pipes/version_pipe.py +++ /dev/null @@ -1,17 +0,0 @@ -from cpl_cli.configuration import VersionSettingsNameEnum -from cpl.core.pipes.pipe_abc import PipeABC - - -class VersionPipe(PipeABC): - def __init__(self): - pass - - def transform(self, value: dict, *args): - for atr in VersionSettingsNameEnum: - if atr.value not in value: - raise KeyError(atr.value) - - v_str = f"{value[VersionSettingsNameEnum.major.value]}.{value[VersionSettingsNameEnum.minor.value]}" - if value[VersionSettingsNameEnum.micro.value] is not None: - v_str += f".{value[VersionSettingsNameEnum.micro.value]}" - return v_str diff --git a/src/cpl-core/cpl/core/typing.py b/src/cpl-core/cpl/core/typing.py index c7bf2217..63a1f8f2 100644 --- a/src/cpl-core/cpl/core/typing.py +++ b/src/cpl-core/cpl/core/typing.py @@ -1,6 +1,7 @@ from typing import TypeVar, Any T = TypeVar("T") +D = TypeVar("D") R = TypeVar("R") Service = TypeVar("Service") diff --git a/src/cpl-core/cpl/core/utils/__init__.py b/src/cpl-core/cpl/core/utils/__init__.py index 5fabb9c9..664d3a02 100644 --- a/src/cpl-core/cpl/core/utils/__init__.py +++ b/src/cpl-core/cpl/core/utils/__init__.py @@ -1,3 +1,5 @@ +from .b64 import B64 from .credential_manager import CredentialManager -from .string import String +from .json_processor import JSONProcessor from .pip import Pip +from .string import String diff --git a/src/cpl-core/cpl/core/utils/b64.py b/src/cpl-core/cpl/core/utils/b64.py new file mode 100644 index 00000000..0292e6f6 --- /dev/null +++ b/src/cpl-core/cpl/core/utils/b64.py @@ -0,0 +1,43 @@ +import base64 +from typing import Union + + +class B64: + + @staticmethod + def encode(string: str) -> str: + """ + Encode a string with base64 + :param string: + :return: + """ + return base64.b64encode(string.encode("utf-8")).decode("utf-8") + + @staticmethod + def decode(string: str) -> str: + """ + Decode a string with base64 + :param string: + :return: + """ + return base64.b64decode(string).decode("utf-8") + + @staticmethod + def is_b64(sb: Union[str, bytes]) -> bool: + """ + Check if a string is base64 encoded + :param Union[str, bytes] sb: + :return: + :rtype: bool + """ + try: + if isinstance(sb, str): + # If there's any unicode here, an exception will be thrown and the function will return false + sb_bytes = bytes(sb, "ascii") + elif isinstance(sb, bytes): + sb_bytes = sb + else: + raise ValueError("Argument must be string or bytes") + return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes + except ValueError: + return False diff --git a/src/cpl-core/cpl/core/utils/get_value.py b/src/cpl-core/cpl/core/utils/get_value.py index 3cb7a33f..3a3cf4c3 100644 --- a/src/cpl-core/cpl/core/utils/get_value.py +++ b/src/cpl-core/cpl/core/utils/get_value.py @@ -40,16 +40,9 @@ def get_value( if cast_type == bool: return value.lower() in ["true", "1"] - if ( - cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__ - ) == list: - if ( - not (value.startswith("[") and value.endswith("]")) - and list_delimiter not in value - ): - raise ValueError( - "List values must be enclosed in square brackets or use a delimiter." - ) + if (cast_type if not hasattr(cast_type, "__origin__") else cast_type.__origin__) == list: + if not (value.startswith("[") and value.endswith("]")) and list_delimiter not in value: + raise ValueError("List values must be enclosed in square brackets or use a delimiter.") if value.startswith("[") and value.endswith("]"): value = value[1:-1] diff --git a/src/cpl-core/cpl/core/utils/json_processor.py b/src/cpl-core/cpl/core/utils/json_processor.py index d4c45474..90eb636b 100644 --- a/src/cpl-core/cpl/core/utils/json_processor.py +++ b/src/cpl-core/cpl/core/utils/json_processor.py @@ -1,7 +1,7 @@ import enum from inspect import signature, Parameter -from cpl.core.utils import String +from cpl.core.utils.string import String class JSONProcessor: @@ -16,7 +16,7 @@ class JSONProcessor: if parameter.name == "self" or parameter.annotation == Parameter.empty: continue - name = String.first_to_upper(String.convert_to_camel_case(parameter.name)) + name = String.first_to_upper(String.to_camel_case(parameter.name)) name_first_lower = String.first_to_lower(name) if name in values or name_first_lower in values or name.upper() in values: value = "" diff --git a/src/cpl-core/cpl/core/utils/string.py b/src/cpl-core/cpl/core/utils/string.py index 31c0c483..e52deae9 100644 --- a/src/cpl-core/cpl/core/utils/string.py +++ b/src/cpl-core/cpl/core/utils/string.py @@ -1,13 +1,13 @@ +import random import re import string -import random class String: r"""Useful functions for strings""" @staticmethod - def convert_to_camel_case(chars: str) -> str: + def to_camel_case(s: str) -> str: r"""Converts string to camel case Parameter: @@ -17,16 +17,10 @@ class String: Returns: String converted to CamelCase """ - converted_name = chars - char_set = string.punctuation + " " - for char in char_set: - if char in converted_name: - converted_name = "".join(word.title() for word in converted_name.split(char)) - - return converted_name + return re.sub(r"(? str: + def to_snake_case(chars: str) -> str: r"""Converts string to snake case Parameter: @@ -56,7 +50,7 @@ class String: return re.sub(pattern2, r"\1_\2", file_name).lower() @staticmethod - def first_to_upper(chars: str) -> str: + def first_to_upper(s: str) -> str: r"""Converts first char to upper Parameter: @@ -66,10 +60,10 @@ class String: Returns: String with first char as upper """ - return f"{chars[0].upper()}{chars[1:]}" + return s[0].upper() + s[1:] if s else s @staticmethod - def first_to_lower(chars: str) -> str: + def first_to_lower(s: str) -> str: r"""Converts first char to lower Parameter: @@ -79,14 +73,24 @@ class String: Returns: String with first char as lower """ - return f"{chars[0].lower()}{chars[1:]}" + return s[0].lower() + s[1:] if s else s @staticmethod - def random_string(chars: str, length: int) -> str: + def random(length: int, letters=True, digits=False, special_characters=False) -> str: r"""Creates random string by given chars and length Returns: String of random chars """ - return "".join(random.choice(chars) for _ in range(length)) + characters = [] + if letters: + characters.append(string.ascii_letters) + + if digits: + characters.append(string.digits) + + if special_characters: + characters.append(string.punctuation) + + return "".join(random.choice(characters) for _ in range(length)) if characters else "" diff --git a/src/cpl-core/requirements.txt b/src/cpl-core/requirements.txt index 578347a1..186be5c3 100644 --- a/src/cpl-core/requirements.txt +++ b/src/cpl-core/requirements.txt @@ -3,3 +3,4 @@ colorama==0.4.6 tabulate==0.9.0 termcolor==3.1.0 mysql-connector-python==9.4.0 +pynput==1.8.1 diff --git a/src/cpl-mail/cpl/mail/email_client.py b/src/cpl-mail/cpl/mail/email_client.py index 1fa02259..bee8fe7f 100644 --- a/src/cpl-mail/cpl/mail/email_client.py +++ b/src/cpl-mail/cpl/mail/email_client.py @@ -2,7 +2,6 @@ import ssl from smtplib import SMTP from typing import Optional -from cpl.core.environment.application_environment_abc import ApplicationEnvironmentABC from cpl.core.utils.credential_manager import CredentialManager from cpl.mail.abc.email_client_abc import EMailClientABC from cpl.mail.email_client_settings import EMailClientSettings @@ -22,10 +21,11 @@ class EMailClient(EMailClientABC): Settings for mailing """ - def __init__(self, environment: ApplicationEnvironmentABC, logger: MailLogger, mail_settings: EMailClientSettings): + def __init__(self, logger: MailLogger, mail_settings: EMailClientSettings): EMailClientABC.__init__(self) - self._environment = environment + assert mail_settings is not None, "mail_settings must not be None" + self._mail_settings = mail_settings self._logger = logger diff --git a/tests/custom/async/src/async/startup.py b/tests/custom/async/src/async/startup.py index 5540354b..29f7159e 100644 --- a/tests/custom/async/src/async/startup.py +++ b/tests/custom/async/src/async/startup.py @@ -1,7 +1,7 @@ from cpl.core.application.async_startup_abc import AsyncStartupABC from cpl.core.configuration import ConfigurationABC from cpl.core.dependency_injection import ServiceProviderABC, ServiceCollectionABC -from cpl.core.environment import ApplicationEnvironment +from cpl.core.environment import Environment class Startup(AsyncStartupABC): @@ -9,11 +9,11 @@ class Startup(AsyncStartupABC): AsyncStartupABC.__init__(self) async def configure_configuration( - self, configuration: ConfigurationABC, environment: ApplicationEnvironment + self, configuration: ConfigurationABC, environment: Environment ) -> ConfigurationABC: return configuration async def configure_services( - self, services: ServiceCollectionABC, environment: ApplicationEnvironment + self, services: ServiceCollectionABC, environment: Environment ) -> ServiceProviderABC: return services.build_service_provider() diff --git a/tests/custom/database/src/startup.py b/tests/custom/database/src/startup.py index 0f613e1d..fdbf6239 100644 --- a/tests/custom/database/src/startup.py +++ b/tests/custom/database/src/startup.py @@ -2,7 +2,7 @@ from cpl.core.application import StartupABC from cpl.core.configuration import ConfigurationABC from cpl.core.database import DatabaseSettings from cpl.core.dependency_injection import ServiceCollectionABC, ServiceProviderABC -from cpl.core.environment import ApplicationEnvironmentABC +from cpl.core.environment import EnvironmentABC from cpl.core.log import Logger, LoggerABC from model.db_context import DBContext @@ -17,7 +17,7 @@ class Startup(StartupABC): self._configuration = None def configure_configuration( - self, configuration: ConfigurationABC, environment: ApplicationEnvironmentABC + self, configuration: ConfigurationABC, environment: EnvironmentABC ) -> ConfigurationABC: configuration.add_environment_variables("PYTHON_") configuration.add_environment_variables("CPL_") @@ -30,7 +30,7 @@ class Startup(StartupABC): return configuration def configure_services( - self, services: ServiceCollectionABC, environment: ApplicationEnvironmentABC + self, services: ServiceCollectionABC, environment: EnvironmentABC ) -> ServiceProviderABC: # Create and connect to database self._configuration.parse_console_arguments(services) diff --git a/tests/custom/di/src/di/startup.py b/tests/custom/di/src/di/startup.py index b9118a5f..820f2380 100644 --- a/tests/custom/di/src/di/startup.py +++ b/tests/custom/di/src/di/startup.py @@ -1,7 +1,7 @@ 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 +from cpl.core.environment import Environment from di.test1_service import Test1Service from di.test2_service import Test2Service from di.test_abc import TestABC @@ -15,12 +15,12 @@ class Startup(StartupABC): StartupABC.__init__(self) def configure_configuration( - self, configuration: ConfigurationABC, environment: ApplicationEnvironment + self, configuration: ConfigurationABC, environment: Environment ) -> ConfigurationABC: return configuration def configure_services( - self, services: ServiceCollectionABC, environment: ApplicationEnvironment + self, services: ServiceCollectionABC, environment: Environment ) -> ServiceProviderABC: services.add_scoped(TestService) services.add_scoped(DITesterService) diff --git a/tests/custom/general/src/general/application.py b/tests/custom/general/src/general/application.py index 0b5c7e93..9a8ef670 100644 --- a/tests/custom/general/src/general/application.py +++ b/tests/custom/general/src/general/application.py @@ -2,20 +2,22 @@ import time from typing import Optional from cpl.core.application.application_abc import ApplicationABC -from cpl.core.configuration import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.console import Console from cpl.core.dependency_injection import ServiceProviderABC +from cpl.core.environment import Environment from cpl.core.log import LoggerABC from cpl.core.pipes import IPAddressPipe from cpl.mail import EMail, EMailClientABC -from test_settings import TestSettings -from test_service import TestService from cpl.query.extension.list import List +from test_service import TestService +from test_settings import TestSettings class Application(ApplicationABC): - def __init__(self, config: ConfigurationABC, services: ServiceProviderABC): - ApplicationABC.__init__(self, config, services) + + def __init__(self, services: ServiceProviderABC): + ApplicationABC.__init__(self, services) self._logger: Optional[LoggerABC] = None self._mailer: Optional[EMailClientABC] = None @@ -25,7 +27,7 @@ class Application(ApplicationABC): mail.add_header("Content-Type: text/plain; charset=utf-8") mail.add_header("Content-Transfer-Encoding: quoted-printable") mail.add_receiver("sven.heidemann@sh-edraft.de") - mail.subject = f"Test - {self._configuration.environment.host_name}" + mail.subject = f"Test - {Environment.get_host_name()}" mail.body = "Dies ist ein Test :D" self._mailer.send_mail(mail) @@ -38,14 +40,8 @@ class Application(ApplicationABC): self._mailer = self._services.get_service(EMailClientABC) def main(self): - self._configuration.parse_console_arguments(self._services) - - if self._configuration.environment.application_name != "": - self._logger.header(f"{self._configuration.environment.application_name}:") - self._logger.debug(f"Args: {self._configuration.additional_arguments}") - self._logger.debug(f"Host: {self._configuration.environment.host_name}") - self._logger.debug(f"Environment: {self._configuration.environment.environment_name}") - self._logger.debug(f"Customer: {self._configuration.environment.customer}") + self._logger.debug(f"Host: {Environment.get_host_name()}") + self._logger.debug(f"Environment: {Environment.get_environment()}") Console.write_line(List(int, range(0, 10)).select(lambda x: f"x={x}").to_list()) Console.spinner("Test", self._wait, 2, spinner_foreground_color="red") test: TestService = self._services.get_service(TestService) @@ -61,12 +57,12 @@ class Application(ApplicationABC): with self._services.create_scope() as s: Console.write_line("with scope", s) - test_settings = self._configuration.get_configuration(TestSettings) + test_settings = Configuration.get(TestSettings) Console.write_line(test_settings.value) Console.write_line("reload config") - self._configuration.add_json_file(f"appsettings.json") - self._configuration.add_json_file(f"appsettings.{self._environment.environment_name}.json") - self._configuration.add_json_file(f"appsettings.{self._environment.host_name}.json", optional=True) - test_settings1 = self._configuration.get_configuration(TestSettings) + Configuration.add_json_file(f"appsettings.json") + Configuration.add_json_file(f"appsettings.{Environment.get_environment()}.json") + Configuration.add_json_file(f"appsettings.{Environment.get_host_name()}.json", optional=True) + test_settings1 = Configuration.get(TestSettings) Console.write_line(test_settings1.value) - # self.test_send_mail() \ No newline at end of file + # self.test_send_mail() diff --git a/tests/custom/general/src/general/arguments/__init__.py b/tests/custom/general/src/general/arguments/__init__.py deleted file mode 100644 index 8b137891..00000000 --- a/tests/custom/general/src/general/arguments/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/custom/general/src/general/arguments/generate_argument.py b/tests/custom/general/src/general/arguments/generate_argument.py deleted file mode 100644 index c0e65a00..00000000 --- a/tests/custom/general/src/general/arguments/generate_argument.py +++ /dev/null @@ -1,14 +0,0 @@ -from cpl.core.configuration import ConfigurationABC, ArgumentExecutableABC -from cpl.core.console import Console -from cpl.core.environment import ApplicationEnvironmentABC - - -class GenerateArgument(ArgumentExecutableABC): - def __init__(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): - ArgumentExecutableABC.__init__(self) - self._config = config - self._env = env - - def execute(self, args: list[str]): - Console.error("Generate:") - Console.write_line(args, self._env.environment_name) diff --git a/tests/custom/general/src/general/arguments/install_argument.py b/tests/custom/general/src/general/arguments/install_argument.py deleted file mode 100644 index 15a36590..00000000 --- a/tests/custom/general/src/general/arguments/install_argument.py +++ /dev/null @@ -1,10 +0,0 @@ -from cpl.core.configuration import ArgumentExecutableABC -from cpl.core.console import Console - - -class InstallArgument(ArgumentExecutableABC): - def __init__(self): - ArgumentExecutableABC.__init__(self) - - def execute(self, args: list[str]): - Console.write_line("Install:", args) diff --git a/tests/custom/general/src/general/main.py b/tests/custom/general/src/general/main.py index a6ec4669..9fb7cc54 100644 --- a/tests/custom/general/src/general/main.py +++ b/tests/custom/general/src/general/main.py @@ -3,13 +3,11 @@ from cpl.core.application import ApplicationBuilder from test_extension import TestExtension from startup import Startup from test_startup_extension import TestStartupExtension -from parameter_startup import ParameterStartup def main(): app_builder = ApplicationBuilder(Application) app_builder.use_startup(Startup) - app_builder.use_extension(ParameterStartup) app_builder.use_extension(TestStartupExtension) app_builder.use_extension(TestExtension) app_builder.build().run() diff --git a/tests/custom/general/src/general/parameter_startup.py b/tests/custom/general/src/general/parameter_startup.py deleted file mode 100644 index f17ea27e..00000000 --- a/tests/custom/general/src/general/parameter_startup.py +++ /dev/null @@ -1,38 +0,0 @@ -from arguments.generate_argument import GenerateArgument -from arguments.install_argument import InstallArgument -from cpl.core.application import StartupExtensionABC -from cpl.core.configuration import ConfigurationABC, ArgumentTypeEnum -from cpl.core.dependency_injection import ServiceCollectionABC -from cpl.core.environment import ApplicationEnvironmentABC - - -class ParameterStartup(StartupExtensionABC): - def __init__(self): - StartupExtensionABC.__init__(self) - - def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): - config.create_console_argument( - ArgumentTypeEnum.Executable, "", "generate", ["g", "G"], GenerateArgument - ).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, "", "service", ["s", "S"], " " - ).add_console_argument( - ArgumentTypeEnum.Variable, "", "settings", ["st", "ST"], " " - ).add_console_argument( - ArgumentTypeEnum.Variable, "", "thread", ["t", "T"], " " - ).add_console_argument( - ArgumentTypeEnum.Variable, "-", "o", ["o", "O"], "=" - ).add_console_argument( - ArgumentTypeEnum.Flag, "--", "virtual", ["v", "V"] - ) - config.create_console_argument( - ArgumentTypeEnum.Executable, "", "install", ["i", "I"], InstallArgument - ).add_console_argument(ArgumentTypeEnum.Flag, "--", "virtual", ["v", "V"]).add_console_argument( - ArgumentTypeEnum.Flag, "--", "simulate", ["s", "S"] - ) - - def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): - services.add_transient(GenerateArgument).add_singleton(InstallArgument) diff --git a/tests/custom/general/src/general/startup.py b/tests/custom/general/src/general/startup.py index 053df38e..e4af1412 100644 --- a/tests/custom/general/src/general/startup.py +++ b/tests/custom/general/src/general/startup.py @@ -1,9 +1,7 @@ from cpl.core.application import StartupABC -from cpl.core.configuration import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.dependency_injection import ServiceCollectionABC, ServiceProviderABC -from cpl.core.environment import ApplicationEnvironmentABC -from cpl.core.log import Logger, LoggerABC -from cpl.mail import EMailClient, EMailClientABC +from cpl.core.environment import Environment from cpl.core.pipes import IPAddressPipe from test_service import TestService @@ -12,14 +10,12 @@ class Startup(StartupABC): def __init__(self): StartupABC.__init__(self) - def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC) -> ConfigurationABC: - config.add_environment_variables("PYTHON_") - config.add_environment_variables("CPLT_") + def configure_configuration(self, config: Configuration, env: Environment): config.add_json_file(f"appsettings.json") - config.add_json_file(f"appsettings.{config.environment.environment_name}.json") - config.add_json_file(f"appsettings.{config.environment.host_name}.json", optional=True) + config.add_json_file(f"appsettings.{env.get_environment()}.json") + config.add_json_file(f"appsettings.{env.get_host_name()}.json", optional=True) - def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC) -> ServiceProviderABC: + def configure_services(self, services: ServiceCollectionABC, env: Environment): services.add_logging() services.add_mail() services.add_transient(IPAddressPipe) diff --git a/tests/custom/general/src/general/test_extension.py b/tests/custom/general/src/general/test_extension.py index 2f9cac49..0dc06646 100644 --- a/tests/custom/general/src/general/test_extension.py +++ b/tests/custom/general/src/general/test_extension.py @@ -1,5 +1,5 @@ from cpl.core.application import ApplicationExtensionABC -from cpl.core.configuration import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.console import Console from cpl.core.dependency_injection import ServiceProviderABC @@ -8,5 +8,5 @@ class TestExtension(ApplicationExtensionABC): def __init__(self): ApplicationExtensionABC.__init__(self) - def run(self, config: ConfigurationABC, services: ServiceProviderABC): + def run(self, config: Configuration, services: ServiceProviderABC): Console.write_line("Hello World from App Extension") diff --git a/tests/custom/general/src/general/test_service.py b/tests/custom/general/src/general/test_service.py index 6f1ce259..a521ef11 100644 --- a/tests/custom/general/src/general/test_service.py +++ b/tests/custom/general/src/general/test_service.py @@ -4,11 +4,10 @@ from cpl.core.pipes.ip_address_pipe import IPAddressPipe class TestService: - def __init__(self, provider: ServiceProviderABC, ip_pipe: IPAddressPipe): + def __init__(self, provider: ServiceProviderABC): self._provider = provider - self._ip_pipe = ip_pipe def run(self): Console.write_line("Hello World!", self._provider) ip = [192, 168, 178, 30] - Console.write_line(ip, self._ip_pipe.transform(ip)) + Console.write_line(ip, IPAddressPipe.to_str(ip)) diff --git a/tests/custom/general/src/general/test_startup_extension.py b/tests/custom/general/src/general/test_startup_extension.py index cd754313..7bb2e3be 100644 --- a/tests/custom/general/src/general/test_startup_extension.py +++ b/tests/custom/general/src/general/test_startup_extension.py @@ -1,16 +1,16 @@ from cpl.core.application import StartupExtensionABC -from cpl.core.configuration import ConfigurationABC +from cpl.core.configuration import Configuration from cpl.core.console import Console from cpl.core.dependency_injection import ServiceCollectionABC -from cpl.core.environment import ApplicationEnvironmentABC +from cpl.core.environment import Environment class TestStartupExtension(StartupExtensionABC): def __init__(self): StartupExtensionABC.__init__(self) - def configure_configuration(self, config: ConfigurationABC, env: ApplicationEnvironmentABC): + def configure_configuration(self, config: Configuration, env: Environment): Console.write_line("config") - def configure_services(self, services: ServiceCollectionABC, env: ApplicationEnvironmentABC): + def configure_services(self, services: ServiceCollectionABC, env: Environment): Console.write_line("services") diff --git a/tests/custom/translation/src/translation/startup.py b/tests/custom/translation/src/translation/startup.py index 328f969d..2e07b1e3 100644 --- a/tests/custom/translation/src/translation/startup.py +++ b/tests/custom/translation/src/translation/startup.py @@ -1,7 +1,7 @@ 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 +from cpl.core.environment import Environment class Startup(StartupABC): @@ -9,13 +9,13 @@ class Startup(StartupABC): StartupABC.__init__(self) def configure_configuration( - self, configuration: ConfigurationABC, environment: ApplicationEnvironment + self, configuration: ConfigurationABC, environment: Environment ) -> ConfigurationABC: configuration.add_json_file("appsettings.json") return configuration def configure_services( - self, services: ServiceCollectionABC, environment: ApplicationEnvironment + self, services: ServiceCollectionABC, environment: Environment ) -> ServiceProviderABC: services.add_translation() return services.build_service_provider() diff --git a/tests/generated/simple-app/LICENSE b/tests/generated/simple-app/LICENSE deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-app/README.md b/tests/generated/simple-app/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-app/appsettings.json b/tests/generated/simple-app/appsettings.json deleted file mode 100644 index 629e6ebd..00000000 --- a/tests/generated/simple-app/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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" - } -} diff --git a/tests/generated/simple-app/cpl-workspace.json b/tests/generated/simple-app/cpl-workspace.json deleted file mode 100644 index 0ed056c2..00000000 --- a/tests/generated/simple-app/cpl-workspace.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "WorkspaceSettings": { - "DefaultProject": "simple-app", - "Projects": { - "simple-app": "src/simple_app/simple-app.json" - } - } -} \ No newline at end of file diff --git a/tests/generated/simple-app/cpl.json b/tests/generated/simple-app/cpl.json deleted file mode 100644 index 1af0f6e6..00000000 --- a/tests/generated/simple-app/cpl.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-app", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "src", - "OutputPath": "dist", - "Main": "main", - "EntryPoint": "simple-app", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {} - } -} \ No newline at end of file diff --git a/tests/generated/simple-app/src/application.py b/tests/generated/simple-app/src/application.py deleted file mode 100644 index 27b56845..00000000 --- a/tests/generated/simple-app/src/application.py +++ /dev/null @@ -1,15 +0,0 @@ -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") diff --git a/tests/generated/simple-app/src/main.py b/tests/generated/simple-app/src/main.py deleted file mode 100644 index 6a3c180e..00000000 --- a/tests/generated/simple-app/src/main.py +++ /dev/null @@ -1,12 +0,0 @@ -from cpl.core.application import ApplicationBuilder - -from application import Application - - -def main(): - app_builder = ApplicationBuilder(Application) - app_builder.build().run() - - -if __name__ == "__main__": - main() diff --git a/tests/generated/simple-app/src/simple_app/__init__.py b/tests/generated/simple-app/src/simple_app/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-app/src/simple_app/application.py b/tests/generated/simple-app/src/simple_app/application.py deleted file mode 100644 index 27b56845..00000000 --- a/tests/generated/simple-app/src/simple_app/application.py +++ /dev/null @@ -1,15 +0,0 @@ -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") diff --git a/tests/generated/simple-app/src/simple_app/main.py b/tests/generated/simple-app/src/simple_app/main.py deleted file mode 100644 index 5f4775d6..00000000 --- a/tests/generated/simple-app/src/simple_app/main.py +++ /dev/null @@ -1,12 +0,0 @@ -from cpl.core.application import ApplicationBuilder - -from simple_app.application import Application - - -def main(): - app_builder = ApplicationBuilder(Application) - app_builder.build().run() - - -if __name__ == "__main__": - main() diff --git a/tests/generated/simple-app/src/simple_app/simple-app.json b/tests/generated/simple-app/src/simple_app/simple-app.json deleted file mode 100644 index 3aa9d743..00000000 --- a/tests/generated/simple-app/src/simple_app/simple-app.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-app", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.1rc2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "", - "OutputPath": "../../dist", - "Main": "simple_app.main", - "EntryPoint": "simple-app", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {}, - "ProjectReferences": [] - } -} \ No newline at end of file diff --git a/tests/generated/simple-app/src/tests/__init__.py b/tests/generated/simple-app/src/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-console/LICENSE b/tests/generated/simple-console/LICENSE deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-console/README.md b/tests/generated/simple-console/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-console/appsettings.json b/tests/generated/simple-console/appsettings.json deleted file mode 100644 index 629e6ebd..00000000 --- a/tests/generated/simple-console/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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" - } -} diff --git a/tests/generated/simple-console/cpl-workspace.json b/tests/generated/simple-console/cpl-workspace.json deleted file mode 100644 index 449bc77d..00000000 --- a/tests/generated/simple-console/cpl-workspace.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "WorkspaceSettings": { - "DefaultProject": "simple-console", - "Projects": { - "simple-console": "src/simple_console/simple-console.json" - } - } -} \ No newline at end of file diff --git a/tests/generated/simple-console/cpl.json b/tests/generated/simple-console/cpl.json deleted file mode 100644 index 5ddc2f0f..00000000 --- a/tests/generated/simple-console/cpl.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-console", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "src", - "OutputPath": "dist", - "Main": "main", - "EntryPoint": "simple-console", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {} - } -} \ No newline at end of file diff --git a/tests/generated/simple-console/src/main.py b/tests/generated/simple-console/src/main.py deleted file mode 100644 index 894b0e20..00000000 --- a/tests/generated/simple-console/src/main.py +++ /dev/null @@ -1,9 +0,0 @@ -from cpl.core.console import Console - - -def main(): - Console.write_line("Hello World") - - -if __name__ == "__main__": - main() diff --git a/tests/generated/simple-console/src/simple_console/__init__.py b/tests/generated/simple-console/src/simple_console/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-console/src/simple_console/main.py b/tests/generated/simple-console/src/simple_console/main.py deleted file mode 100644 index 894b0e20..00000000 --- a/tests/generated/simple-console/src/simple_console/main.py +++ /dev/null @@ -1,9 +0,0 @@ -from cpl.core.console import Console - - -def main(): - Console.write_line("Hello World") - - -if __name__ == "__main__": - main() diff --git a/tests/generated/simple-console/src/simple_console/simple-console.json b/tests/generated/simple-console/src/simple_console/simple-console.json deleted file mode 100644 index 24d5c821..00000000 --- a/tests/generated/simple-console/src/simple_console/simple-console.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-console", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.1rc2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "", - "OutputPath": "../../dist", - "Main": "simple_console.main", - "EntryPoint": "simple-console", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {}, - "ProjectReferences": [] - } -} \ No newline at end of file diff --git a/tests/generated/simple-console/src/tests/__init__.py b/tests/generated/simple-console/src/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-di/LICENSE b/tests/generated/simple-di/LICENSE deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-di/README.md b/tests/generated/simple-di/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-di/appsettings.json b/tests/generated/simple-di/appsettings.json deleted file mode 100644 index 629e6ebd..00000000 --- a/tests/generated/simple-di/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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" - } -} diff --git a/tests/generated/simple-di/cpl-workspace.json b/tests/generated/simple-di/cpl-workspace.json deleted file mode 100644 index 269f9340..00000000 --- a/tests/generated/simple-di/cpl-workspace.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "WorkspaceSettings": { - "DefaultProject": "simple-di", - "Projects": { - "simple-di": "src/simple_di/simple-di.json" - } - } -} \ No newline at end of file diff --git a/tests/generated/simple-di/cpl.json b/tests/generated/simple-di/cpl.json deleted file mode 100644 index a048da7f..00000000 --- a/tests/generated/simple-di/cpl.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-di", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.2.dev1" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "src", - "OutputPath": "dist", - "Main": "main", - "EntryPoint": "simple-di", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {} - } -} \ No newline at end of file diff --git a/tests/generated/simple-di/src/main.py b/tests/generated/simple-di/src/main.py deleted file mode 100644 index a54b90aa..00000000 --- a/tests/generated/simple-di/src/main.py +++ /dev/null @@ -1,23 +0,0 @@ -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() diff --git a/tests/generated/simple-di/src/simple_di/__init__.py b/tests/generated/simple-di/src/simple_di/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-di/src/simple_di/main.py b/tests/generated/simple-di/src/simple_di/main.py deleted file mode 100644 index a54b90aa..00000000 --- a/tests/generated/simple-di/src/simple_di/main.py +++ /dev/null @@ -1,23 +0,0 @@ -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() diff --git a/tests/generated/simple-di/src/simple_di/simple-di.json b/tests/generated/simple-di/src/simple_di/simple-di.json deleted file mode 100644 index 54751fcc..00000000 --- a/tests/generated/simple-di/src/simple_di/simple-di.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-di", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.1rc2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "", - "OutputPath": "../../dist", - "Main": "simple_di.main", - "EntryPoint": "simple-di", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {}, - "ProjectReferences": [] - } -} \ No newline at end of file diff --git a/tests/generated/simple-di/src/tests/__init__.py b/tests/generated/simple-di/src/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-startup-app/LICENSE b/tests/generated/simple-startup-app/LICENSE deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-startup-app/README.md b/tests/generated/simple-startup-app/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-startup-app/appsettings.json b/tests/generated/simple-startup-app/appsettings.json deleted file mode 100644 index 629e6ebd..00000000 --- a/tests/generated/simple-startup-app/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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" - } -} diff --git a/tests/generated/simple-startup-app/cpl-workspace.json b/tests/generated/simple-startup-app/cpl-workspace.json deleted file mode 100644 index 9fe5c55c..00000000 --- a/tests/generated/simple-startup-app/cpl-workspace.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "WorkspaceSettings": { - "DefaultProject": "simple-startup-app", - "Projects": { - "simple-startup-app": "src/simple_startup_app/simple-startup-app.json" - } - } -} \ No newline at end of file diff --git a/tests/generated/simple-startup-app/src/simple_startup_app/__init__.py b/tests/generated/simple-startup-app/src/simple_startup_app/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/simple-startup-app/src/simple_startup_app/application.py b/tests/generated/simple-startup-app/src/simple_startup_app/application.py deleted file mode 100644 index 27b56845..00000000 --- a/tests/generated/simple-startup-app/src/simple_startup_app/application.py +++ /dev/null @@ -1,15 +0,0 @@ -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") diff --git a/tests/generated/simple-startup-app/src/simple_startup_app/main.py b/tests/generated/simple-startup-app/src/simple_startup_app/main.py deleted file mode 100644 index f5747121..00000000 --- a/tests/generated/simple-startup-app/src/simple_startup_app/main.py +++ /dev/null @@ -1,14 +0,0 @@ -from cpl.core.application import ApplicationBuilder - -from simple_startup_app.application import Application -from simple_startup_app.startup import Startup - - -def main(): - app_builder = ApplicationBuilder(Application) - app_builder.use_startup(Startup) - app_builder.build().run() - - -if __name__ == "__main__": - main() diff --git a/tests/generated/simple-startup-app/src/simple_startup_app/simple-startup-app.json b/tests/generated/simple-startup-app/src/simple_startup_app/simple-startup-app.json deleted file mode 100644 index 80e4786f..00000000 --- a/tests/generated/simple-startup-app/src/simple_startup_app/simple-startup-app.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "ProjectSettings": { - "Name": "simple-startup-app", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.1rc2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "", - "OutputPath": "../../dist", - "Main": "simple_startup_app.main", - "EntryPoint": "simple-startup-app", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {}, - "ProjectReferences": [] - } -} \ No newline at end of file diff --git a/tests/generated/simple-startup-app/src/simple_startup_app/startup.py b/tests/generated/simple-startup-app/src/simple_startup_app/startup.py deleted file mode 100644 index cd2c48a8..00000000 --- a/tests/generated/simple-startup-app/src/simple_startup_app/startup.py +++ /dev/null @@ -1,18 +0,0 @@ -from cpl.core.application import StartupABC -from cpl.core.configuration import ConfigurationABC -from cpl.core.dependency_injection import ServiceProviderABC, ServiceCollectionABC - - -class Startup(StartupABC): - def __init__(self, config: ConfigurationABC, services: ServiceCollectionABC): - StartupABC.__init__(self) - - self._configuration = config - self._environment = self._configuration.environment - self._services = services - - def configure_configuration(self) -> ConfigurationABC: - return self._configuration - - def configure_services(self) -> ServiceProviderABC: - return self._services.build_service_provider() diff --git a/tests/generated/simple-startup-app/src/tests/__init__.py b/tests/generated/simple-startup-app/src/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/startup-app/LICENSE b/tests/generated/startup-app/LICENSE deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/startup-app/README.md b/tests/generated/startup-app/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/generated/startup-app/cpl.json b/tests/generated/startup-app/cpl.json deleted file mode 100644 index 39de3a85..00000000 --- a/tests/generated/startup-app/cpl.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "ProjectSettings": { - "Name": "startup-app", - "Version": { - "Major": "0", - "Minor": "0", - "Micro": "0" - }, - "Author": "", - "AuthorEmail": "", - "Description": "", - "LongDescription": "", - "URL": "", - "CopyrightDate": "", - "CopyrightName": "", - "LicenseName": "", - "LicenseDescription": "", - "Dependencies": [ - "sh_cpl==2021.4.2" - ], - "PythonVersion": ">=3.9.2", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "src", - "OutputPath": "dist", - "Main": "main", - "EntryPoint": "startup-app", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {} - } -} \ No newline at end of file diff --git a/tests/generated/startup-app/src/application.py b/tests/generated/startup-app/src/application.py deleted file mode 100644 index 27b56845..00000000 --- a/tests/generated/startup-app/src/application.py +++ /dev/null @@ -1,15 +0,0 @@ -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") diff --git a/tests/generated/startup-app/src/main.py b/tests/generated/startup-app/src/main.py deleted file mode 100644 index 2097002b..00000000 --- a/tests/generated/startup-app/src/main.py +++ /dev/null @@ -1,14 +0,0 @@ -from cpl.core.application import ApplicationBuilder - -from application import Application -from startup import Startup - - -def main(): - app_builder = ApplicationBuilder(Application) - app_builder.use_startup(Startup) - app_builder.build().run() - - -if __name__ == "__main__": - main() diff --git a/tests/generated/startup-app/src/startup.py b/tests/generated/startup-app/src/startup.py deleted file mode 100644 index cd2c48a8..00000000 --- a/tests/generated/startup-app/src/startup.py +++ /dev/null @@ -1,18 +0,0 @@ -from cpl.core.application import StartupABC -from cpl.core.configuration import ConfigurationABC -from cpl.core.dependency_injection import ServiceProviderABC, ServiceCollectionABC - - -class Startup(StartupABC): - def __init__(self, config: ConfigurationABC, services: ServiceCollectionABC): - StartupABC.__init__(self) - - self._configuration = config - self._environment = self._configuration.environment - self._services = services - - def configure_configuration(self) -> ConfigurationABC: - return self._configuration - - def configure_services(self) -> ServiceProviderABC: - return self._services.build_service_provider() diff --git a/tests/generated/startup-app/src/tests/__init__.py b/tests/generated/startup-app/src/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tools/set_pip_urls/__init__.py b/tools/set_pip_urls/__init__.py deleted file mode 100644 index 8b137891..00000000 --- a/tools/set_pip_urls/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/set_pip_urls/application.py b/tools/set_pip_urls/application.py deleted file mode 100644 index ff2c8a02..00000000 --- a/tools/set_pip_urls/application.py +++ /dev/null @@ -1,45 +0,0 @@ -import json -import os -import sys -from typing import Optional - -from cpl.core.environment import EnvironmentNameEnum - -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 -from set_pip_urls.pip_settings import PIPSettings - - -class Application(ApplicationABC): - def __init__(self, config: ConfigurationABC, services: ServiceProviderABC): - ApplicationABC.__init__(self, config, services) - - self._pip_settings: Optional[PIPSettings] = config.get_configuration(PIPSettings) - - def configure(self): - self._configuration.parse_console_arguments(self._services) - - def main(self): - if self._pip_settings is None: - Console.error("appsettings.json not found") - sys.exit() - - url = None - match self._environment.environment_name: - case EnvironmentNameEnum.production.value: - url = self._pip_settings.production - case EnvironmentNameEnum.staging.value: - url = self._pip_settings.staging - case EnvironmentNameEnum.development.value: - url = self._pip_settings.development - - cli_json = {"CLI": {"PipPath": url}} - file = os.path.abspath( - os.path.join(self._environment.working_directory, "../../src/cpl_cli", "appsettings.json") - ) - Console.write_line(f"Writing PipPath: {url} to {file}") - with open(file, "w") as f: - f.write(json.dumps(cli_json, indent=2)) - f.close() diff --git a/tools/set_pip_urls/appsettings.json b/tools/set_pip_urls/appsettings.json deleted file mode 100644 index 25b04f41..00000000 --- a/tools/set_pip_urls/appsettings.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "PIPSettings": { - "production": "https://pip.sh-edraft.de", - "staging": "https://pip-exp.sh-edraft.de", - "development": "https://pip-dev.sh-edraft.de" - } -} diff --git a/tools/set_pip_urls/main.py b/tools/set_pip_urls/main.py deleted file mode 100644 index 63410b99..00000000 --- a/tools/set_pip_urls/main.py +++ /dev/null @@ -1,14 +0,0 @@ -from cpl.core.application import ApplicationBuilder - -from set_pip_urls.application import Application -from set_pip_urls.startup import Startup - - -def main(): - app_builder = ApplicationBuilder(Application) - app_builder.use_startup(Startup) - app_builder.build().run() - - -if __name__ == "__main__": - main() diff --git a/tools/set_pip_urls/pip_settings.py b/tools/set_pip_urls/pip_settings.py deleted file mode 100644 index eebcf531..00000000 --- a/tools/set_pip_urls/pip_settings.py +++ /dev/null @@ -1,22 +0,0 @@ -from cpl.core.configuration.configuration_model_abc import ConfigurationModelABC - - -class PIPSettings(ConfigurationModelABC): - def __init__(self, production: str = None, staging: str = None, development: str = None): - ConfigurationModelABC.__init__(self) - - self._production = production - self._staging = staging - self._development = development - - @property - def production(self): - return self._production - - @property - def staging(self): - return self._staging - - @property - def development(self): - return self._development diff --git a/tools/set_pip_urls/set-pip-urls.json b/tools/set_pip_urls/set-pip-urls.json deleted file mode 100644 index 348e4aa5..00000000 --- a/tools/set_pip_urls/set-pip-urls.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "ProjectSettings": { - "Name": "set-pip-urls", - "Version": { - "Major": "2024", - "Minor": "7", - "Micro": "0" - }, - "Author": "Sven Heidemann", - "AuthorEmail": "sven.heidemann@sh-edraft.de", - "Description": "CPL internal tool to set pip URL for CLI by environment", - "LongDescription": "CPL internal tool to set pip URL for CLI by environment", - "URL": "https://www.sh-edraft.de", - "CopyrightDate": "2022", - "CopyrightName": "sh-edraft.de", - "LicenseName": "MIT", - "LicenseDescription": "MIT, see LICENSE for more details.", - "Dependencies": [ - "cpl-core==2022.12.0" - ], - "PythonVersion": ">=3.10.4", - "PythonPath": {}, - "Classifiers": [], - "DevDependencies": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "", - "OutputPath": "../../dist", - "Main": "set_pip_url.main", - "EntryPoint": "set-pip-url", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {}, - "ProjectReferences": [] - } -} \ No newline at end of file diff --git a/tools/set_pip_urls/startup.py b/tools/set_pip_urls/startup.py deleted file mode 100644 index 33c5b7a7..00000000 --- a/tools/set_pip_urls/startup.py +++ /dev/null @@ -1,21 +0,0 @@ -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: - configuration.add_environment_variables("CPL_") - configuration.add_json_file("appsettings.json", optional=False, output=False) - return configuration - - def configure_services( - self, services: ServiceCollectionABC, environment: ApplicationEnvironment - ) -> ServiceProviderABC: - return services.build_service_provider() diff --git a/tools/set_version/__init__.py b/tools/set_version/__init__.py deleted file mode 100644 index 8b137891..00000000 --- a/tools/set_version/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tools/set_version/application.py b/tools/set_version/application.py deleted file mode 100644 index 1be33a03..00000000 --- a/tools/set_version/application.py +++ /dev/null @@ -1,124 +0,0 @@ -import os -import traceback - -from cpl_cli.configuration import ProjectSettings -from cpl.core.utils import String - -from cpl_cli.configuration.version_settings_name_enum import VersionSettingsNameEnum -from cpl_cli.configuration.workspace_settings import WorkspaceSettings -from cpl.core.application.application_abc import ApplicationABC -from cpl.core.configuration.configuration_abc import ConfigurationABC -from cpl.core.console.console import Console -from cpl.core.dependency_injection.service_provider_abc import ServiceProviderABC -from cpl.core.pipes.version_pipe import VersionPipe -from set_version.git_service import GitService -from set_version.version_setter_service import VersionSetterService - - -class Application(ApplicationABC): - def __init__(self, config: ConfigurationABC, services: ServiceProviderABC): - ApplicationABC.__init__(self, config, services) - - self._workspace: WorkspaceSettings = config.get_configuration(WorkspaceSettings) - - self._git_service: GitService = self._services.get_service(GitService) - self._version_setter: VersionSetterService = self._services.get_service(VersionSetterService) - self._version_pipe: VersionPipe = self._services.get_service(VersionPipe) - - def configure(self): - self._configuration.parse_console_arguments(self._services) - - def main(self): - Console.write_line("Set versions:") - - args = self._configuration.additional_arguments - version = {} - branch = "" - suffix = "" - force = False - if "--force" in args: - args.remove("--force") - force = True - - if len(args) > 1: - Console.error(f'Unexpected argument(s): {", ".join(args[1:])}') - return - - if len(args) == 1: - suffix = args[0] - - try: - branch = self._git_service.get_active_branch_name() - Console.write_line(f"Found branch: {branch}") - except Exception as e: - Console.error("Branch not found", traceback.format_exc()) - return - - try: - if suffix != "": - self._configuration.add_json_file( - self._workspace.projects[self._workspace.default_project], optional=False, output=False - ) - ps: ProjectSettings = self._configuration.get_configuration(ProjectSettings) - - version[VersionSettingsNameEnum.major.value] = ps.version.major - version[VersionSettingsNameEnum.minor.value] = ps.version.minor - version[VersionSettingsNameEnum.micro.value] = suffix - elif branch.startswith("#"): - self._configuration.add_json_file( - self._workspace.projects[self._workspace.default_project], optional=False, output=False - ) - ps: ProjectSettings = self._configuration.get_configuration(ProjectSettings) - - version[VersionSettingsNameEnum.major.value] = ps.version.major - version[VersionSettingsNameEnum.minor.value] = ps.version.minor - version[VersionSettingsNameEnum.micro.value] = f'dev{branch.split("#")[1]}' - else: - version[VersionSettingsNameEnum.major.value] = branch.split(".")[0] - version[VersionSettingsNameEnum.minor.value] = branch.split(".")[1] - if len(branch.split(".")) == 2: - if suffix == "": - suffix = "0" - version[VersionSettingsNameEnum.micro.value] = f"{suffix}" - else: - version[VersionSettingsNameEnum.micro.value] = f'{branch.split(".")[2]}{suffix}' - except Exception as e: - Console.error(f"Branch {branch} does not contain valid version") - return - - diff_paths = [] - for file in self._git_service.get_diff_files(): - if file.startswith("tools"): - continue - - if "/" in file: - file = file.split("/")[1] - else: - file = os.path.basename(os.path.dirname(file)) - - if file in diff_paths: - continue - - diff_paths.append(file) - - try: - skipped = [] - for project in self._workspace.projects: - if project not in diff_paths and String.convert_to_snake_case(project) not in diff_paths and not force: - # Console.write_line(f'Skipping {project} due to missing changes') - skipped.append(project) - continue - - Console.write_line(f"Set dependencies {self._version_pipe.transform(version)} for {project}") - self._version_setter.set_dependencies( - self._workspace.projects[project], version, "Dependencies", skipped=skipped - ) - self._version_setter.set_dependencies( - self._workspace.projects[project], version, "DevDependencies", skipped=skipped - ) - - Console.write_line(f"Set version {self._version_pipe.transform(version)} for {project}") - self._version_setter.set_version(self._workspace.projects[project], version) - except Exception as e: - Console.error("Version could not be set", traceback.format_exc()) - return diff --git a/tools/set_version/git_service.py b/tools/set_version/git_service.py deleted file mode 100644 index dd82171f..00000000 --- a/tools/set_version/git_service.py +++ /dev/null @@ -1,17 +0,0 @@ -import os - -from cpl.core.environment import ApplicationEnvironmentABC -from git import Repo - - -class GitService: - def __init__(self, env: ApplicationEnvironmentABC): - self._env = env - self._repo = Repo(env.working_directory) - - def get_active_branch_name(self) -> str: - branch = self._repo.active_branch - return branch.name - - def get_diff_files(self) -> list[str]: - return [item.a_path for item in self._repo.index.diff(None)] diff --git a/tools/set_version/main.py b/tools/set_version/main.py deleted file mode 100644 index a33c9969..00000000 --- a/tools/set_version/main.py +++ /dev/null @@ -1,14 +0,0 @@ -from cpl.core.application import ApplicationBuilder - -from set_version.application import Application -from set_version.startup import Startup - - -def main(): - app_builder = ApplicationBuilder(Application) - app_builder.use_startup(Startup) - app_builder.build().run() - - -if __name__ == "__main__": - main() diff --git a/tools/set_version/set-version.json b/tools/set_version/set-version.json deleted file mode 100644 index 91e57f59..00000000 --- a/tools/set_version/set-version.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "ProjectSettings": { - "Name": "set-version", - "Version": { - "Major": "2024", - "Minor": "7", - "Micro": "0" - }, - "Author": "Sven Heidemann", - "AuthorEmail": "sven.heidemann@sh-edraft.de", - "Description": "CPL internal tool to set version from branch name", - "LongDescription": "CPL internal tool to set version from branch name", - "URL": "https://www.sh-edraft.de", - "CopyrightDate": "2022", - "CopyrightName": "sh-edraft.de", - "LicenseName": "MIT", - "LicenseDescription": "MIT, see LICENSE for more details.", - "Dependencies": [ - "cpl-core>=2024.6.2024.07.0", - "GitPython>=3.1.29" - ], - "DevDependencies": [], - "PythonVersion": ">=3.10.4", - "PythonPath": {}, - "Classifiers": [] - }, - "BuildSettings": { - "ProjectType": "console", - "SourcePath": "", - "OutputPath": "../../dist", - "Main": "set_version.main", - "EntryPoint": "set-version", - "IncludePackageData": false, - "Included": [], - "Excluded": [ - "*/__pycache__", - "*/logs", - "*/tests" - ], - "PackageData": {}, - "ProjectReferences": [] - } -} \ No newline at end of file diff --git a/tools/set_version/startup.py b/tools/set_version/startup.py deleted file mode 100644 index 41720a71..00000000 --- a/tools/set_version/startup.py +++ /dev/null @@ -1,34 +0,0 @@ -import os - -from cpl_cli.configuration import WorkspaceSettings -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 -from cpl.core.pipes.version_pipe import VersionPipe -from set_version.git_service import GitService -from set_version.version_setter_service import VersionSetterService - - -class Startup(StartupABC): - def __init__(self): - StartupABC.__init__(self) - - def configure_configuration( - self, configuration: ConfigurationABC, environment: ApplicationEnvironment - ) -> ConfigurationABC: - configuration.add_json_file("cpl-workspace.json", optional=True, output=False) - if configuration.get_configuration(WorkspaceSettings) is None: - environment.set_working_directory(os.path.join(environment.working_directory, "../../")) - configuration.add_json_file("cpl-workspace.json", optional=False, output=False) - - return configuration - - def configure_services( - self, services: ServiceCollectionABC, environment: ApplicationEnvironment - ) -> ServiceProviderABC: - services.add_pipes() - services.add_singleton(GitService) - services.add_transient(VersionSetterService) - - return services.build_service_provider() diff --git a/tools/set_version/version_setter_service.py b/tools/set_version/version_setter_service.py deleted file mode 100644 index edb086cf..00000000 --- a/tools/set_version/version_setter_service.py +++ /dev/null @@ -1,62 +0,0 @@ -import json -import os -from string import ascii_letters - -from cpl.core.environment import ApplicationEnvironmentABC -from cpl.core.utils import String - - -class VersionSetterService: - def __init__(self, env: ApplicationEnvironmentABC): - self._env = env - - def _read_file(self, file: str) -> dict: - project_json = {} - with open(os.path.join(self._env.working_directory, file), "r", encoding="utf-8") as f: - # load json - project_json = json.load(f) - f.close() - - return project_json - - def _write_file(self, file: str, project_json: dict): - with open(os.path.join(self._env.working_directory, file), "w", encoding="utf-8") as f: - f.write(json.dumps(project_json, indent=2)) - f.close() - - def set_version(self, file: str, version: dict): - project_json = self._read_file(file) - project_json["ProjectSettings"]["Version"] = version - self._write_file(file, project_json) - - def set_dependencies(self, file: str, version: dict, key: str, skipped=None): - project_json = self._read_file(file) - if key not in project_json["ProjectSettings"]: - project_json["ProjectSettings"][key] = [] - - dependencies = project_json["ProjectSettings"][key] - new_deps = [] - for dependency in dependencies: - if not dependency.startswith("cpl-"): - new_deps.append(dependency) - continue - - dep_version = dependency.split("=")[1] - dep_name = dependency.split("=")[0] - if dep_name[len(dep_name) - 1] not in ascii_letters: - dep_name = dep_name[: len(dep_name) - 1] - - if ( - skipped is not None - and (dep_name in skipped or String.convert_to_snake_case(dep_name) in skipped) - or dep_version == "" - ): - new_deps.append(dependency) - continue - - new_deps.append( - dependency.replace(dep_version, f'{version["Major"]}.{version["Minor"]}.{version["Micro"]}') - ) - - project_json["ProjectSettings"][key] = new_deps - self._write_file(file, project_json) diff --git a/unittests/unittests_cli/add_test_case.py b/unittests/unittests_cli/add_test_case.py index 2892bec1..b7e2dd14 100644 --- a/unittests/unittests_cli/add_test_case.py +++ b/unittests/unittests_cli/add_test_case.py @@ -12,7 +12,7 @@ class AddTestCase(CommandTestCase): CommandTestCase.__init__(self, method_name) self._source = "add-test-project" self._target = "add-test-library" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" def _get_project_settings(self): with open(os.path.join(os.getcwd(), self._project_file), "r", encoding="utf-8") as cfg: @@ -37,6 +37,6 @@ class AddTestCase(CommandTestCase): self.assertIn("ProjectReferences", settings["BuildSettings"]) self.assertIn("BuildSettings", settings) self.assertIn( - f"../{String.convert_to_snake_case(self._target)}/{self._target}.json", + f"../{String.to_snake_case(self._target)}/{self._target}.json", settings["BuildSettings"]["ProjectReferences"], ) diff --git a/unittests/unittests_cli/build_test_case.py b/unittests/unittests_cli/build_test_case.py index 6e97bbbd..ab53641d 100644 --- a/unittests/unittests_cli/build_test_case.py +++ b/unittests/unittests_cli/build_test_case.py @@ -13,7 +13,7 @@ class BuildTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "build-test-source" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" def _get_project_settings(self): with open(os.path.join(os.getcwd(), self._project_file), "r", encoding="utf-8") as cfg: @@ -72,15 +72,15 @@ class BuildTestCase(CommandTestCase): def test_build(self): CLICommands.build() dist_path = "./dist" - full_dist_path = f"{dist_path}/{self._source}/build/{String.convert_to_snake_case(self._source)}" + full_dist_path = f"{dist_path}/{self._source}/build/{String.to_snake_case(self._source)}" self.assertTrue(os.path.exists(dist_path)) self.assertTrue(os.path.exists(full_dist_path)) self.assertFalse( - self._are_dir_trees_equal(f"./src/{String.convert_to_snake_case(self._source)}", full_dist_path) + self._are_dir_trees_equal(f"./src/{String.to_snake_case(self._source)}", full_dist_path) ) with open(f"{full_dist_path}/{self._source}.json", "w") as file: file.write(json.dumps(self._get_project_settings(), indent=2)) file.close() self.assertTrue( - self._are_dir_trees_equal(f"./src/{String.convert_to_snake_case(self._source)}", full_dist_path) + self._are_dir_trees_equal(f"./src/{String.to_snake_case(self._source)}", full_dist_path) ) diff --git a/unittests/unittests_cli/generate_test_case.py b/unittests/unittests_cli/generate_test_case.py index 3bc132d7..bff74fcc 100644 --- a/unittests/unittests_cli/generate_test_case.py +++ b/unittests/unittests_cli/generate_test_case.py @@ -35,10 +35,10 @@ class GenerateTestCase(CommandTestCase): file = f'GeneratedFile{"OnReady" if schematic == "event" else ""}' excepted_path = f'generated_file{"_on_ready" if schematic == "event" else ""}{suffix}.py' if path is not None: - excepted_path = f'{self._project}/src/{String.convert_to_snake_case(self._project)}/{path}/generated_file_in_project{"_on_ready" if schematic == "event" else ""}{suffix}.py' + excepted_path = f'{self._project}/src/{String.to_snake_case(self._project)}/{path}/generated_file_in_project{"_on_ready" if schematic == "event" else ""}{suffix}.py' if enter: os.chdir(path) - excepted_path = f'{path}/src/{String.convert_to_snake_case(self._project)}/generated_file_in_project{"_on_ready" if schematic == "event" else ""}{suffix}.py' + excepted_path = f'{path}/src/{String.to_snake_case(self._project)}/generated_file_in_project{"_on_ready" if schematic == "event" else ""}{suffix}.py' file = f'{path}/GeneratedFileInProject{"OnReady" if schematic == "event" else ""}' @@ -51,7 +51,7 @@ class GenerateTestCase(CommandTestCase): self._test_file("abc", "_abc", path=self._t_path) self._test_file("abc", "_abc", path=f"{self._t_path}/{self._t_path}") self._test_file_with_project("abc", "_abc", path=self._project) - os.chdir(f"src/{String.convert_to_snake_case(self._project)}") + os.chdir(f"src/{String.to_snake_case(self._project)}") self._test_file_with_project("abc", "_abc", path="test", enter=False) def test_class(self): @@ -63,7 +63,7 @@ class GenerateTestCase(CommandTestCase): self._test_file("enum", "_enum") self._test_file("enum", "_enum", path=self._t_path) self._test_file_with_project("enum", "_enum", path=self._project) - os.chdir(f"src/{String.convert_to_snake_case(self._project)}") + os.chdir(f"src/{String.to_snake_case(self._project)}") self._test_file_with_project("enum", "_enum", path="test", enter=False) def test_pipe(self): diff --git a/unittests/unittests_cli/install_test_case.py b/unittests/unittests_cli/install_test_case.py index e9498147..d9e41b4d 100644 --- a/unittests/unittests_cli/install_test_case.py +++ b/unittests/unittests_cli/install_test_case.py @@ -15,7 +15,7 @@ class InstallTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "install-test-source" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" def _get_project_settings(self): with open(os.path.join(os.getcwd(), self._project_file), "r", encoding="utf-8") as cfg: diff --git a/unittests/unittests_cli/new_test_case.py b/unittests/unittests_cli/new_test_case.py index 622cf5c5..c342a022 100644 --- a/unittests/unittests_cli/new_test_case.py +++ b/unittests/unittests_cli/new_test_case.py @@ -28,10 +28,10 @@ class NewTestCase(CommandTestCase): base = name.split("/")[0] name = name.replace(f'{name.split("/")[0]}/', "") - project_path = os.path.abspath(os.path.join(PLAYGROUND_PATH, name, base, String.convert_to_snake_case(name))) + project_path = os.path.abspath(os.path.join(PLAYGROUND_PATH, name, base, String.to_snake_case(name))) if without_ws: project_path = os.path.abspath( - os.path.join(PLAYGROUND_PATH, base, name, "src/", String.convert_to_snake_case(name)) + os.path.join(PLAYGROUND_PATH, base, name, "src/", String.to_snake_case(name)) ) with self.subTest(msg="Project json exists"): @@ -92,7 +92,7 @@ class NewTestCase(CommandTestCase): name = name.replace(f'{name.split("/")[0]}/', "") project_path = os.path.abspath( - os.path.join(PLAYGROUND_PATH, workspace_name, base, String.convert_to_snake_case(name)) + os.path.join(PLAYGROUND_PATH, workspace_name, base, String.to_snake_case(name)) ) self.assertTrue(os.path.exists(project_path)) self.assertTrue(os.path.join(project_path, f"{name}.json")) @@ -113,7 +113,7 @@ class NewTestCase(CommandTestCase): self.assertTrue(os.path.exists(workspace_path)) project_path = os.path.abspath( - os.path.join(PLAYGROUND_PATH, workspace_name, f"src/{directory}", String.convert_to_snake_case(name)) + os.path.join(PLAYGROUND_PATH, workspace_name, f"src/{directory}", String.to_snake_case(name)) ) self.assertTrue(os.path.exists(project_path)) project_file = os.path.join(project_path, f"{name}.json") @@ -129,7 +129,7 @@ class NewTestCase(CommandTestCase): self.assertEqual(project_settings["Name"], name) self.assertEqual(build_settings["ProjectType"], "library") self.assertEqual(build_settings["OutputPath"], "../../dist") - self.assertEqual(build_settings["Main"], f"{String.convert_to_snake_case(name)}.main") + self.assertEqual(build_settings["Main"], f"{String.to_snake_case(name)}.main") self.assertEqual(build_settings["EntryPoint"], name) def test_console(self): diff --git a/unittests/unittests_cli/publish_test_case.py b/unittests/unittests_cli/publish_test_case.py index 1e93ef86..c29cf881 100644 --- a/unittests/unittests_cli/publish_test_case.py +++ b/unittests/unittests_cli/publish_test_case.py @@ -13,7 +13,7 @@ class PublishTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "publish-test-source" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" def setUp(self): if not os.path.exists(PLAYGROUND_PATH): @@ -60,18 +60,18 @@ class PublishTestCase(CommandTestCase): CLICommands.publish() dist_path = "./dist" setup_path = f"{dist_path}/{self._source}/publish/setup" - full_dist_path = f"{dist_path}/{self._source}/publish/build/lib/{String.convert_to_snake_case(self._source)}" + full_dist_path = f"{dist_path}/{self._source}/publish/build/lib/{String.to_snake_case(self._source)}" self.assertTrue(os.path.exists(dist_path)) self.assertTrue(os.path.exists(setup_path)) self.assertTrue(os.path.exists(os.path.join(setup_path, f"{self._source}-0.0.0.tar.gz"))) self.assertTrue( os.path.exists( - os.path.join(setup_path, f"{String.convert_to_snake_case(self._source)}-0.0.0-py3-none-any.whl") + os.path.join(setup_path, f"{String.to_snake_case(self._source)}-0.0.0-py3-none-any.whl") ) ) self.assertTrue(os.path.exists(full_dist_path)) self.assertFalse( - self._are_dir_trees_equal(f"./src/{String.convert_to_snake_case(self._source)}", full_dist_path) + self._are_dir_trees_equal(f"./src/{String.to_snake_case(self._source)}", full_dist_path) ) shutil.copyfile(os.path.join(os.getcwd(), self._project_file), f"{full_dist_path}/{self._source}.json") @@ -81,5 +81,5 @@ class PublishTestCase(CommandTestCase): ) self.assertTrue( - self._are_dir_trees_equal(f"./src/{String.convert_to_snake_case(self._source)}", full_dist_path) + self._are_dir_trees_equal(f"./src/{String.to_snake_case(self._source)}", full_dist_path) ) diff --git a/unittests/unittests_cli/remove_test_case.py b/unittests/unittests_cli/remove_test_case.py index 16729537..e6b5555a 100644 --- a/unittests/unittests_cli/remove_test_case.py +++ b/unittests/unittests_cli/remove_test_case.py @@ -13,7 +13,7 @@ class RemoveTestCase(CommandTestCase): CommandTestCase.__init__(self, method_name) self._source = "add-test-project" self._target = "add-test-library" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" def _get_project_settings(self): with open(os.path.join(os.getcwd(), self._project_file), "r", encoding="utf-8") as cfg: @@ -36,7 +36,7 @@ class RemoveTestCase(CommandTestCase): def test_remove(self): CLICommands.remove(self._target) - path = os.path.abspath(os.path.join(os.getcwd(), f"../{String.convert_to_snake_case(self._target)}")) + path = os.path.abspath(os.path.join(os.getcwd(), f"../{String.to_snake_case(self._target)}")) self.assertTrue(os.path.exists(os.getcwd())) self.assertTrue(os.path.exists(os.path.join(os.getcwd(), self._project_file))) self.assertFalse(os.path.exists(path)) @@ -45,6 +45,6 @@ class RemoveTestCase(CommandTestCase): self.assertIn("ProjectReferences", settings["BuildSettings"]) self.assertIn("BuildSettings", settings) self.assertNotIn( - f"../{String.convert_to_snake_case(self._target)}/{self._target}.json", + f"../{String.to_snake_case(self._target)}/{self._target}.json", settings["BuildSettings"]["ProjectReferences"], ) diff --git a/unittests/unittests_cli/run_test_case.py b/unittests/unittests_cli/run_test_case.py index ed87b02a..5c5a5439 100644 --- a/unittests/unittests_cli/run_test_case.py +++ b/unittests/unittests_cli/run_test_case.py @@ -13,8 +13,8 @@ class RunTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "run-test" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" - self._application = f"src/{String.convert_to_snake_case(self._source)}/application.py" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" + self._application = f"src/{String.to_snake_case(self._source)}/application.py" self._test_code = f""" import json import os @@ -33,9 +33,9 @@ class RunTestCase(CommandTestCase): """ def _get_appsettings(self, is_dev=False): - appsettings = f"dist/{self._source}/build/{String.convert_to_snake_case(self._source)}/appsettings.json" + appsettings = f"dist/{self._source}/build/{String.to_snake_case(self._source)}/appsettings.json" if is_dev: - appsettings = f"src/{String.convert_to_snake_case(self._source)}/appsettings.json" + appsettings = f"src/{String.to_snake_case(self._source)}/appsettings.json" with open(os.path.join(os.getcwd(), appsettings), "r", encoding="utf-8") as cfg: # load json @@ -46,7 +46,7 @@ class RunTestCase(CommandTestCase): def _save_appsettings(self, settings: dict): with open( - os.path.join(os.getcwd(), f"src/{String.convert_to_snake_case(self._source)}/appsettings.json"), + os.path.join(os.getcwd(), f"src/{String.to_snake_case(self._source)}/appsettings.json"), "w", encoding="utf-8", ) as project_file: @@ -72,10 +72,10 @@ class RunTestCase(CommandTestCase): self.assertIn("WasStarted", settings["RunTest"]) self.assertEqual("True", settings["RunTest"]["WasStarted"]) self.assertNotEqual( - os.path.join(os.getcwd(), f"src/{String.convert_to_snake_case(self._source)}"), settings["RunTest"]["Path"] + os.path.join(os.getcwd(), f"src/{String.to_snake_case(self._source)}"), settings["RunTest"]["Path"] ) self.assertEqual( - os.path.join(os.getcwd(), f"dist/{self._source}/build/{String.convert_to_snake_case(self._source)}"), + os.path.join(os.getcwd(), f"dist/{self._source}/build/{String.to_snake_case(self._source)}"), settings["RunTest"]["Path"], ) @@ -87,10 +87,10 @@ class RunTestCase(CommandTestCase): self.assertIn("WasStarted", settings["RunTest"]) self.assertEqual("True", settings["RunTest"]["WasStarted"]) self.assertNotEqual( - os.path.join(os.getcwd(), f"src/{String.convert_to_snake_case(self._source)}"), settings["RunTest"]["Path"] + os.path.join(os.getcwd(), f"src/{String.to_snake_case(self._source)}"), settings["RunTest"]["Path"] ) self.assertEqual( - os.path.join(os.getcwd(), f"dist/{self._source}/build/{String.convert_to_snake_case(self._source)}"), + os.path.join(os.getcwd(), f"dist/{self._source}/build/{String.to_snake_case(self._source)}"), settings["RunTest"]["Path"], ) @@ -102,7 +102,7 @@ class RunTestCase(CommandTestCase): self.assertIn("WasStarted", settings["RunTest"]) self.assertEqual("True", settings["RunTest"]["WasStarted"]) self.assertEqual( - os.path.join(os.getcwd(), f"src/{String.convert_to_snake_case(self._source)}"), settings["RunTest"]["Path"] + os.path.join(os.getcwd(), f"src/{String.to_snake_case(self._source)}"), settings["RunTest"]["Path"] ) def test_run_dev_by_project(self): @@ -113,5 +113,5 @@ class RunTestCase(CommandTestCase): self.assertIn("WasStarted", settings["RunTest"]) self.assertEqual("True", settings["RunTest"]["WasStarted"]) self.assertEqual( - os.path.join(os.getcwd(), f"src/{String.convert_to_snake_case(self._source)}"), settings["RunTest"]["Path"] + os.path.join(os.getcwd(), f"src/{String.to_snake_case(self._source)}"), settings["RunTest"]["Path"] ) diff --git a/unittests/unittests_cli/start_test_case.py b/unittests/unittests_cli/start_test_case.py index f83cb1cf..a4ced71d 100644 --- a/unittests/unittests_cli/start_test_case.py +++ b/unittests/unittests_cli/start_test_case.py @@ -15,9 +15,9 @@ class StartTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "start-test" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" - self._appsettings = f"src/{String.convert_to_snake_case(self._source)}/appsettings.json" - self._application = f"src/{String.convert_to_snake_case(self._source)}/application.py" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" + self._appsettings = f"src/{String.to_snake_case(self._source)}/appsettings.json" + self._application = f"src/{String.to_snake_case(self._source)}/application.py" self._test_code = f""" import json import os @@ -39,9 +39,9 @@ class StartTestCase(CommandTestCase): """ def _get_appsettings(self, is_dev=False): - appsettings = f"dist/{self._source}/build/{String.convert_to_snake_case(self._source)}/appsettings.json" + appsettings = f"dist/{self._source}/build/{String.to_snake_case(self._source)}/appsettings.json" if is_dev: - appsettings = f"src/{String.convert_to_snake_case(self._source)}/appsettings.json" + appsettings = f"src/{String.to_snake_case(self._source)}/appsettings.json" with open(os.path.join(os.getcwd(), appsettings), "r", encoding="utf-8") as cfg: # load json @@ -52,7 +52,7 @@ class StartTestCase(CommandTestCase): def _save_appsettings(self, settings: dict): with open( - os.path.join(os.getcwd(), f"src/{String.convert_to_snake_case(self._source)}/appsettings.json"), + os.path.join(os.getcwd(), f"src/{String.to_snake_case(self._source)}/appsettings.json"), "w", encoding="utf-8", ) as project_file: diff --git a/unittests/unittests_cli/uninstall_test_case.py b/unittests/unittests_cli/uninstall_test_case.py index 7706e4ce..9867a0d2 100644 --- a/unittests/unittests_cli/uninstall_test_case.py +++ b/unittests/unittests_cli/uninstall_test_case.py @@ -15,7 +15,7 @@ class UninstallTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "uninstall-test-source" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" self._version = "1.7.3" self._package_name = "discord.py" self._package = f"{self._package_name}=={self._version}" diff --git a/unittests/unittests_cli/update_test_case.py b/unittests/unittests_cli/update_test_case.py index 6c563cd5..50b483c7 100644 --- a/unittests/unittests_cli/update_test_case.py +++ b/unittests/unittests_cli/update_test_case.py @@ -15,7 +15,7 @@ class UpdateTestCase(CommandTestCase): def __init__(self, method_name: str): CommandTestCase.__init__(self, method_name) self._source = "install-test-source" - self._project_file = f"src/{String.convert_to_snake_case(self._source)}/{self._source}.json" + self._project_file = f"src/{String.to_snake_case(self._source)}/{self._source}.json" self._old_version = "1.7.1" self._old_package_name = "discord.py" diff --git a/unittests/unittests_core/configuration/environment_test_case.py b/unittests/unittests_core/configuration/environment_test_case.py index a7a9ed84..c320394a 100644 --- a/unittests/unittests_core/configuration/environment_test_case.py +++ b/unittests/unittests_core/configuration/environment_test_case.py @@ -3,8 +3,8 @@ import unittest from _socket import gethostname from cpl.core.configuration import Configuration -from cpl.core.environment import ApplicationEnvironment, ApplicationEnvironmentABC -from cpl.core.environment import application_environment +from cpl.core.environment import Environment, EnvironmentABC +from cpl.core.environment import environment class EnvironmentTestCase(unittest.TestCase): @@ -13,15 +13,15 @@ class EnvironmentTestCase(unittest.TestCase): self._env = self._config.environment def test_app_env_created(self): - self.assertTrue(isinstance(self._env, ApplicationEnvironment)) - self.assertTrue(issubclass(type(self._env), ApplicationEnvironmentABC)) + self.assertTrue(isinstance(self._env, Environment)) + self.assertTrue(issubclass(type(self._env), EnvironmentABC)) def test_app_env_values_correct_when_default(self): self.assertEqual(self._env.environment_name, "production") self.assertEqual(self._env.application_name, "") self.assertEqual(self._env.customer, "") self.assertEqual(self._env.host_name, gethostname()) - self.assertEqual(self._env.working_directory, os.getcwd()) + self.assertEqual(self._env.cwd, os.getcwd()) self.assertEqual( self._env.runtime_directory, os.path.dirname(os.path.dirname(os.path.abspath(application_environment.__file__))), @@ -38,7 +38,7 @@ class EnvironmentTestCase(unittest.TestCase): self.assertEqual(self._env.application_name, "Core Tests") self.assertEqual(self._env.customer, "sh-edraft.de") self.assertEqual(self._env.host_name, gethostname()) - self.assertEqual(self._env.working_directory, os.getcwd()) + self.assertEqual(self._env.cwd, os.getcwd()) self.assertEqual( self._env.runtime_directory, os.path.dirname(os.path.dirname(os.path.abspath(application_environment.__file__))), @@ -46,7 +46,7 @@ class EnvironmentTestCase(unittest.TestCase): def test_app_env_set_dirs(self): new_cwd = os.path.join(os.getcwd(), "../") - self._env.set_working_directory(new_cwd) - self.assertEqual(self._env.working_directory, new_cwd) + self._env.set_cwd(new_cwd) + self.assertEqual(self._env.cwd, new_cwd) self._env.set_runtime_directory(new_cwd) self.assertEqual(self._env.runtime_directory, new_cwd) diff --git a/unittests/unittests_core/pipes/bool_pipe_test_case.py b/unittests/unittests_core/pipes/bool_pipe_test_case.py index decf88a7..79716bf6 100644 --- a/unittests/unittests_core/pipes/bool_pipe_test_case.py +++ b/unittests/unittests_core/pipes/bool_pipe_test_case.py @@ -8,7 +8,5 @@ class BoolPipeTestCase(unittest.TestCase): pass def test_transform(self): - pipe = BoolPipe() - - self.assertEqual("True", pipe.transform(True)) - self.assertEqual("False", pipe.transform(False)) + self.assertEqual("true", BoolPipe.to_str(True)) + self.assertEqual("false", BoolPipe.to_str(False)) diff --git a/unittests/unittests_core/pipes/ip_address_pipe_test_case.py b/unittests/unittests_core/pipes/ip_address_pipe_test_case.py index e4b0d878..4e9c169c 100644 --- a/unittests/unittests_core/pipes/ip_address_pipe_test_case.py +++ b/unittests/unittests_core/pipes/ip_address_pipe_test_case.py @@ -8,13 +8,11 @@ class IPAddressTestCase(unittest.TestCase): pass def test_transform(self): - pipe = IPAddressPipe() + self.assertEqual("192.168.178.1", IPAddressPipe.to_str([192, 168, 178, 1])) + self.assertEqual("255.255.255.255", IPAddressPipe.to_str([255, 255, 255, 255])) + self.assertEqual("0.0.0.0", IPAddressPipe.to_str([0, 0, 0, 0])) - self.assertEqual("192.168.178.1", pipe.transform([192, 168, 178, 1])) - self.assertEqual("255.255.255.255", pipe.transform([255, 255, 255, 255])) - self.assertEqual("0.0.0.0", pipe.transform([0, 0, 0, 0])) - - self.assertRaises(Exception, lambda: pipe.transform([-192, 168, 178, 1])) - self.assertRaises(Exception, lambda: pipe.transform([256, 168, 178, 1])) - self.assertRaises(Exception, lambda: pipe.transform([256, 168, 178])) - self.assertRaises(Exception, lambda: pipe.transform([256, 168, 178, 1, 1])) + self.assertRaises(Exception, lambda: IPAddressPipe.to_str([-192, 168, 178, 1])) + self.assertRaises(Exception, lambda: IPAddressPipe.to_str([256, 168, 178, 1])) + self.assertRaises(Exception, lambda: IPAddressPipe.to_str([256, 168, 178])) + self.assertRaises(Exception, lambda: IPAddressPipe.to_str([256, 168, 178, 1, 1])) diff --git a/unittests/unittests_core/pipes/version_pipe_test_case.py b/unittests/unittests_core/pipes/version_pipe_test_case.py deleted file mode 100644 index c122ce9f..00000000 --- a/unittests/unittests_core/pipes/version_pipe_test_case.py +++ /dev/null @@ -1,16 +0,0 @@ -import unittest - -from cpl.core.pipes.version_pipe import VersionPipe - - -class VersionPipeTestCase(unittest.TestCase): - def setUp(self): - pass - - def test_transform(self): - pipe = VersionPipe() - - self.assertEqual("1.1.1", pipe.transform({"Major": 1, "Minor": 1, "Micro": 1})) - self.assertEqual("0.1.1", pipe.transform({"Major": 0, "Minor": 1, "Micro": 1})) - self.assertEqual("0.0.1", pipe.transform({"Major": 0, "Minor": 0, "Micro": 1})) - self.assertEqual("0.0.0", pipe.transform({"Major": 0, "Minor": 0, "Micro": 0})) diff --git a/unittests/unittests_core/utils/string_test_case.py b/unittests/unittests_core/utils/string_test_case.py index 37707be1..fac56d79 100644 --- a/unittests/unittests_core/utils/string_test_case.py +++ b/unittests/unittests_core/utils/string_test_case.py @@ -11,24 +11,24 @@ class StringTestCase(unittest.TestCase): def test_convert_to_camel_case(self): expected = "HelloWorld" - self.assertEqual(expected, String.convert_to_camel_case("hello-world")) - self.assertEqual(expected, String.convert_to_camel_case("hello-World")) - self.assertEqual(expected, String.convert_to_camel_case("hello_world")) - self.assertEqual("helloWorld", String.convert_to_camel_case("helloWorld")) - self.assertEqual(expected, String.convert_to_camel_case("Hello_world")) - self.assertEqual(expected, String.convert_to_camel_case("Hello_World")) - self.assertEqual(expected, String.convert_to_camel_case("hello world")) + self.assertEqual(expected, String.to_camel_case("hello-world")) + self.assertEqual(expected, String.to_camel_case("hello-World")) + self.assertEqual(expected, String.to_camel_case("hello_world")) + self.assertEqual("helloWorld", String.to_camel_case("helloWorld")) + self.assertEqual(expected, String.to_camel_case("Hello_world")) + self.assertEqual(expected, String.to_camel_case("Hello_World")) + self.assertEqual(expected, String.to_camel_case("hello world")) def test_convert_to_snake_case(self): expected = "hello_world" - self.assertEqual(expected, String.convert_to_snake_case("Hello World")) - self.assertEqual(expected, String.convert_to_snake_case("hello-world")) - self.assertEqual(expected, String.convert_to_snake_case("hello_world")) - self.assertEqual(expected, String.convert_to_snake_case("helloWorld")) - self.assertEqual(expected, String.convert_to_snake_case("Hello_world")) - self.assertEqual(expected, String.convert_to_snake_case("Hello_World")) - self.assertEqual(expected, String.convert_to_snake_case("hello world")) + self.assertEqual(expected, String.to_snake_case("Hello World")) + self.assertEqual(expected, String.to_snake_case("hello-world")) + self.assertEqual(expected, String.to_snake_case("hello_world")) + self.assertEqual(expected, String.to_snake_case("helloWorld")) + self.assertEqual(expected, String.to_snake_case("Hello_world")) + self.assertEqual(expected, String.to_snake_case("Hello_World")) + self.assertEqual(expected, String.to_snake_case("hello world")) def test_first_to_upper(self): expected = "HelloWorld"