hgbook

annotate en/examples/run-example @ 73:9604dd885616

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