hgbook

view en/examples/run-example @ 70:365b41b6a15e

bash is not necessarily in /bin.
Original patch against an earlier rev from Guy Brand <gb@isis.u-strasbg.fr>.
author Bryan O'Sullivan <bos@serpentine.com>
date Tue Aug 08 14:13:28 2006 -0700 (2006-08-08)
parents c574ce277a2b
children ddf533d41c09
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('#\$\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 # setup env and prompt
103 self.sendreceive('source %s\n\n' % rcfile)
104 for hunk in self.parse():
105 # is this line a processing instruction?
106 m = self.pi_re.match(hunk)
107 if m:
108 pi, rest = m.groups()
109 if pi == 'name':
110 self.status('.')
111 out = rest
112 assert os.sep not in out
113 if out:
114 ofp = open('%s.%s.out' % (self.name, out), 'w')
115 else:
116 ofp = None
117 elif hunk.strip():
118 # it's something we should execute
119 output = self.sendreceive(hunk)
120 if not ofp:
121 continue
122 # first, print the command we ran
123 if not hunk.startswith('#'):
124 nl = hunk.endswith('\n')
125 hunk = ('$ \\textbf{%s}' %
126 tex_escape(hunk.rstrip('\n')))
127 if nl: hunk += '\n'
128 ofp.write(hunk)
129 # then its output
130 ofp.write(tex_escape(output))
131 self.status('\n')
132 open(self.name + '.run', 'w')
133 finally:
134 try:
135 output = self.sendreceive('exit\n')
136 if ofp:
137 ofp.write(output)
138 self.cfp.close()
139 except IOError:
140 pass
141 os.kill(pid, signal.SIGTERM)
142 os.wait()
143 shutil.rmtree(tmpdir)
145 def main(path='.'):
146 args = sys.argv[1:]
147 if args:
148 for a in args:
149 example(a).run()
150 return
151 for name in os.listdir(path):
152 if name == 'run-example' or name.startswith('.'): continue
153 if name.endswith('.out') or name.endswith('~'): continue
154 if name.endswith('.run'): continue
155 pathname = os.path.join(path, name)
156 st = os.lstat(pathname)
157 if stat.S_ISREG(st.st_mode) and st.st_mode & 0111:
158 example(pathname).run()
159 print >> open(os.path.join(path, '.run'), 'w'), time.asctime()
161 if __name__ == '__main__':
162 main()