chiark / gitweb /
d925ccea68c6200f9aae90330ec5366a2d06c862
[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 # popen2 and os.spawn* suck. We should really use subprocess instead,
21 # but that's only available in Python 2.4 and up, and we try our best
22 # to stay Python 2.3 compatible.
23 import popen2, os
24
25 class RunException(Exception):
26     """Thrown when something bad happened when we tried to run the
27     subprocess."""
28     pass
29
30 class Run:
31     exc = RunException
32     def __init__(self, *cmd):
33         self.__cmd = list(cmd)
34         self.__good_retvals = [0]
35         self.__env = None
36         self.__indata = None
37     def __run_io(self, cmd):
38         """Run with captured IO. Note: arguments are parsed by the
39         shell. We single-quote them, so don't use anything with single
40         quotes in it."""
41         if self.__env == None:
42             ecmd = cmd
43         else:
44             ecmd = (['env'] + ['%s=%s' % (key, val)
45                                for key, val in self.__env.iteritems()]
46                     + cmd)
47         p = popen2.Popen3(' '.join(["'%s'" % c for c in ecmd]), True)
48         if self.__indata != None:
49             p.tochild.write(self.__indata)
50         p.tochild.close()
51         outdata = p.fromchild.read()
52         errdata = p.childerr.read()
53         self.exitcode = p.wait() >> 8
54         if errdata or self.exitcode not in self.__good_retvals:
55             raise self.exc('%s failed with code %d:\n%s'
56                            % (cmd[0], self.exitcode, errdata))
57         return outdata
58     def __run_noshell(self, cmd):
59         """Run without captured IO. Note: arguments are not parsed by
60         the shell."""
61         assert self.__env == None
62         assert self.__indata == None
63         self.exitcode = os.spawnvp(os.P_WAIT, cmd[0], cmd)
64         if not self.exitcode in self.__good_retvals:
65             raise self.exc('%s failed with code %d'
66                            % (cmd[0], self.exitcode))
67     def returns(self, retvals):
68         self.__good_retvals = retvals
69         return self
70     def env(self, env):
71         self.__env = env
72         return self
73     def raw_input(self, indata):
74         self.__indata = indata
75         return self
76     def input_lines(self, lines):
77         self.__indata = ''.join(['%s\n' % line for line in lines])
78         return self
79     def no_output(self):
80         outdata = self.__run_io(self.__cmd)
81         if outdata:
82             raise self.exc, '%s produced output' % self.__cmd[0]
83     def discard_output(self):
84         self.__run_io(self.__cmd)
85     def raw_output(self):
86         return self.__run_io(self.__cmd)
87     def output_lines(self):
88         outdata = self.__run_io(self.__cmd)
89         if outdata.endswith('\n'):
90             outdata = outdata[:-1]
91         if outdata:
92             return outdata.split('\n')
93         else:
94             return []
95     def output_one_line(self):
96         outlines = self.output_lines()
97         if len(outlines) == 1:
98             return outlines[0]
99         else:
100             raise self.exc('%s produced %d lines, expected 1'
101                            % (self.__cmd[0], len(outlines)))
102     def run(self):
103         """Just run, with no IO redirection."""
104         self.__run_noshell(self.__cmd)
105     def xargs(self, xargs):
106         """Just run, with no IO redirection. The extra arguments are
107         appended to the command line a few at a time; the command is
108         run as many times as needed to consume them all."""
109         step = 100
110         for i in xrange(0, len(xargs), step):
111             self.__run_noshell(self.__cmd + xargs[i:i+step])