2014-03-19 23:07:30 -04:00
|
|
|
import os
|
2016-01-16 22:00:15 -05:00
|
|
|
from .plugin import Plugin
|
2014-03-19 23:07:30 -04:00
|
|
|
from .messenger import Messenger
|
2016-03-02 20:53:19 -05:00
|
|
|
from .context import Context
|
2014-03-19 23:07:30 -04:00
|
|
|
|
|
|
|
class Dispatcher(object):
|
2020-03-25 21:38:39 -04:00
|
|
|
def __init__(self, base_directory, only=None, skip=None):
|
2014-03-19 23:07:30 -04:00
|
|
|
self._log = Messenger()
|
2016-03-02 20:53:19 -05:00
|
|
|
self._setup_context(base_directory)
|
2014-03-19 23:07:30 -04:00
|
|
|
self._load_plugins()
|
2020-03-25 21:38:39 -04:00
|
|
|
self._only = only
|
|
|
|
self._skip = skip
|
2014-03-19 23:07:30 -04:00
|
|
|
|
2016-03-02 20:53:19 -05:00
|
|
|
def _setup_context(self, base_directory):
|
2018-05-21 13:10:17 -04:00
|
|
|
path = os.path.abspath(
|
|
|
|
os.path.expanduser(base_directory))
|
2016-03-02 20:53:19 -05:00
|
|
|
if not os.path.exists(path):
|
2015-01-26 10:36:11 -05:00
|
|
|
raise DispatchError('Nonexistent base directory')
|
2016-03-02 20:53:19 -05:00
|
|
|
self._context = Context(path)
|
2014-03-19 23:07:30 -04:00
|
|
|
|
|
|
|
def dispatch(self, tasks):
|
|
|
|
success = True
|
|
|
|
for task in tasks:
|
|
|
|
for action in task:
|
2020-11-22 16:58:00 -05:00
|
|
|
if (self._only is not None and action not in self._only \
|
|
|
|
or self._skip is not None and action in self._skip) \
|
|
|
|
and action != 'defaults':
|
2020-03-25 21:38:39 -04:00
|
|
|
self._log.info('Skipping action %s' % action)
|
|
|
|
continue
|
2014-03-19 23:07:30 -04:00
|
|
|
handled = False
|
2016-03-02 20:53:19 -05:00
|
|
|
if action == 'defaults':
|
|
|
|
self._context.set_defaults(task[action]) # replace, not update
|
|
|
|
handled = True
|
|
|
|
# keep going, let other plugins handle this if they want
|
2014-03-19 23:07:30 -04:00
|
|
|
for plugin in self._plugins:
|
|
|
|
if plugin.can_handle(action):
|
|
|
|
try:
|
|
|
|
success &= plugin.handle(action, task[action])
|
|
|
|
handled = True
|
2018-01-27 02:27:44 -05:00
|
|
|
except Exception as err:
|
2014-03-19 23:07:30 -04:00
|
|
|
self._log.error(
|
|
|
|
'An error was encountered while executing action %s' %
|
|
|
|
action)
|
2018-01-27 02:27:44 -05:00
|
|
|
self._log.debug(err)
|
2014-03-19 23:07:30 -04:00
|
|
|
if not handled:
|
|
|
|
success = False
|
|
|
|
self._log.error('Action %s not handled' % action)
|
|
|
|
return success
|
|
|
|
|
|
|
|
def _load_plugins(self):
|
2016-03-02 20:53:19 -05:00
|
|
|
self._plugins = [plugin(self._context)
|
2016-01-16 22:00:15 -05:00
|
|
|
for plugin in Plugin.__subclasses__()]
|
2014-03-19 23:07:30 -04:00
|
|
|
|
|
|
|
class DispatchError(Exception):
|
|
|
|
pass
|