1 # -*- coding: utf-8 -*-
4 Copyright (C) 2007, Karl Hasselström <kha@treskal.com>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License version 2 as
8 published by the Free Software Foundation.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 # popen2 and os.spawn* suck. We should really use subprocess instead,
21 # but that's only available in Python 2.4 and up, and we try our best
22 # to stay Python 2.3 compatible.
27 from stgit.out import *
29 class RunException(Exception):
30 """Thrown when something bad happened when we tried to run the
34 _all_log_modes = ['debug', 'profile']
35 _log_mode = os.environ.get('STGIT_SUBPROCESS_LOG', '')
36 if _log_mode and not _log_mode in _all_log_modes:
37 out.warn(('Unknown log mode "%s" specified in $STGIT_SUBPROCESS_LOG.'
39 'Valid values are: %s' % ', '.join(_all_log_modes))
43 def __init__(self, *cmd):
44 self.__cmd = list(cmd)
47 raise Exception, 'Bad command: %r' % cmd
48 self.__good_retvals = [0]
51 def __log_start(self, cmd):
52 if _log_mode == 'debug':
53 out.start('Running subprocess %s' % cmd)
54 elif _log_mode == 'profile':
55 out.start('Running subprocess %s' % cmd[0])
56 self.__starttime = datetime.datetime.now()
57 def __log_end(self, retcode):
58 if _log_mode == 'debug':
59 out.done('return code: %d' % retcode)
60 elif _log_mode == 'profile':
61 duration = datetime.datetime.now() - self.__starttime
62 out.done('%1.3f s' % (duration.microseconds/1e6 + duration.seconds))
63 def __run_io(self, cmd):
64 """Run with captured IO. Note: arguments are parsed by the
65 shell. We single-quote them, so don't use anything with single
67 if self.__env == None:
70 ecmd = (['env'] + ['%s=%s' % (key, val)
71 for key, val in self.__env.iteritems()]
73 self.__log_start(ecmd)
74 p = popen2.Popen3(' '.join(["'%s'" % c for c in ecmd]), True)
75 if self.__indata != None:
76 p.tochild.write(self.__indata)
78 outdata = p.fromchild.read()
79 errdata = p.childerr.read()
80 self.exitcode = p.wait() >> 8
81 self.__log_end(self.exitcode)
82 if self.exitcode not in self.__good_retvals:
83 raise self.exc('%s failed with code %d:\n%s'
84 % (cmd[0], self.exitcode, errdata))
86 out.warn('call to %s succeeded, but generated a warning:' % cmd[0])
89 def __run_noshell(self, cmd):
90 """Run without captured IO. Note: arguments are not parsed by
92 assert self.__env == None
93 assert self.__indata == None
95 self.exitcode = os.spawnvp(os.P_WAIT, cmd[0], cmd)
96 self.__log_end(self.exitcode)
97 if not self.exitcode in self.__good_retvals:
98 raise self.exc('%s failed with code %d'
99 % (cmd[0], self.exitcode))
100 def returns(self, retvals):
101 self.__good_retvals = retvals
106 def raw_input(self, indata):
107 self.__indata = indata
109 def input_lines(self, lines):
110 self.__indata = ''.join(['%s\n' % line for line in lines])
113 outdata = self.__run_io(self.__cmd)
115 raise self.exc, '%s produced output' % self.__cmd[0]
116 def discard_output(self):
117 self.__run_io(self.__cmd)
118 def raw_output(self):
119 return self.__run_io(self.__cmd)
120 def output_lines(self):
121 outdata = self.__run_io(self.__cmd)
122 if outdata.endswith('\n'):
123 outdata = outdata[:-1]
125 return outdata.split('\n')
128 def output_one_line(self):
129 outlines = self.output_lines()
130 if len(outlines) == 1:
133 raise self.exc('%s produced %d lines, expected 1'
134 % (self.__cmd[0], len(outlines)))
136 """Just run, with no IO redirection."""
137 self.__run_noshell(self.__cmd)
138 def xargs(self, xargs):
139 """Just run, with no IO redirection. The extra arguments are
140 appended to the command line a few at a time; the command is
141 run as many times as needed to consume them all."""
143 for i in xrange(0, len(xargs), step):
144 self.__run_noshell(self.__cmd + xargs[i:i+step])