1
0
Fork 0
mirror of synced 2024-11-17 22:15:35 -05:00
dotbot/plugins/shell.py

52 lines
2 KiB
Python
Raw Normal View History

2016-01-16 22:00:15 -05:00
import os, subprocess, dotbot
2014-03-19 23:07:30 -04:00
2016-01-16 22:00:15 -05:00
class Shell(dotbot.Plugin):
2014-03-19 23:07:30 -04:00
'''
Run arbitrary shell commands.
'''
2014-04-24 15:41:34 -04:00
_directive = 'shell'
2014-03-19 23:07:30 -04:00
def can_handle(self, directive):
2014-04-24 15:41:34 -04:00
return directive == self._directive
2014-03-19 23:07:30 -04:00
2016-02-27 00:43:11 -05:00
def handle(self, directive, data, defaults):
2014-04-24 15:41:34 -04:00
if directive != self._directive:
2016-02-27 00:43:11 -05:00
raise ValueError('Shell cannot handle directive %s' % directive)
return self._process_commands(data, defaults)
2014-03-19 23:07:30 -04:00
2016-02-27 00:43:11 -05:00
def _process_commands(self, data, defaults):
2014-03-19 23:07:30 -04:00
success = True
with open(os.devnull, 'w') as devnull:
for item in data:
stdin = stdout = stderr = devnull
if isinstance(item, dict):
cmd = item['command']
msg = item.get('description', None)
2016-02-27 00:43:11 -05:00
if item.get('stdin', defaults.get('stdin', False)) is True:
stdin = None
2016-02-27 00:43:11 -05:00
if item.get('stdout', defaults.get('stdout', False)) is True:
stdout = None
2016-02-27 00:43:11 -05:00
if item.get('stderr', defaults.get('stderr', False)) is True:
stderr = None
elif isinstance(item, list):
cmd = item[0]
msg = item[1] if len(item) > 1 else None
else:
cmd = item
msg = None
if msg is None:
self._log.lowinfo(cmd)
else:
self._log.lowinfo('%s [%s]' % (msg, cmd))
ret = subprocess.call(cmd, shell=True, stdin=stdin, stdout=stdout,
2016-02-27 00:43:11 -05:00
stderr=stderr, cwd=self._base_directory)
2014-03-19 23:07:30 -04:00
if ret != 0:
success = False
self._log.warning('Command [%s] failed' % cmd)
if success:
self._log.info('All commands have been executed')
else:
self._log.error('Some commands were not successfully executed')
2014-03-19 23:07:30 -04:00
return success