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', ''))
46 if _log_mode
== 'profile':
47 _log_starttime
= datetime
.datetime
.now()
48 _log_subproctime
= 0.0
52 return 86400*d
.days
+ d
.seconds
+ 1e-6*d
.microseconds
55 if _log_mode
!= 'profile':
57 ttime
= duration(_log_starttime
, datetime
.datetime
.now())
58 rtime
= ttime
- _log_subproctime
59 _logfile
.info('Total time: %1.3f s' % ttime
,
60 'Time spent in subprocess calls: %1.3f s (%1.1f%%)'
61 %
(_log_subproctime
, 100*_log_subproctime
/ttime
),
62 'Remaining time: %1.3f s (%1.1f%%)'
63 %
(rtime
, 100*rtime
/ttime
))
67 def __init__(self
, *cmd
):
68 self
.__cmd
= list(cmd
)
71 raise Exception, 'Bad command: %r' %
(cmd
,)
72 self
.__good_retvals
= [0]
73 self
.__env
= self
.__cwd
= None
75 self
.__discard_stderr
= False
76 def __log_start(self
):
77 if _log_mode
== 'debug':
78 _logfile
.start('Running subprocess %s' % self
.__cmd
)
79 if self
.__cwd
!= None:
80 _logfile
.info('cwd: %s' % self
.__cwd
)
81 if self
.__env
!= None:
82 for k
in sorted(self
.__env
.iterkeys()):
83 if k
not in os
.environ
or os
.environ
[k
] != self
.__env
[k
]:
84 _logfile
.info('%s: %s' %
(k
, self
.__env
[k
]))
85 elif _log_mode
== 'profile':
86 _logfile
.start('Running subprocess %s' % self
.__cmd
)
87 self
.__starttime
= datetime
.datetime
.now()
88 def __log_end(self
, retcode
):
89 global _log_subproctime
, _log_starttime
90 if _log_mode
== 'debug':
91 _logfile
.done('return code: %d' % retcode
)
92 elif _log_mode
== 'profile':
93 n
= datetime
.datetime
.now()
94 d
= duration(self
.__starttime
, n
)
95 _logfile
.done('%1.3f s' % d
)
97 _logfile
.info('Time since program start: %1.3f s'
98 % duration
(_log_starttime
, n
))
99 def __check_exitcode(self
):
100 if self
.__good_retvals
== None:
102 if self
.exitcode
not in self
.__good_retvals
:
103 raise self
.exc('%s failed with code %d'
104 %
(self
.__cmd
[0], self
.exitcode
))
106 """Run with captured IO."""
109 p
= subprocess
.Popen(self
.__cmd
, env
= self
.__env
, cwd
= self
.__cwd
,
110 stdin
= subprocess
.PIPE
,
111 stdout
= subprocess
.PIPE
,
112 stderr
= subprocess
.PIPE
)
113 # TODO: only use communicate() once support for Python 2.4 is
114 # dropped (write() needed because of performance reasons)
116 p
.stdin
.write(self
.__indata
)
117 outdata
, errdata
= p
.communicate()
118 self
.exitcode
= p
.returncode
120 raise self
.exc('%s failed: %s' %
(self
.__cmd
[0], e
))
121 if errdata
and not self
.__discard_stderr
:
123 self
.__log_end(self
.exitcode
)
124 self
.__check_exitcode()
126 def __run_noio(self
):
127 """Run without captured IO."""
128 assert self
.__indata
== None
131 p
= subprocess
.Popen(self
.__cmd
, env
= self
.__env
, cwd
= self
.__cwd
)
132 self
.exitcode
= p
.wait()
134 raise self
.exc('%s failed: %s' %
(self
.__cmd
[0], e
))
135 self
.__log_end(self
.exitcode
)
136 self
.__check_exitcode()
137 def returns(self
, retvals
):
138 self
.__good_retvals
= retvals
140 def discard_exitcode(self
):
141 self
.__good_retvals
= None
143 def discard_stderr(self
, discard
= True):
144 self
.__discard_stderr
= discard
147 self
.__env
= dict(os
.environ
)
148 self
.__env
.update(env
)
153 def raw_input(self
, indata
):
154 self
.__indata
= indata
156 def input_lines(self
, lines
):
157 self
.__indata
= ''.join(['%s\n' % line
for line
in lines
])
159 def input_nulterm(self
, lines
):
160 self
.__indata
= ''.join('%s\0' % line
for line
in lines
)
163 outdata
= self
.__run_io()
165 raise self
.exc
, '%s produced output' % self
.__cmd
[0]
166 def discard_output(self
):
168 def raw_output(self
):
169 return self
.__run_io()
170 def output_lines(self
):
171 outdata
= self
.__run_io()
172 if outdata
.endswith('\n'):
173 outdata
= outdata
[:-1]
175 return outdata
.split('\n')
178 def output_one_line(self
):
179 outlines
= self
.output_lines()
180 if len(outlines
) == 1:
183 raise self
.exc('%s produced %d lines, expected 1'
184 %
(self
.__cmd
[0], len(outlines
)))
186 """Just run, with no IO redirection."""
188 def xargs(self
, xargs
):
189 """Just run, with no IO redirection. The extra arguments are
190 appended to the command line a few at a time; the command is
191 run as many times as needed to consume them all."""
194 for i
in xrange(0, len(xargs
), step
):
195 self
.__cmd
= basecmd
+ xargs
[i
:i
+step
]