Refactoring: pass more than one file to resolved()
[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
7748ec70
KH
30_all_log_modes = ['debug', 'profile']
31_log_mode = os.environ.get('STGIT_SUBPROCESS_LOG', '')
32if _log_mode and not _log_mode in _all_log_modes:
33 out.warn(('Unknown log mode "%s" specified in $STGIT_SUBPROCESS_LOG.'
34 % _log_mode),
35 'Valid values are: %s' % ', '.join(_all_log_modes))
36
f0de3f92
KH
37class Run:
38 exc = RunException
39 def __init__(self, *cmd):
40 self.__cmd = list(cmd)
06104c20
KH
41 for c in cmd:
42 if type(c) != str:
f7268180 43 raise Exception, 'Bad command: %r' % (cmd,)
f0de3f92
KH
44 self.__good_retvals = [0]
45 self.__env = None
46 self.__indata = None
5dfab174 47 self.__discard_stderr = False
9371394e 48 def __log_start(self):
7748ec70 49 if _log_mode == 'debug':
9371394e 50 out.start('Running subprocess %s' % self.__cmd)
7748ec70 51 elif _log_mode == 'profile':
9371394e 52 out.start('Running subprocess %s' % self.__cmd[0])
7748ec70
KH
53 self.__starttime = datetime.datetime.now()
54 def __log_end(self, retcode):
55 if _log_mode == 'debug':
56 out.done('return code: %d' % retcode)
57 elif _log_mode == 'profile':
58 duration = datetime.datetime.now() - self.__starttime
59 out.done('%1.3f s' % (duration.microseconds/1e6 + duration.seconds))
9371394e 60 def __check_exitcode(self):
289687b4
KH
61 if self.__good_retvals == None:
62 return
f5a9f89f 63 if self.exitcode not in self.__good_retvals:
9371394e
KH
64 raise self.exc('%s failed with code %d'
65 % (self.__cmd[0], self.exitcode))
66 def __run_io(self):
67 """Run with captured IO."""
68 self.__log_start()
69 try:
70 p = subprocess.Popen(self.__cmd, env = self.__env,
71 stdin = subprocess.PIPE,
5dfab174
KH
72 stdout = subprocess.PIPE,
73 stderr = subprocess.PIPE)
9371394e
KH
74 outdata, errdata = p.communicate(self.__indata)
75 self.exitcode = p.returncode
76 except OSError, e:
77 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
5dfab174
KH
78 if errdata and not self.__discard_stderr:
79 out.err_raw(errdata)
9371394e
KH
80 self.__log_end(self.exitcode)
81 self.__check_exitcode()
f0de3f92 82 return outdata
289687b4 83 def __run_noio(self):
9371394e 84 """Run without captured IO."""
f0de3f92 85 assert self.__indata == None
9371394e
KH
86 self.__log_start()
87 try:
88 p = subprocess.Popen(self.__cmd, env = self.__env)
89 self.exitcode = p.wait()
90 except OSError, e:
91 raise self.exc('%s failed: %s' % (self.__cmd[0], e))
7748ec70 92 self.__log_end(self.exitcode)
289687b4 93 self.__check_exitcode()
f0de3f92
KH
94 def returns(self, retvals):
95 self.__good_retvals = retvals
96 return self
289687b4
KH
97 def discard_exitcode(self):
98 self.__good_retvals = None
99 return self
5dfab174
KH
100 def discard_stderr(self, discard = True):
101 self.__discard_stderr = discard
102 return self
f0de3f92 103 def env(self, env):
9371394e
KH
104 self.__env = dict(os.environ)
105 self.__env.update(env)
f0de3f92
KH
106 return self
107 def raw_input(self, indata):
108 self.__indata = indata
109 return self
110 def input_lines(self, lines):
111 self.__indata = ''.join(['%s\n' % line for line in lines])
112 return self
0fbf9801
KH
113 def input_nulterm(self, lines):
114 self.__indata = ''.join('%s\0' % line for line in lines)
115 return self
f0de3f92 116 def no_output(self):
9371394e 117 outdata = self.__run_io()
f0de3f92
KH
118 if outdata:
119 raise self.exc, '%s produced output' % self.__cmd[0]
120 def discard_output(self):
9371394e 121 self.__run_io()
f0de3f92 122 def raw_output(self):
9371394e 123 return self.__run_io()
f0de3f92 124 def output_lines(self):
9371394e 125 outdata = self.__run_io()
f0de3f92
KH
126 if outdata.endswith('\n'):
127 outdata = outdata[:-1]
128 if outdata:
129 return outdata.split('\n')
130 else:
131 return []
132 def output_one_line(self):
133 outlines = self.output_lines()
134 if len(outlines) == 1:
135 return outlines[0]
136 else:
137 raise self.exc('%s produced %d lines, expected 1'
138 % (self.__cmd[0], len(outlines)))
289687b4 139 def run(self):
f0de3f92 140 """Just run, with no IO redirection."""
289687b4 141 self.__run_noio()
f0de3f92
KH
142 def xargs(self, xargs):
143 """Just run, with no IO redirection. The extra arguments are
144 appended to the command line a few at a time; the command is
145 run as many times as needed to consume them all."""
146 step = 100
9371394e 147 basecmd = self.__cmd
f0de3f92 148 for i in xrange(0, len(xargs), step):
9371394e
KH
149 self.__cmd = basecmd + xargs[i:i+step]
150 self.__run_noio()
151 self.__cmd = basecmd