befd3c10f8533ffe17fefd8c6dd47df7d29d68fb
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 def get_log_mode(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.'
38 'Valid values are: %s' %
', '.join(all_log_modes
))
40 f
= MessagePrinter(open(outfile
, 'a'))
45 (_log_mode
, _logfile
) = get_log_mode(os
.environ
.get('STGIT_SUBPROCESS_LOG', ''))
49 def __init__(self
, *cmd
):
50 self
.__cmd
= list(cmd
)
53 raise Exception, 'Bad command: %r' %
(cmd
,)
54 self
.__good_retvals
= [0]
55 self
.__env
= self
.__cwd
= 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
77 def __check_exitcode(self
):
78 if self
.__good_retvals
== None:
80 if self
.exitcode
not in self
.__good_retvals
:
81 raise self
.exc('%s failed with code %d'
82 %
(self
.__cmd
[0], self
.exitcode
))
84 """Run with captured IO."""
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
94 raise self
.exc('%s failed: %s' %
(self
.__cmd
[0], e
))
95 if errdata
and not self
.__discard_stderr
:
97 self
.__log_end(self
.exitcode
)
98 self
.__check_exitcode()
100 def __run_noio(self
):
101 """Run without captured IO."""
102 assert self
.__indata
== None
105 p
= subprocess
.Popen(self
.__cmd
, env
= self
.__env
, cwd
= self
.__cwd
)
106 self
.exitcode
= p
.wait()
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
114 def discard_exitcode(self
):
115 self
.__good_retvals
= None
117 def discard_stderr(self
, discard
= True):
118 self
.__discard_stderr
= discard
121 self
.__env
= dict(os
.environ
)
122 self
.__env
.update(env
)
127 def raw_input(self
, indata
):
128 self
.__indata
= indata
130 def input_lines(self
, lines
):
131 self
.__indata
= ''.join(['%s\n' % line
for line
in lines
])
133 def input_nulterm(self
, lines
):
134 self
.__indata
= ''.join('%s\0' % line
for line
in lines
)
137 outdata
= self
.__run_io()
139 raise self
.exc
, '%s produced output' % self
.__cmd
[0]
140 def discard_output(self
):
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]
149 return outdata
.split('\n')
152 def output_one_line(self
):
153 outlines
= self
.output_lines()
154 if len(outlines
) == 1:
157 raise self
.exc('%s produced %d lines, expected 1'
158 %
(self
.__cmd
[0], len(outlines
)))
160 """Just run, with no IO redirection."""
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."""
168 for i
in xrange(0, len(xargs
), step
):
169 self
.__cmd
= basecmd
+ xargs
[i
:i
+step
]