Write warnings and errors to stderr if not on a terminal
[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
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.
23import popen2, os
24
7748ec70
KH
25import datetime
26
27from stgit.out import *
28
f0de3f92
KH
29class RunException(Exception):
30 """Thrown when something bad happened when we tried to run the
31 subprocess."""
32 pass
33
7748ec70
KH
34_all_log_modes = ['debug', 'profile']
35_log_mode = os.environ.get('STGIT_SUBPROCESS_LOG', '')
36if _log_mode and not _log_mode in _all_log_modes:
37 out.warn(('Unknown log mode "%s" specified in $STGIT_SUBPROCESS_LOG.'
38 % _log_mode),
39 'Valid values are: %s' % ', '.join(_all_log_modes))
40
f0de3f92
KH
41class Run:
42 exc = RunException
43 def __init__(self, *cmd):
44 self.__cmd = list(cmd)
06104c20
KH
45 for c in cmd:
46 if type(c) != str:
47 raise Exception, 'Bad command: %r' % cmd
f0de3f92
KH
48 self.__good_retvals = [0]
49 self.__env = None
50 self.__indata = None
7748ec70
KH
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))
f0de3f92
KH
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
66 quotes in it."""
67 if self.__env == None:
68 ecmd = cmd
69 else:
70 ecmd = (['env'] + ['%s=%s' % (key, val)
71 for key, val in self.__env.iteritems()]
72 + cmd)
7748ec70 73 self.__log_start(ecmd)
f0de3f92
KH
74 p = popen2.Popen3(' '.join(["'%s'" % c for c in ecmd]), True)
75 if self.__indata != None:
76 p.tochild.write(self.__indata)
77 p.tochild.close()
78 outdata = p.fromchild.read()
79 errdata = p.childerr.read()
80 self.exitcode = p.wait() >> 8
7748ec70 81 self.__log_end(self.exitcode)
f0de3f92
KH
82 if errdata or self.exitcode not in self.__good_retvals:
83 raise self.exc('%s failed with code %d:\n%s'
84 % (cmd[0], self.exitcode, errdata))
85 return outdata
86 def __run_noshell(self, cmd):
87 """Run without captured IO. Note: arguments are not parsed by
88 the shell."""
89 assert self.__env == None
90 assert self.__indata == None
7748ec70 91 self.__log_start(cmd)
f0de3f92 92 self.exitcode = os.spawnvp(os.P_WAIT, cmd[0], cmd)
7748ec70 93 self.__log_end(self.exitcode)
f0de3f92
KH
94 if not self.exitcode in self.__good_retvals:
95 raise self.exc('%s failed with code %d'
96 % (cmd[0], self.exitcode))
97 def returns(self, retvals):
98 self.__good_retvals = retvals
99 return self
100 def env(self, env):
101 self.__env = env
102 return self
103 def raw_input(self, indata):
104 self.__indata = indata
105 return self
106 def input_lines(self, lines):
107 self.__indata = ''.join(['%s\n' % line for line in lines])
108 return self
109 def no_output(self):
110 outdata = self.__run_io(self.__cmd)
111 if outdata:
112 raise self.exc, '%s produced output' % self.__cmd[0]
113 def discard_output(self):
114 self.__run_io(self.__cmd)
115 def raw_output(self):
116 return self.__run_io(self.__cmd)
117 def output_lines(self):
118 outdata = self.__run_io(self.__cmd)
119 if outdata.endswith('\n'):
120 outdata = outdata[:-1]
121 if outdata:
122 return outdata.split('\n')
123 else:
124 return []
125 def output_one_line(self):
126 outlines = self.output_lines()
127 if len(outlines) == 1:
128 return outlines[0]
129 else:
130 raise self.exc('%s produced %d lines, expected 1'
131 % (self.__cmd[0], len(outlines)))
132 def run(self):
133 """Just run, with no IO redirection."""
134 self.__run_noshell(self.__cmd)
135 def xargs(self, xargs):
136 """Just run, with no IO redirection. The extra arguments are
137 appended to the command line a few at a time; the command is
138 run as many times as needed to consume them all."""
139 step = 100
140 for i in xrange(0, len(xargs), step):
141 self.__run_noshell(self.__cmd + xargs[i:i+step])