From a083894c57ab0825d886b0a931ed5f29314ece92 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Thu, 3 Dec 2015 22:33:04 +0000 Subject: [PATCH] Added get and set commands for user config --- project/config/cli.py | 17 +++++++++++++++++ project/utils/config.py | 31 ++++++++++++++++++++++--------- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/project/config/cli.py b/project/config/cli.py index 78fd6db..2bceca1 100644 --- a/project/config/cli.py +++ b/project/config/cli.py @@ -13,3 +13,20 @@ def show(key): key = " ".join(key) print(config.get(key)) return 0 + + +@cli.command('set') +@click.argument('key', nargs=1) +@click.argument('value', nargs=-1) +def set(key, value): + key = " ".join(key) + status = config.set(key, value) + if status == "SUCCESS": + print("Repo set to", repo) + return 0 + elif status == "NO_KEY": + print("Key {} not found".format(key)) + return 1 + else: + print("Something went wrong:", status) + return 1 diff --git a/project/utils/config.py b/project/utils/config.py index 788136d..5076fb7 100644 --- a/project/utils/config.py +++ b/project/utils/config.py @@ -1,25 +1,32 @@ import os -from yaml import load +from yaml import load, dump try: - from yaml import CLoader as Loader + from yaml import CLoader as Loader, CDumper as Dumper except ImportError: - from yaml import Loader + from yaml import Loader, Dumper BASE_DIR = os.path.dirname(os.path.abspath(__file__)) -USER_CONFIG_DIR = "~/.dfa.yml" - +USER_CONFIG_DIR = os.path.expanduser("~/.dfa.yml") +DEFAULT_CONFIG_DIR = os.path.join(BASE_DIR, 'defaults.yml') def get_config_data(filename): try: - config_file = open(filename) - return load(config_file, Loader=Loader) + with open(filename) as config_file: + return load(config_file, Loader=Loader) except FileNotFoundError: - return [] + return {} +def write_user_config(refresh_after=False): + try: + with open(USER_CONFIG_DIR, 'w') as config_file: + dump(USER_CONFIG, config_file, indent=4, default_flow_style=False) + return "SUCCESS" + except Exception as e: + return e -DEFAULT_CONFIG = get_config_data(os.path.join(BASE_DIR, 'defaults.yml')) +DEFAULT_CONFIG = get_config_data(DEFAULT_CONFIG_DIR) USER_CONFIG = get_config_data(os.path.expanduser(USER_CONFIG_DIR)) @@ -30,3 +37,9 @@ def get(key): elif DEFAULT_CONFIG and key in DEFAULT_CONFIG: return DEFAULT_CONFIG[key] return None + +def set(key, value, refresh_after=False): + if key not in DEFAULT_CONFIG: + return "NO_KEY" + USER_CONFIG[key] = value + return write_user_config(refresh_after)