hgbook

annotate en/examples/run-example @ 75:2bfa2499e971

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