1 # -*- coding: utf-8 -*-
4 Copyright (C) 2007, Karl Hasselström <kha@treskal.com>
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.
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.
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
20 import datetime
, os
, subprocess
22 from stgit
.exception
import *
23 from stgit
.out
import *
25 class RunException(StgException
):
26 """Thrown when something bad happened when we tried to run the
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.'
35 'Valid values are: %s' %
', '.join(_all_log_modes
))
39 def __init__(self
, *cmd
):
40 self
.__cmd
= list(cmd
)
43 raise Exception, 'Bad command: %r' %
(cmd
,)
44 self
.__good_retvals
= [0]
47 self
.__discard_stderr
= False
48 def __log_start(self
):
49 if _log_mode
== 'debug':
50 out
.start('Running subprocess %s' % self
.__cmd
)
51 elif _log_mode
== 'profile':
52 out
.start('Running subprocess %s' % self
.__cmd
[0])
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
))
60 def __check_exitcode(self
):
61 if self
.__good_retvals
== None:
63 if self
.exitcode
not in self
.__good_retvals
:
64 raise self
.exc('%s failed with code %d'
65 %
(self
.__cmd
[0], self
.exitcode
))
67 """Run with captured IO."""
70 p
= subprocess
.Popen(self
.__cmd
, env
= self
.__env
,
71 stdin
= subprocess
.PIPE
,
72 stdout
= subprocess
.PIPE
,
73 stderr
= subprocess
.PIPE
)
74 outdata
, errdata
= p
.communicate(self
.__indata
)
75 self
.exitcode
= p
.returncode
77 raise self
.exc('%s failed: %s' %
(self
.__cmd
[0], e
))
78 if errdata
and not self
.__discard_stderr
:
80 self
.__log_end(self
.exitcode
)
81 self
.__check_exitcode()
84 """Run without captured IO."""
85 assert self
.__indata
== None
88 p
= subprocess
.Popen(self
.__cmd
, env
= self
.__env
)
89 self
.exitcode
= p
.wait()
91 raise self
.exc('%s failed: %s' %
(self
.__cmd
[0], e
))
92 self
.__log_end(self
.exitcode
)
93 self
.__check_exitcode()
94 def returns(self
, retvals
):
95 self
.__good_retvals
= retvals
97 def discard_exitcode(self
):
98 self
.__good_retvals
= None
100 def discard_stderr(self
, discard
= True):
101 self
.__discard_stderr
= discard
104 self
.__env
= dict(os
.environ
)
105 self
.__env
.update(env
)
107 def raw_input(self
, indata
):
108 self
.__indata
= indata
110 def input_lines(self
, lines
):
111 self
.__indata
= ''.join(['%s\n' % line
for line
in lines
])
114 outdata
= self
.__run_io()
116 raise self
.exc
, '%s produced output' % self
.__cmd
[0]
117 def discard_output(self
):
119 def raw_output(self
):
120 return self
.__run_io()
121 def output_lines(self
):
122 outdata
= self
.__run_io()
123 if outdata
.endswith('\n'):
124 outdata
= outdata
[:-1]
126 return outdata
.split('\n')
129 def output_one_line(self
):
130 outlines
= self
.output_lines()
131 if len(outlines
) == 1:
134 raise self
.exc('%s produced %d lines, expected 1'
135 %
(self
.__cmd
[0], len(outlines
)))
137 """Just run, with no IO redirection."""
139 def xargs(self
, xargs
):
140 """Just run, with no IO redirection. The extra arguments are
141 appended to the command line a few at a time; the command is
142 run as many times as needed to consume them all."""
145 for i
in xrange(0, len(xargs
), step
):
146 self
.__cmd
= basecmd
+ xargs
[i
:i
+step
]