"""Configuration handling module.""" import os from autonomic import logger from autonomic.settings import AUTONOMIC_YAML from autonomic.system import exit_with_msg from autonomic.yaml import yaml log = logger.get_logger(__name__) def ensure_config(): """Ensure the configuration exists.""" if not os.path.exists(AUTONOMIC_YAML): msg = "{} is missing, run: autonomic init".format(AUTONOMIC_YAML) exit_with_msg(msg) def add_to_config(data): """Add values to the autonomic.yml file.""" ensure_config() with open(AUTONOMIC_YAML, "r") as handle: config = yaml.load(handle.read()) if config is None: config = {} for key in data: config[key] = data[key] with open(AUTONOMIC_YAML, "w") as handle: yaml.dump(config, handle) def get_from_config(key): """Get values from the autonomic.yml file.""" ensure_config() with open(AUTONOMIC_YAML, "r") as handle: config = yaml.load(handle.read()) try: return config[key] except KeyError: msg = "Unable to retrieve {} from {}".format(key, AUTONOMIC_YAML) exit_with_msg(msg)