hgbook

annotate en/examples/run-example @ 103:5b80c922ebdd

More merge content.
author Bryan O'Sullivan <bos@serpentine.com>
date Thu Oct 19 15:18:07 2006 -0700 (2006-10-19)
parents b476081a9c04
children c9aad709bd3a
rev   line source
bos@67 1 #!/usr/bin/env python
bos@4 2 #
bos@4 3 # This program takes something that resembles a shell script and runs
bos@4 4 # it, spitting input (commands from the script) and output into text
bos@4 5 # files, for use in examples.
bos@3 6
bos@3 7 import cStringIO
bos@73 8 import errno
bos@78 9 import getopt
bos@3 10 import os
bos@3 11 import pty
bos@3 12 import re
bos@79 13 import select
bos@4 14 import shutil
bos@6 15 import signal
bos@36 16 import stat
bos@3 17 import sys
bos@4 18 import tempfile
bos@4 19 import time
bos@3 20
bos@77 21 tex_subs = {
bos@77 22 '\\': '\\textbackslash{}',
bos@77 23 '{': '\\{',
bos@77 24 '}': '\\}',
bos@77 25 }
bos@77 26
bos@77 27 def gensubs(s):
bos@77 28 start = 0
bos@77 29 for i, c in enumerate(s):
bos@77 30 sub = tex_subs.get(c)
bos@77 31 if sub:
bos@77 32 yield s[start:i]
bos@77 33 start = i + 1
bos@77 34 yield sub
bos@77 35 yield s[start:]
bos@77 36
bos@4 37 def tex_escape(s):
bos@77 38 return ''.join(gensubs(s))
bos@4 39
bos@3 40 class example:
bos@70 41 shell = '/usr/bin/env bash'
bos@103 42 ps1 = '__run_example_ps1__ '
bos@103 43 ps2 = '__run_example_ps2__ '
bos@71 44 pi_re = re.compile(r'#\$\s*(name):\s*(.*)$')
bos@4 45
bos@79 46 timeout = 5
bos@79 47
bos@78 48 def __init__(self, name, verbose):
bos@3 49 self.name = name
bos@78 50 self.verbose = verbose
bos@79 51 self.poll = select.poll()
bos@3 52
bos@3 53 def parse(self):
bos@4 54 '''yield each hunk of input from the file.'''
bos@3 55 fp = open(self.name)
bos@3 56 cfp = cStringIO.StringIO()
bos@3 57 for line in fp:
bos@3 58 cfp.write(line)
bos@3 59 if not line.rstrip().endswith('\\'):
bos@3 60 yield cfp.getvalue()
bos@3 61 cfp.seek(0)
bos@3 62 cfp.truncate()
bos@3 63
bos@3 64 def status(self, s):
bos@3 65 sys.stdout.write(s)
bos@3 66 if not s.endswith('\n'):
bos@3 67 sys.stdout.flush()
bos@3 68
bos@6 69 def send(self, s):
bos@78 70 if self.verbose:
bos@78 71 print >> sys.stderr, '>', self.debugrepr(s)
bos@73 72 while s:
bos@73 73 count = os.write(self.cfd, s)
bos@73 74 s = s[count:]
bos@6 75
bos@78 76 def debugrepr(self, s):
bos@78 77 rs = repr(s)
bos@78 78 limit = 60
bos@78 79 if len(rs) > limit:
bos@78 80 return ('%s%s ... [%d bytes]' % (rs[:limit], rs[0], len(s)))
bos@78 81 else:
bos@78 82 return rs
bos@78 83
bos@79 84 timeout = 5
bos@79 85
bos@79 86 def read(self):
bos@79 87 events = self.poll.poll(self.timeout * 1000)
bos@79 88 if not events:
bos@79 89 print >> sys.stderr, '[timed out after %d seconds]' % self.timeout
bos@79 90 os.kill(self.pid, signal.SIGHUP)
bos@79 91 return ''
bos@79 92 return os.read(self.cfd, 1024)
bos@79 93
bos@6 94 def receive(self):
bos@6 95 out = cStringIO.StringIO()
bos@4 96 while True:
bos@73 97 try:
bos@78 98 if self.verbose:
bos@78 99 sys.stderr.write('< ')
bos@79 100 s = self.read()
bos@73 101 except OSError, err:
bos@73 102 if err.errno == errno.EIO:
bos@103 103 return '', ''
bos@73 104 raise
bos@78 105 if self.verbose:
bos@78 106 print >> sys.stderr, self.debugrepr(s)
bos@6 107 out.write(s)
bos@73 108 s = out.getvalue()
bos@103 109 if s.endswith(self.ps1):
bos@103 110 return self.ps1, s.replace('\r\n', '\n')[:-len(self.ps1)]
bos@103 111 if s.endswith(self.ps2):
bos@103 112 return self.ps2, s.replace('\r\n', '\n')[:-len(self.ps2)]
bos@4 113
bos@6 114 def sendreceive(self, s):
bos@6 115 self.send(s)
bos@103 116 ps, r = self.receive()
bos@6 117 if r.startswith(s):
bos@6 118 r = r[len(s):]
bos@103 119 return ps, r
bos@6 120
bos@3 121 def run(self):
bos@3 122 ofp = None
bos@4 123 basename = os.path.basename(self.name)
bos@4 124 self.status('running %s ' % basename)
bos@4 125 tmpdir = tempfile.mkdtemp(prefix=basename)
bos@78 126
bos@78 127 rcfile = os.path.join(tmpdir, '.hgrc')
bos@78 128 rcfp = open(rcfile, 'w')
bos@78 129 print >> rcfp, '[ui]'
bos@78 130 print >> rcfp, "username = Bryan O'Sullivan <bos@serpentine.com>"
bos@78 131
bos@6 132 rcfile = os.path.join(tmpdir, '.bashrc')
bos@6 133 rcfp = open(rcfile, 'w')
bos@103 134 print >> rcfp, 'PS1="%s"' % self.ps1
bos@103 135 print >> rcfp, 'PS2="%s"' % self.ps2
bos@6 136 print >> rcfp, 'unset HISTFILE'
bos@19 137 print >> rcfp, 'export EXAMPLE_DIR="%s"' % os.getcwd()
bos@6 138 print >> rcfp, 'export LANG=C'
bos@6 139 print >> rcfp, 'export LC_ALL=C'
bos@6 140 print >> rcfp, 'export TZ=GMT'
bos@6 141 print >> rcfp, 'export HGRC="%s/.hgrc"' % tmpdir
bos@6 142 print >> rcfp, 'export HGRCPATH=$HGRC'
bos@6 143 print >> rcfp, 'cd %s' % tmpdir
bos@6 144 rcfp.close()
bos@68 145 sys.stdout.flush()
bos@68 146 sys.stderr.flush()
bos@79 147 self.pid, self.cfd = pty.fork()
bos@79 148 if self.pid == 0:
bos@70 149 cmdline = ['/usr/bin/env', 'bash', '--noediting', '--noprofile',
bos@70 150 '--norc']
bos@68 151 try:
bos@68 152 os.execv(cmdline[0], cmdline)
bos@68 153 except OSError, err:
bos@68 154 print >> sys.stderr, '%s: %s' % (cmdline[0], err.strerror)
bos@68 155 sys.stderr.flush()
bos@68 156 os._exit(0)
bos@79 157 self.poll.register(self.cfd, select.POLLIN | select.POLLERR |
bos@79 158 select.POLLHUP)
bos@103 159
bos@103 160 prompts = {
bos@103 161 '': '',
bos@103 162 self.ps1: '$',
bos@103 163 self.ps2: '>',
bos@103 164 }
bos@103 165
bos@4 166 try:
bos@71 167 try:
bos@73 168 # eat first prompt string from shell
bos@79 169 self.read()
bos@71 170 # setup env and prompt
bos@103 171 ps, output = self.sendreceive('source %s\n' % rcfile)
bos@71 172 for hunk in self.parse():
bos@71 173 # is this line a processing instruction?
bos@71 174 m = self.pi_re.match(hunk)
bos@71 175 if m:
bos@71 176 pi, rest = m.groups()
bos@71 177 if pi == 'name':
bos@71 178 self.status('.')
bos@71 179 out = rest
bos@71 180 assert os.sep not in out
bos@71 181 if out:
bos@71 182 ofp = open('%s.%s.out' % (self.name, out), 'w')
bos@71 183 else:
bos@71 184 ofp = None
bos@71 185 elif hunk.strip():
bos@71 186 # it's something we should execute
bos@103 187 newps, output = self.sendreceive(hunk)
bos@71 188 if not ofp:
bos@71 189 continue
bos@71 190 # first, print the command we ran
bos@71 191 if not hunk.startswith('#'):
bos@71 192 nl = hunk.endswith('\n')
bos@103 193 hunk = ('%s \\textbf{%s}' %
bos@103 194 (prompts[ps],
bos@103 195 tex_escape(hunk.rstrip('\n'))))
bos@71 196 if nl: hunk += '\n'
bos@71 197 ofp.write(hunk)
bos@71 198 # then its output
bos@71 199 ofp.write(tex_escape(output))
bos@103 200 ps = newps
bos@71 201 self.status('\n')
bos@71 202 open(self.name + '.run', 'w')
bos@71 203 except:
bos@72 204 print >> sys.stderr, '(killed)'
bos@79 205 os.kill(self.pid, signal.SIGKILL)
bos@72 206 pid, rc = os.wait()
bos@71 207 raise
bos@72 208 else:
bos@71 209 try:
bos@103 210 ps, output = self.sendreceive('exit\n')
bos@71 211 if ofp:
bos@71 212 ofp.write(output)
bos@73 213 os.close(self.cfd)
bos@71 214 except IOError:
bos@71 215 pass
bos@79 216 os.kill(self.pid, signal.SIGTERM)
bos@72 217 pid, rc = os.wait()
bos@72 218 if rc:
bos@72 219 if os.WIFEXITED(rc):
bos@72 220 print >> sys.stderr, '(exit %s)' % os.WEXITSTATUS(rc)
bos@72 221 elif os.WIFSIGNALED(rc):
bos@72 222 print >> sys.stderr, '(signal %s)' % os.WTERMSIG(rc)
bos@72 223 return rc
bos@72 224 finally:
bos@4 225 shutil.rmtree(tmpdir)
bos@3 226
bos@3 227 def main(path='.'):
bos@78 228 opts, args = getopt.getopt(sys.argv[1:], 'v', ['verbose'])
bos@78 229 verbose = False
bos@78 230 for o, a in opts:
bos@78 231 if o in ('-v', '--verbose'):
bos@78 232 verbose = True
bos@71 233 errs = 0
bos@3 234 if args:
bos@3 235 for a in args:
bos@75 236 try:
bos@75 237 st = os.lstat(a)
bos@75 238 except OSError, err:
bos@75 239 print >> sys.stderr, '%s: %s' % (a, err.strerror)
bos@75 240 errs += 1
bos@75 241 continue
bos@75 242 if stat.S_ISREG(st.st_mode) and st.st_mode & 0111:
bos@78 243 if example(a, verbose).run():
bos@75 244 errs += 1
bos@75 245 else:
bos@75 246 print >> sys.stderr, '%s: not a file, or not executable' % a
bos@71 247 errs += 1
bos@71 248 return errs
bos@3 249 for name in os.listdir(path):
bos@3 250 if name == 'run-example' or name.startswith('.'): continue
bos@3 251 if name.endswith('.out') or name.endswith('~'): continue
bos@45 252 if name.endswith('.run'): continue
bos@19 253 pathname = os.path.join(path, name)
bos@36 254 st = os.lstat(pathname)
bos@36 255 if stat.S_ISREG(st.st_mode) and st.st_mode & 0111:
bos@78 256 if example(pathname, verbose).run():
bos@71 257 errs += 1
bos@4 258 print >> open(os.path.join(path, '.run'), 'w'), time.asctime()
bos@71 259 return errs
bos@3 260
bos@3 261 if __name__ == '__main__':
bos@71 262 sys.exit(main())