phi/src/phi/config.py

47 lines
1.2 KiB
Python

import os.path
import yaml
NAME = "phi"
CONFIG_FILE = "config.yml"
CONFIG_PATHS = [
"./",
"~/.config/" + NAME + "/",
"/usr/local/etc/" + NAME + "/",
"/etc/" + NAME + "/",
]
CONFIG_FILES = [os.path.join(p, CONFIG_FILE) for p in CONFIG_PATHS]
def get_config(custom_config=None):
"""Return the path of the found configuration file and its content
:returns: (path, config)
:rtype: (str, dict)
"""
if custom_config:
global CONFIG_FILES
CONFIG_FILES = [custom_config]
for f in CONFIG_FILES:
try:
with open(f, "r") as c:
config = yaml.safe_load(c)
return (f, config)
except FileNotFoundError:
# Skip to the next file.
# We only care if the file is preset but it's not
# accessible or if the file is not present at all
# in any of CONFIG_PATHS.
pass
else:
if custom_config:
raise FileNotFoundError("Config file {} not found.".format(custom_config))
else:
raise FileNotFoundError(
"Could not find {} in any of {}.".format(
CONFIG_FILE, ", ".join(CONFIG_PATHS)
)
)