From 759d7d77f99d9dbe0635ca0a2e3665c120b615ac Mon Sep 17 00:00:00 2001 From: Tim Van Baak Date: Fri, 17 Jan 2020 01:23:48 -0800 Subject: [PATCH] Refactor config --get/set to cli.helpers --- amanuensis/cli/helpers.py | 51 ++++++++++++++++++++++++++++++++++++++- amanuensis/cli/server.py | 19 +++------------ 2 files changed, 54 insertions(+), 16 deletions(-) diff --git a/amanuensis/cli/helpers.py b/amanuensis/cli/helpers.py index ccc9f83..df2a1b4 100644 --- a/amanuensis/cli/helpers.py +++ b/amanuensis/cli/helpers.py @@ -46,4 +46,53 @@ def requires(argument, verify=lambda a: a is not None): command(cmd_args) augmented_command.__dict__['wrapper'] = True return augmented_command - return req_checker \ No newline at end of file + 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 \ No newline at end of file diff --git a/amanuensis/cli/server.py b/amanuensis/cli/server.py index ec77c2c..4f9b80c 100644 --- a/amanuensis/cli/server.py +++ b/amanuensis/cli/server.py @@ -1,6 +1,4 @@ -from cli.helpers import add_argument, no_argument - -CONFIG_GET_ROOT_VALUE = object() +from cli.helpers import add_argument, no_argument, config_get, config_set, CONFIG_GET_ROOT_VALUE @add_argument("--update", action="store_true", help="Refresh an existing config directory") def command_init(args): @@ -116,18 +114,9 @@ def command_config(args): return -1 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: - for spec in path: - if spec not in cfg: - config.logger.error("Path not found") - return -1 - cfg = cfg.get(spec) - print(json.dumps(cfg, indent=2)) + config_get(cfg, args.get) if args.set: - raise NotImplementedError() - + with config.json_rw('config.json') as cfg: + config_set(cfg, args.set)