Files
dougal-software/bin/configuration.py

79 lines
2.2 KiB
Python

import os
from glob import glob
from yaml import full_load as _load
"""
Interface to the instance configuration.
The instance configuration is expected to be found under
$HOME/etc/config.yaml and the configuration for the individual
surveys should be under $HOME/etc/surveys/*.yaml. In both cases,
$HOME is the home directory of the user running this script.
"""
prefix = os.environ.get("DOUGAL_ROOT", os.environ.get("HOME", ".")+"/software")
def read (file = None):
if file is None:
file = prefix+"/etc/config.yaml"
with open(file, "r") as fd:
cfg = _load(fd)
if "db" in cfg and "connection_string" in cfg["db"] and os.environ.get("PGDATABASE"):
# This should cause the PostgreSQL library to use the environment variables
cfg["db"]["connection_string"] = ""
print("Using environment variables for database connection")
return cfg
def files (globspec = None, include_archived = False):
"""
Read and parse survey configuration files.
Arguments:
globspec (string): a glob spec matching the selection of files to read.
If not provided, a default value will be used.
include_archived (bool): whether to include surveys marked as archived or
not. Defaults to ignoring archived surveys.
Note that file names starting with `.` or `_` (dot or underscore) will
never be read (and there is no option to override this). Intended for
quickly and temporarily “disabling” a survey configuration by renaming
the relevant file.
"""
tuples = []
if globspec is None:
globspec = prefix+'/etc/surveys/*.yaml'
for filepath in glob(globspec):
filepath = os.path.abspath(filepath)
if os.path.basename(filepath).startswith("_") or os.path.basename(filepath).startswith("."):
continue
survey = read(filepath)
if not include_archived and "archived" in survey and survey["archived"] is not False:
continue
tuples.append((filepath, survey))
return tuples
def surveys (globspec = None, include_archived = False):
return [i[1] for i in files(globspec, include_archived)]
def rxflags (flagstr):
"""
Convert flags string into a Python flags argument.
"""
flags = 0
cases = {
"i": re.I
}
for flag in flagstr:
flags |= cases.get(flag, 0)
return flags