hgbook

view en/examples/run-example @ 72:12df31afb4e1

Propagate exceptions more correctly.
author Bryan O'Sullivan <bos@serpentine.com>
date Tue Aug 29 22:34:03 2006 -0700 (2006-08-29)
parents ddf533d41c09
children 9604dd885616
line source
1 #!/usr/bin/env python
2 #
3 # This program takes something that resembles a shell script and runs
4 # it, spitting input (commands from the script) and output into text
5 # files, for use in examples.
7 import cStringIO
8 import os
9 import pty
10 import re
11 import shutil
12 import signal
13 import stat
14 import sys
15 import tempfile
16 import time
18 def tex_escape(s):
19 if '\\' in s:
20 s = s.replace('\\', '\\\\')
21 if '{' in s:
22 s = s.replace('{', '\\{')
23 if '}' in s:
24 s = s.replace('}', '\\}')
25 return s
27 class example:
28 shell = '/usr/bin/env bash'
29 prompt = '__run_example_prompt__\n'
30 pi_re = re.compile(r'#\$\s*(name):\s*(.*)$')
32 def __init__(self, name):
33 self.name = name
35 def parse(self):
36 '''yield each hunk of input from the file.'''
37 fp = open(self.name)
38 cfp = cStringIO.StringIO()
39 for line in fp:
40 cfp.write(line)
41 if not line.rstrip().endswith('\\'):
42 yield cfp.getvalue()
43 cfp.seek(0)
44 cfp.truncate()
46 def status(self, s):
47 sys.stdout.write(s)
48 if not s.endswith('\n'):
49 sys.stdout.flush()
51 def send(self, s):
52 self.cfp.write(s)
53 self.cfp.flush()
55 def receive(self):
56 out = cStringIO.StringIO()
57 while True:
58 s = self.cfp.readline().replace('\r\n', '\n')
59 if not s or s == self.prompt:
60 break
61 out.write(s)
62 return out.getvalue()
64 def sendreceive(self, s):
65 self.send(s)
66 r = self.receive()
67 if r.startswith(s):
68 r = r[len(s):]
69 return r
71 def run(self):
72 ofp = None
73 basename = os.path.basename(self.name)
74 self.status('running %s ' % basename)
75 tmpdir = tempfile.mkdtemp(prefix=basename)
76 rcfile = os.path.join(tmpdir, '.bashrc')
77 rcfp = open(rcfile, 'w')
78 print >> rcfp, 'PS1="%s"' % self.prompt
79 print >> rcfp, 'unset HISTFILE'
80 print >> rcfp, 'export EXAMPLE_DIR="%s"' % os.getcwd()
81 print >> rcfp, 'export LANG=C'
82 print >> rcfp, 'export LC_ALL=C'
83 print >> rcfp, 'export TZ=GMT'
84 print >> rcfp, 'export HGRC="%s/.hgrc"' % tmpdir
85 print >> rcfp, 'export HGRCPATH=$HGRC'
86 print >> rcfp, 'cd %s' % tmpdir
87 rcfp.close()
88 sys.stdout.flush()
89 sys.stderr.flush()
90 pid, fd = pty.fork()
91 if pid == 0:
92 cmdline = ['/usr/bin/env', 'bash', '--noediting', '--noprofile',
93 '--norc']
94 try:
95 os.execv(cmdline[0], cmdline)
96 except OSError, err:
97 print >> sys.stderr, '%s: %s' % (cmdline[0], err.strerror)
98 sys.stderr.flush()
99 os._exit(0)
100 self.cfp = os.fdopen(fd, 'w+')
101 try:
102 try:
103 # setup env and prompt
104 self.sendreceive('source %s\n\n' % rcfile)
105 for hunk in self.parse():
106 # is this line a processing instruction?
107 m = self.pi_re.match(hunk)
108 if m:
109 pi, rest = m.groups()
110 if pi == 'name':
111 self.status('.')
112 out = rest
113 assert os.sep not in out
114 if out:
115 ofp = open('%s.%s.out' % (self.name, out), 'w')
116 else:
117 ofp = None
118 elif hunk.strip():
119 # it's something we should execute
120 output = self.sendreceive(hunk)
121 if not ofp:
122 continue
123 # first, print the command we ran
124 if not hunk.startswith('#'):
125 nl = hunk.endswith('\n')
126 hunk = ('$ \\textbf{%s}' %
127 tex_escape(hunk.rstrip('\n')))
128 if nl: hunk += '\n'
129 ofp.write(hunk)
130 # then its output
131 ofp.write(tex_escape(output))
132 self.status('\n')
133 open(self.name + '.run', 'w')
134 except:
135 print >> sys.stderr, '(killed)'
136 os.kill(pid, signal.SIGKILL)
137 pid, rc = os.wait()
138 raise
139 else:
140 try:
141 output = self.sendreceive('exit\n')
142 if ofp:
143 ofp.write(output)
144 self.cfp.close()
145 except IOError:
146 pass
147 os.kill(pid, signal.SIGTERM)
148 pid, rc = os.wait()
149 if rc:
150 if os.WIFEXITED(rc):
151 print >> sys.stderr, '(exit %s)' % os.WEXITSTATUS(rc)
152 elif os.WIFSIGNALED(rc):
153 print >> sys.stderr, '(signal %s)' % os.WTERMSIG(rc)
154 return rc
155 finally:
156 shutil.rmtree(tmpdir)
158 def main(path='.'):
159 args = sys.argv[1:]
160 errs = 0
161 if args:
162 for a in args:
163 if example(a).run():
164 errs += 1
165 return errs
166 for name in os.listdir(path):
167 if name == 'run-example' or name.startswith('.'): continue
168 if name.endswith('.out') or name.endswith('~'): continue
169 if name.endswith('.run'): continue
170 pathname = os.path.join(path, name)
171 st = os.lstat(pathname)
172 if stat.S_ISREG(st.st_mode) and st.st_mode & 0111:
173 if example(pathname).run():
174 errs += 1
175 print >> open(os.path.join(path, '.run'), 'w'), time.asctime()
176 return errs
178 if __name__ == '__main__':
179 sys.exit(main())