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