chiark / gitweb /
Ignore the gitk exit code in 'stg log -g' (bug #10010)
[stgit] / stgit / run.py
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
20 import datetime, os, subprocess
21
22 from stgit.exception import *
23 from stgit.out import *
24
25 class RunException(StgException):
26     """Thrown when something bad happened when we tried to run the
27     subprocess."""
28     pass
29
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
37 class Run:
38     exc = RunException
39     def __init__(self, *cmd):
40         self.__cmd = list(cmd)
41         for c in cmd:
42             if type(c) != str:
43                 raise Exception, 'Bad command: %r' % (cmd,)
44         self.__good_retvals = [0]
45         self.__env = None
46         self.__indata = None
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.exitcode not in self.__good_retvals:
62             raise self.exc('%s failed with code %d'
63                            % (self.__cmd[0], self.exitcode))
64     def __run_io(self):
65         """Run with captured IO."""
66         self.__log_start()
67         try:
68             p = subprocess.Popen(self.__cmd, env = self.__env,
69                                  stdin = subprocess.PIPE,
70                                  stdout = subprocess.PIPE,
71                                  stderr = subprocess.PIPE)
72             outdata, errdata = p.communicate(self.__indata)
73             self.exitcode = p.returncode
74         except OSError, e:
75             raise self.exc('%s failed: %s' % (self.__cmd[0], e))
76         if errdata and not self.__discard_stderr:
77             out.err_raw(errdata)
78         self.__log_end(self.exitcode)
79         self.__check_exitcode()
80         return outdata
81     def __run_noio(self, exitcode = True):
82         """Run without captured IO."""
83         assert self.__indata == None
84         self.__log_start()
85         try:
86             p = subprocess.Popen(self.__cmd, env = self.__env)
87             self.exitcode = p.wait()
88         except OSError, e:
89             raise self.exc('%s failed: %s' % (self.__cmd[0], e))
90         self.__log_end(self.exitcode)
91         if exitcode:
92             self.__check_exitcode()
93     def returns(self, retvals):
94         self.__good_retvals = retvals
95         return self
96     def discard_stderr(self, discard = True):
97         self.__discard_stderr = discard
98         return self
99     def env(self, env):
100         self.__env = dict(os.environ)
101         self.__env.update(env)
102         return self
103     def raw_input(self, indata):
104         self.__indata = indata
105         return self
106     def input_lines(self, lines):
107         self.__indata = ''.join(['%s\n' % line for line in lines])
108         return self
109     def no_output(self):
110         outdata = self.__run_io()
111         if outdata:
112             raise self.exc, '%s produced output' % self.__cmd[0]
113     def discard_output(self):
114         self.__run_io()
115     def raw_output(self):
116         return self.__run_io()
117     def output_lines(self):
118         outdata = self.__run_io()
119         if outdata.endswith('\n'):
120             outdata = outdata[:-1]
121         if outdata:
122             return outdata.split('\n')
123         else:
124             return []
125     def output_one_line(self):
126         outlines = self.output_lines()
127         if len(outlines) == 1:
128             return outlines[0]
129         else:
130             raise self.exc('%s produced %d lines, expected 1'
131                            % (self.__cmd[0], len(outlines)))
132     def run(self, exitcode = True):
133         """Just run, with no IO redirection."""
134         self.__run_noio(exitcode = exitcode)
135     def xargs(self, xargs):
136         """Just run, with no IO redirection. The extra arguments are
137         appended to the command line a few at a time; the command is
138         run as many times as needed to consume them all."""
139         step = 100
140         basecmd = self.__cmd
141         for i in xrange(0, len(xargs), step):
142             self.__cmd = basecmd + xargs[i:i+step]
143             self.__run_noio()
144         self.__cmd = basecmd