Added build command to cli

This commit is contained in:
Sven Heidemann 2020-12-16 16:47:31 +01:00
parent e9c20061d1
commit 3374ffe8db
8 changed files with 104 additions and 112 deletions

View File

@ -1,12 +1,15 @@
from abc import ABC, abstractmethod
from sh_edraft.console.console import Console
class CommandBase(ABC):
@abstractmethod
def __init__(self): pass
def __init__(self):
self._aliases: list[str] = []
@property
def aliases(self):
return self._aliases
@abstractmethod
def run(self, args: list[str]): pass

View File

@ -1,21 +1,52 @@
import sys
import traceback
from typing import Optional
from sh_edraft.cli.cpl_cli.commands.build import Build
from sh_edraft.cli.cpl_cli.commands.help import Help
from sh_edraft.cli.cpl_cli.commands.new import New
from sh_edraft.cli.cpl_cli.commands.version import Version
from sh_edraft.cli.interpreter.interpreter import Interpreter
from sh_edraft.configuration.base import ConfigurationBase
from sh_edraft.console.console import Console
from sh_edraft.hosting.application_host import ApplicationHost
from sh_edraft.hosting.base.application_base import ApplicationBase
from sh_edraft.logging.logger import Logger
from sh_edraft.logging.base.logger_base import LoggerBase
from sh_edraft.publishing.publisher import Publisher
from sh_edraft.publishing.base.publisher_base import PublisherBase
from sh_edraft.service.providing.service_provider import ServiceProviderBase
class CLI:
class CLI(ApplicationBase):
def __init__(self):
ApplicationBase.__init__(self)
self._app_host: Optional[ApplicationHost] = None
self._services: Optional[ServiceProviderBase] = None
self._configuration: Optional[ConfigurationBase] = None
self._logger: Optional[LoggerBase] = None
self._interpreter = Interpreter()
def create_application_host(self):
self._app_host = ApplicationHost()
self._configuration = self._app_host.configuration
self._services = self._app_host.services
def create_configuration(self):
self._configuration.add_json_file(f'project.json')
def create_services(self):
self._services.add_singleton(LoggerBase, Logger)
self._logger = self._services.get_service(LoggerBase)
self._services.add_singleton(PublisherBase, Publisher)
def setup(self):
self._interpreter.add_command(New())
self._interpreter.add_command(Build(self._services, self._configuration))
self._interpreter.add_command(Help())
self._interpreter.add_command(New())
self._interpreter.add_command(Version())
def main(self):
@ -30,6 +61,9 @@ class CLI:
def main():
cli = CLI()
cli.create_application_host()
cli.create_configuration()
cli.create_services()
cli.setup()
cli.main()

View File

@ -1,96 +0,0 @@
import os
class CLICommands:
@classmethod
def new(cls, args: list[str]):
rel_path = os.path.dirname(__file__)
if not os.path.isdir(f'{rel_path}/templates/{args[0]}'):
cls.unexpected_command(args[0])
sub_args = args[1:]
if len(sub_args) != 1:
cls.unexpected_argument(sub_args[1])
if not (sub_args[0].startswith('.') or sub_args[0].startswith('/')):
full_path = f'./{sub_args[0]}'
else:
full_path = sub_args[0]
name = os.path.basename(full_path)
path = os.path.dirname(full_path)
if args[0] in ['base', 'class', 'configmodel', 'enum', 'service']:
if not os.path.isdir(path):
os.makedirs(path)
else:
if not os.path.isdir(full_path):
os.makedirs(full_path)
for r, d, f in os.walk(f'{rel_path}/templates/{args[0]}'):
for file in f:
template_content = ''
with open(f'{r}/{file}') as template:
template_content = template.read()
template.close()
file = file.replace('txt', 'py')
if args[0] in ['base', 'class', 'configmodel', 'enum', 'service']:
suffix = None
if args[0] == 'base':
suffix = 'base'
elif args[0] == 'configmodel':
suffix = 'settings'
elif args[0] == 'service':
suffix = 'service'
if suffix is not None:
file_path = f'{path}/{name}_{suffix}.py'
else:
file_path = f'{path}/{name}.py'
else:
file_path = f'{full_path}/{file}'
with open(file_path, 'w+') as pyfile:
if name[0].islower():
name = f'{name[0].upper()}{name[1:]}'
if args[0] == 'base':
template_content = template_content.replace('$Name', f'{name}Base')
pyfile.write(template_content)
elif args[0] == 'configmodel':
template_content = template_content.replace('$Name', f'{name}Settings')
pyfile.write(template_content)
elif args[0] == 'service':
template_content = template_content.replace('$Name', f'{name}Service')
template_content = template_content.replace('$Base', f'{name}Base')
pyfile.write(template_content)
else:
template_content = template_content.replace('$Name', name)
pyfile.write(template_content)
pyfile.close()
@staticmethod
def help(*args):
print('Commands:')
@classmethod
def unexpected_command(cls, command: str):
print(f'Unexpected command {command}')
cls.help()
exit()
@classmethod
def unexpected_argument(cls, argument: str):
print(f'Unexpected argument {argument}')
cls.help()
exit()

View File

@ -0,0 +1,26 @@
from sh_edraft.cli.command.base.command_base import CommandBase
from sh_edraft.configuration.base.configuration_base import ConfigurationBase
from sh_edraft.console.console import Console
from sh_edraft.publishing.publisher import Publisher
from sh_edraft.publishing.base.publisher_base import PublisherBase
from sh_edraft.service.providing.service_provider import ServiceProviderBase
class Build(CommandBase):
def __init__(self, services: ServiceProviderBase, config: ConfigurationBase):
CommandBase.__init__(self)
self._services = services
self._config = config
self._aliases.append('-b')
self._aliases.append('-B')
self._publisher: Publisher = self._services.get_service(PublisherBase)
def run(self, args: list[str]):
if len(args) > 0:
Console.error(f'Invalid arguments {args}')
Console.error('Run \'cpl help\'')
self._publisher.create()
self._publisher.publish()

View File

@ -6,13 +6,16 @@ class Help(CommandBase):
def __init__(self):
CommandBase.__init__(self)
self._aliases.append('-h')
self._aliases.append('-H')
def run(self, args: list[str]):
Console.write_line('Available Commands:')
commands = [
['help', 'Lists available commands and their short descriptions.'],
['build (-b|-B)', 'Prepares files for publishing into an output directory named dist/ at the given output path.Must be executed from within a workspace directory.'],
['help (-h|-H)', 'Lists available commands and their short descriptions.'],
['new', 'Creates a new file or package.'],
['version', 'Outputs CPL CLI version.']
['version (-v|-V)', 'Outputs CPL CLI version.']
]
for name, description in commands:
Console.set_foreground_color('blue')

View File

@ -14,6 +14,8 @@ class Version(CommandBase):
def __init__(self):
CommandBase.__init__(self)
self._aliases.append('-v')
self._aliases.append('-V')
def run(self, args: list[str]):
Console.set_foreground_color('yellow')

View File

@ -0,0 +1,22 @@
{
"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": "INFO",
"FileLogLevel": "TRACE"
},
"PublishSettings": {
"SourcePath": "../",
"DistPath": "../../../../dist",
"Templates": [],
"IncludedFiles": [],
"ExcludedFiles": [],
"TemplateEnding": "_template.txt"
}
}

View File

@ -15,16 +15,14 @@ class Interpreter:
def interpret(self, input_string: str):
input_list = input_string.split(' ')
commands = [type(cmd).__name__.lower() for cmd in self._commands]
command = input_list[0]
args = input_list[1:] if len(input_list) > 2 else []
if command in commands:
cmd = next((cmd for cmd in self._commands if type(cmd).__name__.lower() == command), None)
args = input_list[1:] if len(input_list) > 1 else []
cmd = next(
(cmd for cmd in self._commands if type(cmd).__name__.lower() == command or command in cmd.aliases),
None)
if cmd is not None:
cmd.run(args)
else:
Console.error(f'Unexpected command {command}')
Console.error('Run \'cpl help\'')
else:
Console.error(f'Unexpected command {command}')
Console.error('Run \'cpl help\'')