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