BotZ/api/conf.py

94 lines
2.8 KiB
Python

# -*- encoding: utf-8 -*-
import os
from pprint import pprint
import typing as T
import yaml
from api import DEBUG, BASE_URI
def read_conf(path: T.Optional[T.Text]) -> T.Dict:
"""
Read the configuration from the provided path.
Such configuration may provide the following information:
---
base_uri: <base uri of the target instance>
debug: <bool, set debug on, defaults to false>
headless: <bool, use headless mode, defaults to true>
log:
level: <may be DEBUG, INFO, WARN, ..., defaults at INFO>
syslog: <bool, whether to redirect to standard syslog, defaults to false>
http:
bind_addr: <a list of addresses to bind to>
port: <int, the port to bind to>
cookie_name: <defaults to BOTZ_SESSION>
cookie_secure: <bool, whether to set Secure cookie flag, defaults to true>
cors_allow: <an optional single allowed Cross Origin domain>
"""
if path is None:
path = seek_path()
if path is not None:
with open(path) as f:
conf = yaml.safe_load(f)
else:
conf = {}
if "base_uri" not in conf:
if BASE_URI is None:
raise RuntimeError("Missing base_uri")
conf["base_uri"] = BASE_URI
if "debug" not in conf:
conf["debug"] = DEBUG
if "headless" not in conf:
conf["headless"] = True
conf = validate_log_conf(conf)
conf = validate_http_log(conf)
pprint(conf)
return conf
def seek_path() -> T.Optional[T.Text]:
"""
Seeks the path to a config file, in the following order:
- $BOTZ_CONFIG
- $PWD/.botz.yaml
- ~/.botz.yaml
- /etc/botz/conf.yaml
"""
paths = [
os.path.join(os.path.curdir, ".botz.yaml"),
os.path.expanduser("~/.botz.yaml"),
"/etc/botz/conf.yaml",
]
env = os.environ.get("BOTZ_CONFIG")
if env is not None:
paths.insert(0, env)
for path in paths:
if os.path.exists(path):
return path
return None
def validate_log_conf(conf: T.Dict[T.Text, T.Any]) -> T.Dict[T.Text, T.Any]:
if "log" not in conf:
conf["log"] = {}
if conf["log"].get("level") is None:
conf["log"]["level"] = "INFO"
if conf["log"].get("syslog") is None:
conf["log"]["syslog"] = False
return conf
def validate_http_log(conf: T.Dict[T.Text, T.Any]) -> T.Dict[T.Text, T.Any]:
if "http" not in conf:
conf["http"] = {}
if conf["http"].get("bind_addr") is None:
conf["http"]["bind_addr"] = ["127.0.0.1"]
if conf["http"].get("port") is None:
conf["http"]["port"] = 3003
if conf["http"].get("cookie_name") is None:
conf["http"]["cookie_name"] = "BOTZ_SESSION"
if conf["http"].get("cookie_secure") is None:
conf["http"]["cookie_secure"] = True
return conf