Show full command in subprocess profiling
[stgit] / stgit / run.py
CommitLineData
f0de3f92
KH
1# -*- coding: utf-8 -*-
2
3__copyright__ = """
4Copyright (C) 2007, Karl Hasselström <kha@treskal.com>
5
6This program is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License version 2 as
8published by the Free Software Foundation.
9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program; if not, write to the Free Software
17Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18"""
19
9371394e 20import datetime, os, subprocess
7748ec70 21
87c93eab
KH
22from stgit.exception import *
23from stgit.out import *
7748ec70 24
87c93eab 25class RunException(StgException):
f0de3f92
KH
26 """Thrown when something bad happened when we tried to run the
27 subprocess."""
28 pass
29
cf8be1c8
KH
30def get_log_mode(spec):
31 if not ':' in spec:
32 spec += ':'
33 (log_mode, outfile) = spec.split(':', 1)
34 all_log_modes = ['debug', 'profile']
35 if log_mode and not log_mode in all_log_modes:
36 out.warn(('Unknown log mode "%s" specified in $STGIT_SUBPROCESS_LOG.'
37 % log_mode),
38 'Valid values are: %s' % ', '.join(all_log_modes))
39 if outfile:
40 f = MessagePrinter(open(outfile, 'a'))
41 else:
42 f = out
43 return (log_mode, f)
44
45(_log_mode, _logfile) = get_log_mode(os.environ.get('STGIT_SUBPROCESS_LOG', ''))
7748ec70 46
f0de3f92
KH
47class Run:
48 exc = RunException
49 def __init__(self, *cmd):
50 self.__cmd = list(cmd)
06104c20
KH
51 for c in cmd:
52 if type(c) != str:
f7268180 53 raise Exception, 'Bad command: %r' % (cmd,)
f0de3f92 54 self.__good_retvals = [0]
8d96d568 55 self.__env = self.__cwd = None
f0de3f92 56 self.__indata = None
5dfab174 57 self.__discard_stderr = False
9371394e 58 def __log_start(self):
7748ec70 59 if _log_mode == 'debug':
cf8be1c8 60 _logfile.start('Running subprocess %s' % self.__cmd)
fa2fa45e 61 if self.__cwd != None:
cf8be1c8 62 _logfile.info('cwd: %s' % self.__cwd)
fa2fa45e
KH
63 if self.__env != None:
64 for k in sorted(self.__env.iterkeys()):
65 if k not in os.environ or os.environ[k] != self.__env[k]:
cf8be1c8 66 _logfile.info('%s: %s' % (k, self.__env[k]))
7748ec70 67 elif _log_mode == 'profile':
16d143bf 68 _logfile.start('Running subprocess %s' % self.__cmd)
7748ec70
KH
69 self.__starttime = datetime.datetime.now()
70 def __log_end(self, retcode):
71 if _log_mode == 'debug':
cf8be1c8 72 _logfile.done('return code: %d' % retcode)
7748ec70
KH
73 elif _log_mode == 'profile':
74 duration = datetime.datetime.now() - self.__starttime
cf8be1c8
KH
75 _logfile.done('%1.3f s' % (duration.microseconds/1e6
76 + duration.seconds))
9371394e 77 def __check_exitcode(self):
289687b4
KH
78 if self.__good_retvals == None:
79 return
f5a9f89f 80 if self.exitcode not in self.__good_retvals:
9371394e
KH
81 raise self.exc('%s failed with code %d'
82 % (self.__cmd[0], self.exitcode))
83 def __run_io(self):
84 """Run with captured IO."""
85 self.__log_start()
86 try:
8d96d568 87 p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd,
9371394e 88 stdin = subprocess.PIPE,
5dfab174
KH
89 stdout = subprocess.PIPE,
90 stderr = subprocess.PIPE)
9371394e
KH
91 outdata, errdata = p.communicate(self.__indata)
92 self.exitcode = p.returncode
93 except OSError, e:
94 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
5dfab174
KH
95 if errdata and not self.__discard_stderr:
96 out.err_raw(errdata)
9371394e
KH
97 self.__log_end(self.exitcode)
98 self.__check_exitcode()
f0de3f92 99 return outdata
289687b4 100 def __run_noio(self):
9371394e 101 """Run without captured IO."""
f0de3f92 102 assert self.__indata == None
9371394e
KH
103 self.__log_start()
104 try:
8d96d568 105 p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd)
9371394e
KH
106 self.exitcode = p.wait()
107 except OSError, e:
108 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
7748ec70 109 self.__log_end(self.exitcode)
289687b4 110 self.__check_exitcode()
f0de3f92
KH
111 def returns(self, retvals):
112 self.__good_retvals = retvals
113 return self
289687b4
KH
114 def discard_exitcode(self):
115 self.__good_retvals = None
116 return self
5dfab174
KH
117 def discard_stderr(self, discard = True):
118 self.__discard_stderr = discard
119 return self
f0de3f92 120 def env(self, env):
9371394e
KH
121 self.__env = dict(os.environ)
122 self.__env.update(env)
f0de3f92 123 return self
8d96d568
KH
124 def cwd(self, cwd):
125 self.__cwd = cwd
126 return self
f0de3f92
KH
127 def raw_input(self, indata):
128 self.__indata = indata
129 return self
130 def input_lines(self, lines):
131 self.__indata = ''.join(['%s\n' % line for line in lines])
132 return self
0fbf9801
KH
133 def input_nulterm(self, lines):
134 self.__indata = ''.join('%s\0' % line for line in lines)
135 return self
f0de3f92 136 def no_output(self):
9371394e 137 outdata = self.__run_io()
f0de3f92
KH
138 if outdata:
139 raise self.exc, '%s produced output' % self.__cmd[0]
140 def discard_output(self):
9371394e 141 self.__run_io()
f0de3f92 142 def raw_output(self):
9371394e 143 return self.__run_io()
f0de3f92 144 def output_lines(self):
9371394e 145 outdata = self.__run_io()
f0de3f92
KH
146 if outdata.endswith('\n'):
147 outdata = outdata[:-1]
148 if outdata:
149 return outdata.split('\n')
150 else:
151 return []
152 def output_one_line(self):
153 outlines = self.output_lines()
154 if len(outlines) == 1:
155 return outlines[0]
156 else:
157 raise self.exc('%s produced %d lines, expected 1'
158 % (self.__cmd[0], len(outlines)))
289687b4 159 def run(self):
f0de3f92 160 """Just run, with no IO redirection."""
289687b4 161 self.__run_noio()
f0de3f92
KH
162 def xargs(self, xargs):
163 """Just run, with no IO redirection. The extra arguments are
164 appended to the command line a few at a time; the command is
165 run as many times as needed to consume them all."""
166 step = 100
9371394e 167 basecmd = self.__cmd
f0de3f92 168 for i in xrange(0, len(xargs), step):
9371394e
KH
169 self.__cmd = basecmd + xargs[i:i+step]
170 self.__run_noio()
171 self.__cmd = basecmd