Commit | Line | Data |
---|---|---|
f0de3f92 KH |
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 | ||
9371394e | 20 | import datetime, os, subprocess |
7748ec70 | 21 | |
87c93eab KH |
22 | from stgit.exception import * |
23 | from stgit.out import * | |
7748ec70 | 24 | |
87c93eab | 25 | class 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', '') | |
32 | if _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 |
37 | class 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 | 44 | self.__good_retvals = [0] |
8d96d568 | 45 | self.__env = self.__cwd = None |
f0de3f92 | 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) |
fa2fa45e KH |
51 | if self.__cwd != None: |
52 | out.info('cwd: %s' % self.__cwd) | |
53 | if self.__env != None: | |
54 | for k in sorted(self.__env.iterkeys()): | |
55 | if k not in os.environ or os.environ[k] != self.__env[k]: | |
56 | out.info('%s: %s' % (k, self.__env[k])) | |
7748ec70 | 57 | elif _log_mode == 'profile': |
9371394e | 58 | out.start('Running subprocess %s' % self.__cmd[0]) |
7748ec70 KH |
59 | self.__starttime = datetime.datetime.now() |
60 | def __log_end(self, retcode): | |
61 | if _log_mode == 'debug': | |
62 | out.done('return code: %d' % retcode) | |
63 | elif _log_mode == 'profile': | |
64 | duration = datetime.datetime.now() - self.__starttime | |
65 | out.done('%1.3f s' % (duration.microseconds/1e6 + duration.seconds)) | |
9371394e | 66 | def __check_exitcode(self): |
289687b4 KH |
67 | if self.__good_retvals == None: |
68 | return | |
f5a9f89f | 69 | if self.exitcode not in self.__good_retvals: |
9371394e KH |
70 | raise self.exc('%s failed with code %d' |
71 | % (self.__cmd[0], self.exitcode)) | |
72 | def __run_io(self): | |
73 | """Run with captured IO.""" | |
74 | self.__log_start() | |
75 | try: | |
8d96d568 | 76 | p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd, |
9371394e | 77 | stdin = subprocess.PIPE, |
5dfab174 KH |
78 | stdout = subprocess.PIPE, |
79 | stderr = subprocess.PIPE) | |
9371394e KH |
80 | outdata, errdata = p.communicate(self.__indata) |
81 | self.exitcode = p.returncode | |
82 | except OSError, e: | |
83 | raise self.exc('%s failed: %s' % (self.__cmd[0], e)) | |
5dfab174 KH |
84 | if errdata and not self.__discard_stderr: |
85 | out.err_raw(errdata) | |
9371394e KH |
86 | self.__log_end(self.exitcode) |
87 | self.__check_exitcode() | |
f0de3f92 | 88 | return outdata |
289687b4 | 89 | def __run_noio(self): |
9371394e | 90 | """Run without captured IO.""" |
f0de3f92 | 91 | assert self.__indata == None |
9371394e KH |
92 | self.__log_start() |
93 | try: | |
8d96d568 | 94 | p = subprocess.Popen(self.__cmd, env = self.__env, cwd = self.__cwd) |
9371394e KH |
95 | self.exitcode = p.wait() |
96 | except OSError, e: | |
97 | raise self.exc('%s failed: %s' % (self.__cmd[0], e)) | |
7748ec70 | 98 | self.__log_end(self.exitcode) |
289687b4 | 99 | self.__check_exitcode() |
f0de3f92 KH |
100 | def returns(self, retvals): |
101 | self.__good_retvals = retvals | |
102 | return self | |
289687b4 KH |
103 | def discard_exitcode(self): |
104 | self.__good_retvals = None | |
105 | return self | |
5dfab174 KH |
106 | def discard_stderr(self, discard = True): |
107 | self.__discard_stderr = discard | |
108 | return self | |
f0de3f92 | 109 | def env(self, env): |
9371394e KH |
110 | self.__env = dict(os.environ) |
111 | self.__env.update(env) | |
f0de3f92 | 112 | return self |
8d96d568 KH |
113 | def cwd(self, cwd): |
114 | self.__cwd = cwd | |
115 | return self | |
f0de3f92 KH |
116 | def raw_input(self, indata): |
117 | self.__indata = indata | |
118 | return self | |
119 | def input_lines(self, lines): | |
120 | self.__indata = ''.join(['%s\n' % line for line in lines]) | |
121 | return self | |
0fbf9801 KH |
122 | def input_nulterm(self, lines): |
123 | self.__indata = ''.join('%s\0' % line for line in lines) | |
124 | return self | |
f0de3f92 | 125 | def no_output(self): |
9371394e | 126 | outdata = self.__run_io() |
f0de3f92 KH |
127 | if outdata: |
128 | raise self.exc, '%s produced output' % self.__cmd[0] | |
129 | def discard_output(self): | |
9371394e | 130 | self.__run_io() |
f0de3f92 | 131 | def raw_output(self): |
9371394e | 132 | return self.__run_io() |
f0de3f92 | 133 | def output_lines(self): |
9371394e | 134 | outdata = self.__run_io() |
f0de3f92 KH |
135 | if outdata.endswith('\n'): |
136 | outdata = outdata[:-1] | |
137 | if outdata: | |
138 | return outdata.split('\n') | |
139 | else: | |
140 | return [] | |
141 | def output_one_line(self): | |
142 | outlines = self.output_lines() | |
143 | if len(outlines) == 1: | |
144 | return outlines[0] | |
145 | else: | |
146 | raise self.exc('%s produced %d lines, expected 1' | |
147 | % (self.__cmd[0], len(outlines))) | |
289687b4 | 148 | def run(self): |
f0de3f92 | 149 | """Just run, with no IO redirection.""" |
289687b4 | 150 | self.__run_noio() |
f0de3f92 KH |
151 | def xargs(self, xargs): |
152 | """Just run, with no IO redirection. The extra arguments are | |
153 | appended to the command line a few at a time; the command is | |
154 | run as many times as needed to consume them all.""" | |
155 | step = 100 | |
9371394e | 156 | basecmd = self.__cmd |
f0de3f92 | 157 | for i in xrange(0, len(xargs), step): |
9371394e KH |
158 | self.__cmd = basecmd + xargs[i:i+step] |
159 | self.__run_noio() | |
160 | self.__cmd = basecmd |