Skip to content

Commit

Permalink
put it in a class so other classes can use it
Browse files Browse the repository at this point in the history
  • Loading branch information
grayaii committed Mar 17, 2021
1 parent 4301c05 commit aa4bd52
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions retemplate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,25 @@ def get_value(self, key):
raise RetrievalError


class ProcessExecutor():
'''
A simple class to encapsulate the execution of external function calls.
'''

def exec_process(cmd):
'''
Shells out an external process and gets the stdout/stderr and returncoce.
'''
logging.debug('Running command: {}'.format(cmd))
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
shell=True)
output = p.communicate()[0]
returncode = p.returncode
return output, returncode

class LocalExecutionStore(DataStore):
'''
A DataStore that issues a terminal command and uses its standard output as a template value.
Expand All @@ -226,7 +245,7 @@ def get_value(self, key, **kwargs):
# Clean these args up a bit
for i in range(0, len(subp_args)):
subp_args[i] = subp_args[i].strip()
output, _ = self.exec_process(' '.join(subp_args))
output, _ = ProcessExecutor.exec_process(' '.join(subp_args))
return output
except Exception as ex:
logging.error('Failed to get local execution data. Error: {}'.format(ex))
Expand Down Expand Up @@ -365,20 +384,6 @@ def process(self, tpl):
prerender.append(line)
return '\n'.join(prerender)

def exec_process(self, cmd):
'''
Shells out an external process and gets the stdout/stderr and returncoce.
'''
logging.debug('Running command: {}'.format(cmd))
p = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
shell=True)
output = p.communicate()[0]
returncode = p.returncode
return output, returncode

def render(self):
'''
Renders a template in three phases:
Expand Down Expand Up @@ -450,7 +455,7 @@ def write_file(self, content):
shutil.chown(self.target, user=owner, group=group)
if chmod:
logging.info('Setting mode of {} to {}'.format(self.target, chmod))
self.exec_process(' '.join([ 'chmod', self.settings['chmod'], self.target ]))
ProcessExecutor.exec_process(' '.join([ 'chmod', self.settings['chmod'], self.target ]))
return True
except IOError:
logging.error('Cannot write target file {}'.format(self.target))
Expand All @@ -470,7 +475,7 @@ def execute_onchange(self):

logging.info('Running onchange command \'{}\' for target {}'.format(onchange, self.target))
try:
output, returncode = self.exec_process(onchange)
output, returncode = ProcessExecutor.exec_process(onchange)
logging.debug('onchange command exited: {}'.format(returncode))
logging.debug('onchange command output: {}'.format(output))
except subprocess.CalledProcessError as ex:
Expand Down

0 comments on commit aa4bd52

Please sign in to comment.