1
Fork 0
This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
dotfile-automator/project/utils/config.py

55 lines
1.3 KiB
Python
Raw Normal View History

2015-12-02 22:07:56 +00:00
import os
from yaml import load, dump
from .constants import DEFAULT_CONFIG_DIR, USER_CONFIG_DIR, REQUIRED_KEYS
2015-12-02 22:07:56 +00:00
try:
from yaml import CLoader as Loader, CDumper as Dumper
2015-12-02 22:07:56 +00:00
except ImportError:
from yaml import Loader, Dumper
2015-12-02 22:07:56 +00:00
2015-12-02 22:39:40 +00:00
2015-12-02 22:07:56 +00:00
def get_config_data(filename):
try:
with open(filename) as config_file:
return load(config_file, Loader=Loader)
2015-12-02 22:07:56 +00:00
except FileNotFoundError:
return {}
except Exception as e:
print("Error:", e)
return {}
2015-12-02 22:07:56 +00:00
2015-12-03 22:43:42 +00:00
def write_user_config(refresh_after=False):
try:
with open(USER_CONFIG_DIR, 'w') as config_file:
2015-12-03 22:43:42 +00:00
dump(USER_CONFIG, config_file, indent=4, default_flow_style=False, Dumper=Dumper)
return "SUCCESS"
except Exception as e:
return e
2015-12-02 22:07:56 +00:00
2015-12-03 22:43:42 +00:00
DEFAULT_CONFIG = get_config_data(DEFAULT_CONFIG_DIR)
2015-12-02 22:07:56 +00:00
USER_CONFIG = get_config_data(os.path.expanduser(USER_CONFIG_DIR))
2015-12-02 22:39:40 +00:00
2015-12-03 18:07:08 +00:00
def get(key):
2015-12-02 22:37:36 +00:00
if USER_CONFIG and key in USER_CONFIG:
2015-12-02 22:07:56 +00:00
return USER_CONFIG[key]
2015-12-02 22:37:36 +00:00
elif DEFAULT_CONFIG and key in DEFAULT_CONFIG:
2015-12-02 22:07:56 +00:00
return DEFAULT_CONFIG[key]
return None
2015-12-03 22:43:42 +00:00
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)
def has_basics():
for key in REQUIRED_KEYS:
if not get(key):
return False
return True