2017-06-03 17:13:45 -04:00
|
|
|
'''
|
|
|
|
Presents an interface for yaml files as a dict-like object
|
|
|
|
'''
|
|
|
|
|
2017-06-03 17:49:48 -04:00
|
|
|
import yaml, shutil, logging
|
2017-06-03 17:13:45 -04:00
|
|
|
from threading import Lock
|
|
|
|
|
2017-06-03 17:49:48 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2017-06-03 17:34:30 -04:00
|
|
|
class _ReadOnlyFile():
|
|
|
|
'''
|
|
|
|
Opens a yaml file for reading. Intended for config files.
|
|
|
|
'''
|
2017-06-03 17:13:45 -04:00
|
|
|
def __init__(self, path):
|
|
|
|
self._path = path
|
2017-06-03 18:37:24 -04:00
|
|
|
try:
|
|
|
|
self._load()
|
|
|
|
except FileNotFoundError:
|
|
|
|
logger.warn('File %s not found. Attempting to copy example', self._path)
|
|
|
|
defaultPath = self._path + '.default'
|
|
|
|
|
|
|
|
try:
|
|
|
|
shutil.copy(defaultPath, self._path)
|
|
|
|
except FileNotFoundError:
|
|
|
|
logger.error('Example file %s not found', defaultPath)
|
|
|
|
raise SystemExit
|
|
|
|
|
|
|
|
self._path = defaultPath
|
|
|
|
self._load()
|
|
|
|
except yaml.parser.ParserError as e:
|
|
|
|
logger.error(e)
|
|
|
|
raise SystemExit
|
|
|
|
|
2017-06-03 17:13:45 -04:00
|
|
|
def __getitem__(self, key):
|
|
|
|
return self._dict[key]
|
2017-06-03 18:37:24 -04:00
|
|
|
|
|
|
|
def _load(self):
|
|
|
|
with open(self._path, 'r') as f:
|
|
|
|
self._dict = yaml.safe_load(f)
|
2017-06-03 17:13:45 -04:00
|
|
|
|
2017-06-03 17:34:30 -04:00
|
|
|
class _ReadWriteFile(_ReadOnlyFile):
|
|
|
|
'''
|
|
|
|
Same as above but adds write functionality. Intended for files that retain
|
|
|
|
program state so that it may return to the same state when recovering from
|
|
|
|
a crash (eg someone can't crash the system to disarm it)
|
|
|
|
'''
|
|
|
|
def __init__(self, path):
|
|
|
|
super().__init__(path)
|
|
|
|
self._lock = Lock()
|
|
|
|
|
2017-06-03 17:13:45 -04:00
|
|
|
def __setitem__(self, key, value):
|
|
|
|
with self._lock:
|
|
|
|
self._dict[key] = value
|
2017-06-03 17:34:30 -04:00
|
|
|
with open(self._path, 'w') as f:
|
|
|
|
yaml.dump(self._dict, f, default_flow_style=False)
|
2017-06-03 17:13:45 -04:00
|
|
|
|
2017-06-03 18:37:24 -04:00
|
|
|
configFile = _ReadOnlyFile('config/pyledriver.yaml')
|
|
|
|
stateFile = _ReadWriteFile('config/state.yaml')
|