hgbook

view en/examples/run-example @ 67:a2f0b010d6e3

Don't assume that python is in /usr/bin.
author Bryan O'Sullivan <bos@serpentine.com>
date Mon Aug 07 15:35:14 2006 -0700 (2006-08-07)
parents 6b7b0339e7d6
children c574ce277a2b
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 = '/bin/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 pid, fd = pty.fork()
89 if pid == 0:
90 #os.execl(self.shell, self.shell)
91 os.system('/bin/bash --noediting --noprofile --norc')
92 sys.exit(0)
93 self.cfp = os.fdopen(fd, 'w+')
94 try:
95 # setup env and prompt
96 self.sendreceive('source %s\n\n' % rcfile)
97 for hunk in self.parse():
98 # is this line a processing instruction?
99 m = self.pi_re.match(hunk)
100 if m:
101 pi, rest = m.groups()
102 if pi == 'name':
103 self.status('.')
104 out = rest
105 assert os.sep not in out
106 if out:
107 ofp = open('%s.%s.out' % (self.name, out), 'w')
108 else:
109 ofp = None
110 elif hunk.strip():
111 # it's something we should execute
112 output = self.sendreceive(hunk)
113 if not ofp:
114 continue
115 # first, print the command we ran
116 if not hunk.startswith('#'):
117 nl = hunk.endswith('\n')
118 hunk = ('$ \\textbf{%s}' %
119 tex_escape(hunk.rstrip('\n')))
120 if nl: hunk += '\n'
121 ofp.write(hunk)
122 # then its output
123 ofp.write(tex_escape(output))
124 self.status('\n')
125 open(self.name + '.run', 'w')
126 finally:
127 try:
128 output = self.sendreceive('exit\n')
129 if ofp:
130 ofp.write(output)
131 self.cfp.close()
132 except IOError:
133 pass
134 os.kill(pid, signal.SIGTERM)
135 os.wait()
136 shutil.rmtree(tmpdir)
138 def main(path='.'):
139 args = sys.argv[1:]
140 if args:
141 for a in args:
142 example(a).run()
143 return
144 for name in os.listdir(path):
145 if name == 'run-example' or name.startswith('.'): continue
146 if name.endswith('.out') or name.endswith('~'): continue
147 if name.endswith('.run'): continue
148 pathname = os.path.join(path, name)
149 st = os.lstat(pathname)
150 if stat.S_ISREG(st.st_mode) and st.st_mode & 0111:
151 example(pathname).run()
152 print >> open(os.path.join(path, '.run'), 'w'), time.asctime()
154 if __name__ == '__main__':
155 main()