hgbook

view en/examples/run-example @ 71:ddf533d41c09

Propagate errors correctly.
author Bryan O'Sullivan <bos@serpentine.com>
date Tue Aug 29 22:25:18 2006 -0700 (2006-08-29)
parents 365b41b6a15e
children 12df31afb4e1
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 clean_exit = True
103 try:
104 # setup env and prompt
105 self.sendreceive('source %s\n\n' % rcfile)
106 for hunk in self.parse():
107 # is this line a processing instruction?
108 m = self.pi_re.match(hunk)
109 if m:
110 pi, rest = m.groups()
111 if pi == 'name':
112 self.status('.')
113 out = rest
114 assert os.sep not in out
115 if out:
116 ofp = open('%s.%s.out' % (self.name, out), 'w')
117 else:
118 ofp = None
119 elif hunk.strip():
120 # it's something we should execute
121 output = self.sendreceive(hunk)
122 if not ofp:
123 continue
124 # first, print the command we ran
125 if not hunk.startswith('#'):
126 nl = hunk.endswith('\n')
127 hunk = ('$ \\textbf{%s}' %
128 tex_escape(hunk.rstrip('\n')))
129 if nl: hunk += '\n'
130 ofp.write(hunk)
131 # then its output
132 ofp.write(tex_escape(output))
133 self.status('\n')
134 open(self.name + '.run', 'w')
135 except:
136 clean_exit = False
137 raise
138 finally:
139 if clean_exit:
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 time.sleep(0.1)
149 os.kill(pid, signal.SIGKILL)
150 pid, rc = os.wait()
151 if rc:
152 if os.WIFEXITED(rc):
153 print >> sys.stderr, '(exit %s)' % os.WEXITSTATUS(rc)
154 elif os.WIFSIGNALED(rc):
155 print >> sys.stderr, '(signal %s)' % os.WTERMSIG(rc)
156 shutil.rmtree(tmpdir)
157 return rc
159 def main(path='.'):
160 args = sys.argv[1:]
161 errs = 0
162 if args:
163 for a in args:
164 if example(a).run():
165 errs += 1
166 return errs
167 for name in os.listdir(path):
168 if name == 'run-example' or name.startswith('.'): continue
169 if name.endswith('.out') or name.endswith('~'): continue
170 if name.endswith('.run'): continue
171 pathname = os.path.join(path, name)
172 st = os.lstat(pathname)
173 if stat.S_ISREG(st.st_mode) and st.st_mode & 0111:
174 if example(pathname).run():
175 errs += 1
176 print >> open(os.path.join(path, '.run'), 'w'), time.asctime()
177 return errs
179 if __name__ == '__main__':
180 sys.exit(main())