1
0
Fork 0
mirror of https://github.com/yavook/kiwi-scp.git synced 2024-11-21 20:33:00 +00:00

init routine in subcommand class

This commit is contained in:
Jörn-Michael Miehe 2020-08-06 13:43:45 +02:00
parent d108ae2183
commit 1929a1369e
9 changed files with 158 additions and 72 deletions

View file

@ -1 +0,0 @@
VERSION="0.1"

1
kiwi.yml Normal file
View file

@ -0,0 +1 @@
version: 0.1

View file

@ -11,3 +11,4 @@ network:
runtime:
storage: /var/kiwi
env:
HELLO_KIWI: Hello World!

View file

@ -1,27 +1,16 @@
#!/usr/bin/env python3
import argparse
from kiwi.config import *
import kiwi
from kiwi.cmd_init import InitSubCommand
def main():
parser = argparse.ArgumentParser(description='kiwi-config')
isc = InitSubCommand()
isc.setup()
subs = parser.add_subparsers()
subs.required = True
subs.dest = 'command'
subs.add_parser('init', help="Create new kiwi-config instance")
subs.add_parser('add', help="Add a project to kiwi-config")
# parser.add_argument('cmd', metavar='command', type=str, help='subcommand to execute')
args = parser.parse_args()
args = kiwi.Parser.get_args()
print(args.command)
cf = Config.default()
# cf.user_input()
cf.dump()
isc.run()
pass

View file

@ -1 +1,4 @@
__all__ = ['config']
from .core import Parser
from .config import Config
__all__ = ['Parser', 'Config']

40
src/kiwi/cmd_init.py Normal file
View file

@ -0,0 +1,40 @@
import logging
import os
from .core import KIWI_CONF_NAME, Parser, SubCommand
from .config import Config
class InitSubCommand(SubCommand):
def __init__(self):
super(InitSubCommand, self).__init__('init')
def setup(self):
init_parser = Parser.get_subparsers().add_parser(str(self), help="Create new kiwi-config instance")
# init_parser.add_argument('cmd', metavar='command', type=str, help='subcommand to execute')
def __user_input(self, config, key, prompt):
# prompt user as per argument
result = input("{} [Current: {}] ".format(prompt, config[key])).strip()
# store result if present
if result:
config[key] = result
def run(self):
config = Config.default()
if os.path.isfile(KIWI_CONF_NAME):
logging.warning("Overwriting existing '%s'!", KIWI_CONF_NAME)
self.__user_input(config, 'version', "Choose kiwi-config version")
self.__user_input(config, 'markers:project', "Enter marker string for project directories")
self.__user_input(config, 'markers:down', "Enter marker string for disabled projects")
self.__user_input(config, 'network:name', "Enter name for local docker network")
self.__user_input(config, 'network:cidr', "Enter CIDR block for local docker network")
self.__user_input(config, 'runtime:storage', "Enter main directory for local data")
print(str(config))

View file

@ -1,79 +1,76 @@
import os
import logging
import re
import yaml
from .core import KIWI_ROOT, KIWI_CONF_NAME
###########
# CONSTANTS
DEFAULT_KIWI_CONF_NAME = KIWI_ROOT + "/default.kiwi.yml"
class Config:
KIWI_ROOT = os.getenv('KIWI_ROOT', '.')
__yml_content = None
__yml_content = {}
@classmethod
def __from_file(cls, filename):
result = cls()
def __str__(self):
# dump yml content
yml_string = yaml.dump(self.__yml_content, default_flow_style=False, sort_keys=False)
with open(filename, 'r') as stream:
try:
result.__yml_content = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
# insert newline before every main key
yml_string = re.sub(r'^(\S)', r'\n\1', yml_string, flags=re.MULTILINE)
return result
# extract header comment from default config
with open(DEFAULT_KIWI_CONF_NAME, 'r') as stream:
yml_header = stream.read().strip()
yml_header = re.sub(r'^[^#].*', r'', yml_header, flags=re.MULTILINE).strip()
yml_string = "{}\n{}".format(yml_header, yml_string)
@classmethod
def default(cls):
result = cls.__from_file(cls.KIWI_ROOT + "/default.kiwi.yml")
return yml_string
with open(cls.KIWI_ROOT + "/version-tag", 'r') as stream:
result.__yml_content["version"] = stream.read().strip()
return result
def __yml_resolve(self, key):
def __key_resolve(self, key):
# "a:b:c" => path = ['a', 'b'], key = 'c'
path = key.split(':')
path, key = path[:-1], path[-1]
# resolve path
content = self.__yml_content
container = self.__yml_content
for step in path:
content = content[step]
container = container[step]
return content, key
return container, key
def __yml_get(self, key):
content, key = self.__yml_resolve(key)
return content[key]
def __setitem__(self, key, value):
container, key = self.__key_resolve(key)
container[key] = value
def __yml_set(self, key, value):
content, key = self.__yml_resolve(key)
content[key] = value
def __getitem__(self, key):
container, key = self.__key_resolve(key)
return container[key]
def __user_input(self, key, prompt):
# prompt user as per argument
result = input("{} [Current: {}] ".format(prompt, self.__yml_get(key))).strip()
def __update_from_file(self, filename):
with open(filename, 'r') as stream:
try:
self.__yml_content.update(yaml.safe_load(stream))
except yaml.YAMLError as exc:
logging.error(exc)
# store result if present
if result:
self.__yml_set(key, result)
@classmethod
def default(cls):
result = cls()
result.__update_from_file(DEFAULT_KIWI_CONF_NAME)
def user_input(self):
self.__user_input("version", "Choose kiwi-config version")
with open(KIWI_ROOT + "/version-tag", 'r') as stream:
result.__yml_content["version"] = stream.read().strip()
self.__user_input("markers:project", "Enter marker string for project directories")
self.__user_input("markers:down", "Enter marker string for disabled projects")
return result
self.__user_input("network:name", "Enter name for local docker network")
self.__user_input("network:cidr", "Enter CIDR block for local docker network")
@classmethod
def load(cls):
result = cls.default()
result.__update_from_file(KIWI_CONF_NAME)
self.__user_input("runtime:storage", "Enter main directory for local data")
return result
def dump(self):
yml_string = yaml.dump(self.__yml_content, default_flow_style=False, sort_keys=False)
yml_string = re.sub(r'^(\S)', r'\n\1', yml_string, flags=re.MULTILINE)
with open(Config.KIWI_ROOT + "/default.kiwi.yml", 'r') as stream:
yml_header = stream.read().strip()
yml_header = re.sub(r'^[^#].*', r'', yml_header, flags=re.MULTILINE).strip()
yml_string = "{}\n{}".format(yml_header, yml_string)
print(yml_string)
def save(self):
pass

56
src/kiwi/core.py Normal file
View file

@ -0,0 +1,56 @@
import argparse
import os
###########
# CONSTANTS
KIWI_ROOT = os.getenv('KIWI_ROOT', ".")
KIWI_CONF_NAME = os.getenv('KIWI_CONF_NAME', "kiwi.yml")
class Parser:
__instance = None
__subparsers = None
__args = None
@classmethod
def __init_instance(cls):
if not cls.__instance:
cls.__instance = argparse.ArgumentParser(description='kiwi-config')
cls.__subparsers = Parser.__instance.add_subparsers()
cls.__subparsers.required = True
cls.__subparsers.dest = 'command'
@classmethod
def get_instance(cls):
cls.__init_instance()
return cls.__instance
@classmethod
def get_subparsers(cls):
cls.__init_instance()
return cls.__subparsers
@classmethod
def get_args(cls):
if not cls.__args:
cls.__args = cls.get_instance().parse_args()
return cls.__args
class SubCommand:
__cmd = None
def __init__(self, cmd):
self.__cmd = cmd
def __str__(self):
return self.__cmd
def setup(self):
pass
def run(self):
pass

View file