Refactor config --get/set to cli.helpers

This commit is contained in:
Tim Van Baak 2020-01-17 01:23:48 -08:00
parent 3abc07eb39
commit 759d7d77f9
2 changed files with 54 additions and 16 deletions

View File

@ -46,4 +46,53 @@ def requires(argument, verify=lambda a: a is not None):
command(cmd_args) command(cmd_args)
augmented_command.__dict__['wrapper'] = True augmented_command.__dict__['wrapper'] = True
return augmented_command return augmented_command
return req_checker return req_checker
# Helpers for common command tasks
CONFIG_GET_ROOT_VALUE = object()
def config_get(cfg, pathspec):
"""
Performs config --get for a given config
cfg is from a with json_ro context
path is the full pathspec, unsplit
"""
import json
from config import logger
if pathspec is CONFIG_GET_ROOT_VALUE:
path = []
else:
path = pathspec.split(".")
for spec in path:
if spec not in cfg:
logger.error("Path not found: {}".format(pathspec))
return -1
cfg = cfg.get(spec)
print(json.dumps(cfg, indent=2))
def config_set(cfg, set_tuple):
"""
Performs config --set for a given config
config is from a with json_rw context
set_tuple is a tuple of the pathspec and the value
"""
from config import logger
pathspec, value = set_tuple
if not pathspec:
logger.error("Path must be non-empty")
path = pathspec.split('.')
if not value:
value = None
for spec in path[:-1]:
if spec not in cfg:
logger.error("Path not found")
return -1
cfg = cfg.get(spec)
key = path[-1]
if key not in cfg:
logger.error("Path not found")
return -1
cfg[key] = value

View File

@ -1,6 +1,4 @@
from cli.helpers import add_argument, no_argument from cli.helpers import add_argument, no_argument, config_get, config_set, CONFIG_GET_ROOT_VALUE
CONFIG_GET_ROOT_VALUE = object()
@add_argument("--update", action="store_true", help="Refresh an existing config directory") @add_argument("--update", action="store_true", help="Refresh an existing config directory")
def command_init(args): def command_init(args):
@ -116,18 +114,9 @@ def command_config(args):
return -1 return -1
if args.get: if args.get:
if args.get is CONFIG_GET_ROOT_VALUE:
path = []
else:
path = args.get.split(".")
with config.json_ro('config.json') as cfg: with config.json_ro('config.json') as cfg:
for spec in path: config_get(cfg, args.get)
if spec not in cfg:
config.logger.error("Path not found")
return -1
cfg = cfg.get(spec)
print(json.dumps(cfg, indent=2))
if args.set: if args.set:
raise NotImplementedError() with config.json_rw('config.json') as cfg:
config_set(cfg, args.set)