mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-05 23:51:21 +00:00
42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
from subprocess import Popen
|
|
from functools import partial
|
|
|
|
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()
|
|
super(YamlFSM, self).__init__() # FSMBase.__init__() requires states
|
|
self.setup_transitions()
|
|
|
|
@staticmethod
|
|
def parse_config(config_file):
|
|
with open(config_file, 'r') as ifile:
|
|
return yaml.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']:
|
|
self.machine.add_transition(**transition)
|
|
|
|
def patch_config_callbacks(self):
|
|
topatch = {'on_enter', 'on_exit', 'prepare', 'before', 'after'}
|
|
|
|
for array in {'states', 'transitions'}:
|
|
for json_obj in self.config[array]:
|
|
for attribute, value in json_obj.items():
|
|
if attribute in topatch:
|
|
json_obj[attribute] = partial(self.run, value)
|
|
|
|
@staticmethod
|
|
def run(command, event):
|
|
Popen(command, shell=True)
|