baseimage-tutorial-framework/lib/tfw/yaml_fsm.py

42 lines
1.2 KiB
Python
Raw Normal View History

from subprocess import Popen
from functools import partial
2018-07-03 13:14:00 +00:00
import yaml
from transitions import State
from tfw import FSMBase
class YamlFSM(FSMBase):
def __init__(self, config_file):
self.config = self.parse_config(config_file)
self.patch_config_callbacks()
self.setup_states()
2018-07-04 14:22:03 +00:00
super().__init__() # FSMBase.__init__() requires states
self.setup_transitions()
2018-07-03 13:14:00 +00:00
@staticmethod
def parse_config(config_file):
with open(config_file, 'r') as ifile:
2018-07-04 14:22:03 +00:00
return yaml.safe_load(ifile)
def setup_states(self):
self.states = [State(**state) for state in self.config['states']]
def setup_transitions(self):
for transition in self.config['transitions']:
2018-07-04 14:22:03 +00:00
self.add_transition(**transition)
def patch_config_callbacks(self):
2018-07-04 14:22:03 +00:00
topatch = ('on_enter', 'on_exit', 'prepare', 'before', 'after')
2018-07-04 14:22:03 +00:00
for array in ('states', 'transitions'):
for json_obj in self.config[array]:
2018-07-04 14:22:03 +00:00
for key in json_obj:
if key in topatch:
json_obj[key] = partial(self.run, json_obj[key])
@staticmethod
def run(command, event):
Popen(command, shell=True)