befd3c10f8533ffe17fefd8c6dd47df7d29d68fb
[stgit] / stgit / run.py
1 # -*- coding: utf-8 -*-
2
3 __copyright__ = """
4 Copyright (C) 2007, Karl Hasselström <kha@treskal.com>
5
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.
9
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.
14
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
18 """
19
20 import datetime, os, subprocess
21
22 from stgit.exception import *
23 from stgit.out import *
24
25 class RunException(StgException):
26 """Thrown when something bad happened when we tried to run the
27 subprocess."""
28 pass
29
30 def 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', ''))
46
47 class Run:
48 exc = RunException
49 def __init__(self, *cmd):
50 self.__cmd = list(cmd)
51 for c in cmd:
52 if type(c) != str:
53 raise Exception, 'Bad command: %r' % (cmd,)
54 self.__good_retvals = [0]
55 self.__env = self.__cwd = None
56 self.__indata = None
57 self.__discard_stderr = False
58 def __log_start(self):
59 if _log_mode == 'debug':
60 _logfile.start('Running subprocess %s' % self.__cmd)
61 if self.__cwd != None:
62 _logfile.info('cwd: %s' % self.__cwd)
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]:
66 _logfile.info('%s: %s' % (k, self.__env[k]))
67 elif _log_mode == 'profile':
68 _logfile.start('Running subprocess %s' % self.__cmd)
69 self.__starttime = datetime.datetime.now()
70 def __log_end(self, retcode):
71 if _log_mode == 'debug':
72 _logfile.done('return code: %d' % retcode)
73 elif _log_mode == 'profile':
74 duration = datetime.datetime.now() - self.__starttime
75 _logfile.done('%1.3f s' % (duration.microseconds/1e6
76 + duration.seconds))
77 def __check_exitcode(self):
78 if self.__good_retvals == None:
79 return
80 if self.exitcode not in self.__good_retvals:
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:
87 p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd,
88 stdin = subprocess.PIPE,
89 stdout = subprocess.PIPE,
90 stderr = subprocess.PIPE)
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))
95 if errdata and not self.__discard_stderr:
96 out.err_raw(errdata)
97 self.__log_end(self.exitcode)
98 self.__check_exitcode()
99 return outdata
100 def __run_noio(self):
101 """Run without captured IO."""
102 assert self.__indata == None
103 self.__log_start()
104 try:
105 p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd)
106 self.exitcode = p.wait()
107 except OSError, e:
108 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
109 self.__log_end(self.exitcode)
110 self.__check_exitcode()
111 def returns(self, retvals):
112 self.__good_retvals = retvals
113 return self
114 def discard_exitcode(self):
115 self.__good_retvals = None
116 return self
117 def discard_stderr(self, discard = True):
118 self.__discard_stderr = discard
119 return self
120 def env(self, env):
121 self.__env = dict(os.environ)
122 self.__env.update(env)
123 return self
124 def cwd(self, cwd):
125 self.__cwd = cwd
126 return self
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
133 def input_nulterm(self, lines):
134 self.__indata = ''.join('%s\0' % line for line in lines)
135 return self
136 def no_output(self):
137 outdata = self.__run_io()
138 if outdata:
139 raise self.exc, '%s produced output' % self.__cmd[0]
140 def discard_output(self):
141 self.__run_io()
142 def raw_output(self):
143 return self.__run_io()
144 def output_lines(self):
145 outdata = self.__run_io()
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)))
159 def run(self):
160 """Just run, with no IO redirection."""
161 self.__run_noio()
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
167 basecmd = self.__cmd
168 for i in xrange(0, len(xargs), step):
169 self.__cmd = basecmd + xargs[i:i+step]
170 self.__run_noio()
171 self.__cmd = basecmd