Strip leading or trailing '-' when generating patch names
[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', ''))
36a06e01
KH
46if _log_mode == 'profile':
47 _log_starttime = datetime.datetime.now()
48 _log_subproctime = 0.0
49
50def duration(t1, t2):
51 d = t2 - t1
52 return 86400*d.days + d.seconds + 1e-6*d.microseconds
53
54def finish_logging():
55 if _log_mode != 'profile':
56 return
57 ttime = duration(_log_starttime, datetime.datetime.now())
58 rtime = ttime - _log_subproctime
59 _logfile.info('Total time: %1.3f s' % ttime,
60 'Time spent in subprocess calls: %1.3f s (%1.1f%%)'
61 % (_log_subproctime, 100*_log_subproctime/ttime),
62 'Remaining time: %1.3f s (%1.1f%%)'
63 % (rtime, 100*rtime/ttime))
7748ec70 64
f0de3f92
KH
65class Run:
66 exc = RunException
67 def __init__(self, *cmd):
68 self.__cmd = list(cmd)
06104c20
KH
69 for c in cmd:
70 if type(c) != str:
f7268180 71 raise Exception, 'Bad command: %r' % (cmd,)
f0de3f92 72 self.__good_retvals = [0]
8d96d568 73 self.__env = self.__cwd = None
f0de3f92 74 self.__indata = None
5dfab174 75 self.__discard_stderr = False
9371394e 76 def __log_start(self):
7748ec70 77 if _log_mode == 'debug':
cf8be1c8 78 _logfile.start('Running subprocess %s' % self.__cmd)
fa2fa45e 79 if self.__cwd != None:
cf8be1c8 80 _logfile.info('cwd: %s' % self.__cwd)
fa2fa45e
KH
81 if self.__env != None:
82 for k in sorted(self.__env.iterkeys()):
83 if k not in os.environ or os.environ[k] != self.__env[k]:
cf8be1c8 84 _logfile.info('%s: %s' % (k, self.__env[k]))
7748ec70 85 elif _log_mode == 'profile':
16d143bf 86 _logfile.start('Running subprocess %s' % self.__cmd)
7748ec70
KH
87 self.__starttime = datetime.datetime.now()
88 def __log_end(self, retcode):
36a06e01 89 global _log_subproctime, _log_starttime
7748ec70 90 if _log_mode == 'debug':
cf8be1c8 91 _logfile.done('return code: %d' % retcode)
7748ec70 92 elif _log_mode == 'profile':
36a06e01
KH
93 n = datetime.datetime.now()
94 d = duration(self.__starttime, n)
95 _logfile.done('%1.3f s' % d)
96 _log_subproctime += d
97 _logfile.info('Time since program start: %1.3f s'
98 % duration(_log_starttime, n))
9371394e 99 def __check_exitcode(self):
289687b4
KH
100 if self.__good_retvals == None:
101 return
f5a9f89f 102 if self.exitcode not in self.__good_retvals:
9371394e
KH
103 raise self.exc('%s failed with code %d'
104 % (self.__cmd[0], self.exitcode))
105 def __run_io(self):
106 """Run with captured IO."""
107 self.__log_start()
108 try:
8d96d568 109 p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd,
9371394e 110 stdin = subprocess.PIPE,
5dfab174
KH
111 stdout = subprocess.PIPE,
112 stderr = subprocess.PIPE)
465e13d3
KW
113 # TODO: only use communicate() once support for Python 2.4 is
114 # dropped (write() needed because of performance reasons)
115 if self.__indata:
116 p.stdin.write(self.__indata)
117 outdata, errdata = p.communicate()
9371394e
KH
118 self.exitcode = p.returncode
119 except OSError, e:
120 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
5dfab174
KH
121 if errdata and not self.__discard_stderr:
122 out.err_raw(errdata)
9371394e
KH
123 self.__log_end(self.exitcode)
124 self.__check_exitcode()
f0de3f92 125 return outdata
289687b4 126 def __run_noio(self):
9371394e 127 """Run without captured IO."""
f0de3f92 128 assert self.__indata == None
9371394e
KH
129 self.__log_start()
130 try:
8d96d568 131 p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd)
9371394e
KH
132 self.exitcode = p.wait()
133 except OSError, e:
134 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
7748ec70 135 self.__log_end(self.exitcode)
289687b4 136 self.__check_exitcode()
f0de3f92
KH
137 def returns(self, retvals):
138 self.__good_retvals = retvals
139 return self
289687b4
KH
140 def discard_exitcode(self):
141 self.__good_retvals = None
142 return self
5dfab174
KH
143 def discard_stderr(self, discard = True):
144 self.__discard_stderr = discard
145 return self
f0de3f92 146 def env(self, env):
9371394e
KH
147 self.__env = dict(os.environ)
148 self.__env.update(env)
f0de3f92 149 return self
8d96d568
KH
150 def cwd(self, cwd):
151 self.__cwd = cwd
152 return self
f0de3f92
KH
153 def raw_input(self, indata):
154 self.__indata = indata
155 return self
156 def input_lines(self, lines):
157 self.__indata = ''.join(['%s\n' % line for line in lines])
158 return self
0fbf9801
KH
159 def input_nulterm(self, lines):
160 self.__indata = ''.join('%s\0' % line for line in lines)
161 return self
f0de3f92 162 def no_output(self):
9371394e 163 outdata = self.__run_io()
f0de3f92
KH
164 if outdata:
165 raise self.exc, '%s produced output' % self.__cmd[0]
166 def discard_output(self):
9371394e 167 self.__run_io()
f0de3f92 168 def raw_output(self):
9371394e 169 return self.__run_io()
f0de3f92 170 def output_lines(self):
9371394e 171 outdata = self.__run_io()
f0de3f92
KH
172 if outdata.endswith('\n'):
173 outdata = outdata[:-1]
174 if outdata:
175 return outdata.split('\n')
176 else:
177 return []
178 def output_one_line(self):
179 outlines = self.output_lines()
180 if len(outlines) == 1:
181 return outlines[0]
182 else:
183 raise self.exc('%s produced %d lines, expected 1'
184 % (self.__cmd[0], len(outlines)))
289687b4 185 def run(self):
f0de3f92 186 """Just run, with no IO redirection."""
289687b4 187 self.__run_noio()
f0de3f92
KH
188 def xargs(self, xargs):
189 """Just run, with no IO redirection. The extra arguments are
190 appended to the command line a few at a time; the command is
191 run as many times as needed to consume them all."""
192 step = 100
9371394e 193 basecmd = self.__cmd
f0de3f92 194 for i in xrange(0, len(xargs), step):
9371394e
KH
195 self.__cmd = basecmd + xargs[i:i+step]
196 self.__run_noio()
197 self.__cmd = basecmd