hgbook

annotate en/examples/run-example @ 579:80928ea6e7ae

Add the ability to include text files and have them XML-mangled.
author Bryan O'Sullivan <bos@serpentine.com>
date Tue Mar 17 21:47:12 2009 -0700 (2009-03-17)
parents 60ee738fdc0e
children 8366882f67f2
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@564 21 xml_subs = {
bos@564 22 '<': '&lt;',
bos@564 23 '>': '&gt;',
bos@564 24 '&': '&amp;',
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@564 30 sub = xml_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@564 37 def xml_escape(s):
bos@77 38 return ''.join(gensubs(s))
bos@4 39
bos@137 40 def maybe_unlink(name):
bos@137 41 try:
bos@137 42 os.unlink(name)
bos@137 43 return True
bos@137 44 except OSError, err:
bos@137 45 if err.errno != errno.ENOENT:
bos@137 46 raise
bos@137 47 return False
bos@137 48
bos@172 49 def find_path_to(program):
bos@172 50 for p in os.environ.get('PATH', os.defpath).split(os.pathsep):
bos@172 51 name = os.path.join(p, program)
bos@172 52 if os.access(name, os.X_OK):
bos@172 53 return p
bos@172 54 return None
bos@172 55
bos@564 56 def result_name(name):
bos@579 57 return os.path.join('results', name.replace(os.sep, '-'))
bos@564 58
bos@3 59 class example:
bos@579 60 entities = dict.fromkeys(l.rstrip() for l in open('auto-snippets.xml'))
bos@579 61
bos@579 62 def __init__(self, name, verbose, keep_change):
bos@579 63 self.name = name
bos@579 64 self.verbose = verbose
bos@579 65 self.keep_change = keep_change
bos@579 66
bos@579 67 def rename_output(self, base, ignore=[]):
bos@579 68 mangle_re = re.compile('(?:' + '|'.join(ignore) + ')')
bos@579 69 def mangle(s):
bos@579 70 return mangle_re.sub('', s)
bos@579 71 def matchfp(fp1, fp2):
bos@579 72 while True:
bos@579 73 s1 = mangle(fp1.readline())
bos@579 74 s2 = mangle(fp2.readline())
bos@579 75 if cmp(s1, s2):
bos@579 76 break
bos@579 77 if not s1:
bos@579 78 return True
bos@579 79 return False
bos@579 80
bos@579 81 oldname = result_name(base + '.out')
bos@579 82 tmpname = result_name(base + '.tmp')
bos@579 83 errname = result_name(base + '.err')
bos@579 84 errfp = open(errname, 'w+')
bos@579 85 for line in open(tmpname):
bos@579 86 errfp.write(mangle_re.sub('', line))
bos@579 87 os.rename(tmpname, result_name(base + '.lxo'))
bos@579 88 errfp.seek(0)
bos@579 89 try:
bos@579 90 oldfp = open(oldname)
bos@579 91 except IOError, err:
bos@579 92 if err.errno != errno.ENOENT:
bos@579 93 raise
bos@579 94 os.rename(errname, oldname)
bos@579 95 return False
bos@579 96 if matchfp(oldfp, errfp):
bos@579 97 os.unlink(errname)
bos@579 98 return False
bos@579 99 else:
bos@579 100 print >> sys.stderr, '\nOutput of %s has changed!' % baseq
bos@579 101 if self.keep_change:
bos@579 102 os.rename(errname, oldname)
bos@579 103 return False
bos@579 104 else:
bos@579 105 os.system('diff -u %s %s 1>&2' % (oldname, errname))
bos@579 106 return True
bos@579 107
bos@579 108 def wopen(name):
bos@579 109 path = os.path.dirname(name)
bos@579 110 if path:
bos@579 111 try:
bos@579 112 os.makedirs(path)
bos@579 113 except OSError, err:
bos@579 114 if err.errno != errno.EEXIST:
bos@579 115 raise
bos@579 116 return open(name, 'w')
bos@579 117
bos@579 118 class static_example(example):
bos@579 119 def run(self):
bos@579 120 s = open(self.name).read().rstrip()
bos@579 121 s = s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
bos@579 122 ofp = wopen(result_name(self.name + '.tmp'))
bos@579 123 ofp.write('<programlisting>')
bos@579 124 ofp.write(s)
bos@579 125 ofp.write('</programlisting>\n')
bos@579 126 ofp.close()
bos@579 127 self.rename_output(self.name)
bos@579 128 norm = self.name.replace(os.sep, '-')
bos@579 129 example.entities[
bos@579 130 '<!ENTITY %s SYSTEM "results/%s.out">' % (norm, norm)] = 1
bos@579 131
bos@579 132
bos@579 133 class shell_example(example):
bos@70 134 shell = '/usr/bin/env bash'
bos@103 135 ps1 = '__run_example_ps1__ '
bos@103 136 ps2 = '__run_example_ps2__ '
bos@168 137 pi_re = re.compile(r'#\$\s*(name|ignore):\s*(.*)$')
bos@4 138
bos@192 139 timeout = 10
bos@79 140
bos@545 141 def __init__(self, name, verbose, keep_change):
bos@579 142 example.__init__(self, name, verbose, keep_change)
bos@79 143 self.poll = select.poll()
bos@3 144
bos@3 145 def parse(self):
bos@4 146 '''yield each hunk of input from the file.'''
bos@3 147 fp = open(self.name)
bos@3 148 cfp = cStringIO.StringIO()
bos@3 149 for line in fp:
bos@3 150 cfp.write(line)
bos@3 151 if not line.rstrip().endswith('\\'):
bos@3 152 yield cfp.getvalue()
bos@3 153 cfp.seek(0)
bos@3 154 cfp.truncate()
bos@3 155
bos@3 156 def status(self, s):
bos@3 157 sys.stdout.write(s)
bos@3 158 if not s.endswith('\n'):
bos@3 159 sys.stdout.flush()
bos@3 160
bos@6 161 def send(self, s):
bos@78 162 if self.verbose:
bos@78 163 print >> sys.stderr, '>', self.debugrepr(s)
bos@73 164 while s:
bos@73 165 count = os.write(self.cfd, s)
bos@73 166 s = s[count:]
bos@6 167
bos@78 168 def debugrepr(self, s):
bos@78 169 rs = repr(s)
bos@78 170 limit = 60
bos@78 171 if len(rs) > limit:
bos@78 172 return ('%s%s ... [%d bytes]' % (rs[:limit], rs[0], len(s)))
bos@78 173 else:
bos@78 174 return rs
bos@78 175
bos@79 176 timeout = 5
bos@79 177
bos@173 178 def read(self, hint):
bos@79 179 events = self.poll.poll(self.timeout * 1000)
bos@79 180 if not events:
bos@173 181 print >> sys.stderr, ('[%stimed out after %d seconds]' %
bos@173 182 (hint, self.timeout))
bos@79 183 os.kill(self.pid, signal.SIGHUP)
bos@79 184 return ''
bos@79 185 return os.read(self.cfd, 1024)
bos@79 186
bos@173 187 def receive(self, hint):
bos@6 188 out = cStringIO.StringIO()
bos@4 189 while True:
bos@73 190 try:
bos@78 191 if self.verbose:
bos@78 192 sys.stderr.write('< ')
bos@173 193 s = self.read(hint)
bos@73 194 except OSError, err:
bos@73 195 if err.errno == errno.EIO:
bos@103 196 return '', ''
bos@73 197 raise
bos@78 198 if self.verbose:
bos@78 199 print >> sys.stderr, self.debugrepr(s)
bos@6 200 out.write(s)
bos@73 201 s = out.getvalue()
bos@103 202 if s.endswith(self.ps1):
bos@103 203 return self.ps1, s.replace('\r\n', '\n')[:-len(self.ps1)]
bos@103 204 if s.endswith(self.ps2):
bos@103 205 return self.ps2, s.replace('\r\n', '\n')[:-len(self.ps2)]
bos@4 206
bos@173 207 def sendreceive(self, s, hint):
bos@6 208 self.send(s)
bos@173 209 ps, r = self.receive(hint)
bos@6 210 if r.startswith(s):
bos@6 211 r = r[len(s):]
bos@103 212 return ps, r
bos@6 213
bos@3 214 def run(self):
bos@3 215 ofp = None
bos@4 216 basename = os.path.basename(self.name)
bos@4 217 self.status('running %s ' % basename)
bos@4 218 tmpdir = tempfile.mkdtemp(prefix=basename)
bos@78 219
bos@136 220 # remove the marker file that we tell make to use to see if
bos@136 221 # this run succeeded
bos@137 222 maybe_unlink(self.name + '.run')
bos@136 223
bos@78 224 rcfile = os.path.join(tmpdir, '.hgrc')
bos@579 225 rcfp = wopen(rcfile)
bos@78 226 print >> rcfp, '[ui]'
bos@78 227 print >> rcfp, "username = Bryan O'Sullivan <bos@serpentine.com>"
bos@78 228
bos@6 229 rcfile = os.path.join(tmpdir, '.bashrc')
bos@579 230 rcfp = wopen(rcfile)
bos@103 231 print >> rcfp, 'PS1="%s"' % self.ps1
bos@103 232 print >> rcfp, 'PS2="%s"' % self.ps2
bos@6 233 print >> rcfp, 'unset HISTFILE'
bos@172 234 path = ['/usr/bin', '/bin']
bos@172 235 hg = find_path_to('hg')
bos@172 236 if hg and hg not in path:
bos@172 237 path.append(hg)
bos@172 238 def re_export(envar):
bos@172 239 v = os.getenv(envar)
bos@172 240 if v is not None:
bos@172 241 print >> rcfp, 'export ' + envar + '=' + v
bos@172 242 print >> rcfp, 'export PATH=' + ':'.join(path)
bos@172 243 re_export('PYTHONPATH')
bos@19 244 print >> rcfp, 'export EXAMPLE_DIR="%s"' % os.getcwd()
bos@124 245 print >> rcfp, 'export HGMERGE=merge'
bos@6 246 print >> rcfp, 'export LANG=C'
bos@6 247 print >> rcfp, 'export LC_ALL=C'
bos@6 248 print >> rcfp, 'export TZ=GMT'
bos@6 249 print >> rcfp, 'export HGRC="%s/.hgrc"' % tmpdir
bos@6 250 print >> rcfp, 'export HGRCPATH=$HGRC'
bos@6 251 print >> rcfp, 'cd %s' % tmpdir
bos@6 252 rcfp.close()
bos@68 253 sys.stdout.flush()
bos@68 254 sys.stderr.flush()
bos@79 255 self.pid, self.cfd = pty.fork()
bos@79 256 if self.pid == 0:
bos@172 257 cmdline = ['/usr/bin/env', '-i', 'bash', '--noediting',
bos@172 258 '--noprofile', '--norc']
bos@68 259 try:
bos@68 260 os.execv(cmdline[0], cmdline)
bos@68 261 except OSError, err:
bos@68 262 print >> sys.stderr, '%s: %s' % (cmdline[0], err.strerror)
bos@68 263 sys.stderr.flush()
bos@68 264 os._exit(0)
bos@79 265 self.poll.register(self.cfd, select.POLLIN | select.POLLERR |
bos@79 266 select.POLLHUP)
bos@103 267
bos@103 268 prompts = {
bos@103 269 '': '',
bos@103 270 self.ps1: '$',
bos@103 271 self.ps2: '>',
bos@103 272 }
bos@103 273
bos@137 274 ignore = [
bos@137 275 r'\d+:[0-9a-f]{12}', # changeset number:hash
bos@141 276 r'[0-9a-f]{40}', # long changeset hash
bos@141 277 r'[0-9a-f]{12}', # short changeset hash
bos@137 278 r'^(?:---|\+\+\+) .*', # diff header with dates
bos@137 279 r'^date:.*', # date
bos@141 280 #r'^diff -r.*', # "diff -r" is followed by hash
bos@138 281 r'^# Date \d+ \d+', # hg patch header
bos@137 282 ]
bos@137 283
bos@138 284 err = False
bos@173 285 read_hint = ''
bos@138 286
bos@4 287 try:
bos@71 288 try:
bos@73 289 # eat first prompt string from shell
bos@173 290 self.read(read_hint)
bos@71 291 # setup env and prompt
bos@173 292 ps, output = self.sendreceive('source %s\n' % rcfile,
bos@173 293 read_hint)
bos@71 294 for hunk in self.parse():
bos@71 295 # is this line a processing instruction?
bos@71 296 m = self.pi_re.match(hunk)
bos@71 297 if m:
bos@71 298 pi, rest = m.groups()
bos@71 299 if pi == 'name':
bos@71 300 self.status('.')
bos@71 301 out = rest
bos@155 302 if out in ('err', 'lxo', 'out', 'run', 'tmp'):
bos@155 303 print >> sys.stderr, ('%s: illegal section '
bos@155 304 'name %r' %
bos@155 305 (self.name, out))
bos@155 306 return 1
bos@71 307 assert os.sep not in out
bos@137 308 if ofp is not None:
bos@564 309 ofp.write('</screen>\n')
bos@137 310 ofp.close()
bos@160 311 err |= self.rename_output(ofp_basename, ignore)
bos@71 312 if out:
bos@137 313 ofp_basename = '%s.%s' % (self.name, out)
bos@566 314 norm = os.path.normpath(ofp_basename)
bos@566 315 example.entities[
bos@569 316 '<!ENTITY interaction.%s '
bos@566 317 'SYSTEM "results/%s.out">'
bos@566 318 % (norm, norm)] = 1
bos@173 319 read_hint = ofp_basename + ' '
bos@579 320 ofp = wopen(result_name(ofp_basename + '.tmp'))
bos@564 321 ofp.write('<screen>')
bos@71 322 else:
bos@71 323 ofp = None
bos@137 324 elif pi == 'ignore':
bos@137 325 ignore.append(rest)
bos@71 326 elif hunk.strip():
bos@71 327 # it's something we should execute
bos@173 328 newps, output = self.sendreceive(hunk, read_hint)
bos@168 329 if not ofp:
bos@71 330 continue
bos@71 331 # first, print the command we ran
bos@71 332 if not hunk.startswith('#'):
bos@71 333 nl = hunk.endswith('\n')
bos@564 334 hunk = ('<prompt>%s</prompt> <userinput>%s</userinput>' %
bos@103 335 (prompts[ps],
bos@564 336 xml_escape(hunk.rstrip('\n'))))
bos@71 337 if nl: hunk += '\n'
bos@71 338 ofp.write(hunk)
bos@71 339 # then its output
bos@564 340 ofp.write(xml_escape(output))
bos@103 341 ps = newps
bos@71 342 self.status('\n')
bos@71 343 except:
bos@72 344 print >> sys.stderr, '(killed)'
bos@79 345 os.kill(self.pid, signal.SIGKILL)
bos@72 346 pid, rc = os.wait()
bos@71 347 raise
bos@72 348 else:
bos@71 349 try:
bos@173 350 ps, output = self.sendreceive('exit\n', read_hint)
bos@138 351 if ofp is not None:
bos@71 352 ofp.write(output)
bos@564 353 ofp.write('</screen>\n')
bos@138 354 ofp.close()
bos@160 355 err |= self.rename_output(ofp_basename, ignore)
bos@73 356 os.close(self.cfd)
bos@71 357 except IOError:
bos@71 358 pass
bos@79 359 os.kill(self.pid, signal.SIGTERM)
bos@72 360 pid, rc = os.wait()
bos@160 361 err = err or rc
bos@160 362 if err:
bos@72 363 if os.WIFEXITED(rc):
bos@72 364 print >> sys.stderr, '(exit %s)' % os.WEXITSTATUS(rc)
bos@72 365 elif os.WIFSIGNALED(rc):
bos@72 366 print >> sys.stderr, '(signal %s)' % os.WTERMSIG(rc)
bos@136 367 else:
bos@579 368 wopen(result_name(self.name + '.run'))
bos@160 369 return err
bos@72 370 finally:
bos@4 371 shutil.rmtree(tmpdir)
bos@3 372
bos@258 373 def print_help(exit, msg=None):
bos@258 374 if msg:
bos@258 375 print >> sys.stderr, 'Error:', msg
bos@258 376 print >> sys.stderr, 'Usage: run-example [options] [test...]'
bos@258 377 print >> sys.stderr, 'Options:'
bos@565 378 print >> sys.stderr, ' -a --all run all examples in this directory'
bos@258 379 print >> sys.stderr, ' -h --help print this help message'
bos@545 380 print >> sys.stderr, ' --help keep new output as desired output'
bos@258 381 print >> sys.stderr, ' -v --verbose display extra debug output'
bos@258 382 sys.exit(exit)
bos@258 383
bos@3 384 def main(path='.'):
bos@566 385 if os.path.realpath(path).split(os.sep)[-1] != 'examples':
bos@566 386 print >> sys.stderr, 'Not being run from the examples directory!'
bos@566 387 sys.exit(1)
bos@566 388
bos@258 389 opts, args = getopt.getopt(sys.argv[1:], '?ahv',
bos@545 390 ['all', 'help', 'keep', 'verbose'])
bos@78 391 verbose = False
bos@258 392 run_all = False
bos@545 393 keep_change = False
bos@566 394
bos@78 395 for o, a in opts:
bos@258 396 if o in ('-h', '-?', '--help'):
bos@258 397 print_help(0)
bos@258 398 if o in ('-a', '--all'):
bos@258 399 run_all = True
bos@545 400 if o in ('--keep',):
bos@545 401 keep_change = True
bos@78 402 if o in ('-v', '--verbose'):
bos@78 403 verbose = True
bos@71 404 errs = 0
bos@3 405 if args:
bos@3 406 for a in args:
bos@75 407 try:
bos@75 408 st = os.lstat(a)
bos@75 409 except OSError, err:
bos@75 410 print >> sys.stderr, '%s: %s' % (a, err.strerror)
bos@75 411 errs += 1
bos@75 412 continue
bos@579 413 if stat.S_ISREG(st.st_mode):
bos@579 414 if st.st_mode & 0111:
bos@579 415 if shell_example(a, verbose, keep_change).run():
bos@579 416 errs += 1
bos@579 417 elif a.endswith('.lst'):
bos@579 418 static_example(a, verbose, keep_change).run()
bos@75 419 else:
bos@75 420 print >> sys.stderr, '%s: not a file, or not executable' % a
bos@71 421 errs += 1
bos@258 422 elif run_all:
bos@579 423 names = glob.glob("*") + glob.glob("app*/*") + glob.glob("ch*/*")
bos@258 424 names.sort()
bos@258 425 for name in names:
bos@579 426 if name == 'run-example' or name.endswith('~'): continue
bos@258 427 pathname = os.path.join(path, name)
bos@258 428 try:
bos@258 429 st = os.lstat(pathname)
bos@258 430 except OSError, err:
bos@258 431 # could be an output file that was removed while we ran
bos@258 432 if err.errno != errno.ENOENT:
bos@258 433 raise
bos@258 434 continue
bos@579 435 if stat.S_ISREG(st.st_mode):
bos@579 436 if st.st_mode & 0111:
bos@579 437 if shell_example(pathname, verbose, keep_change).run():
bos@579 438 errs += 1
bos@579 439 elif pathname.endswith('.lst'):
bos@579 440 static_example(pathname, verbose, keep_change).run()
bos@579 441 print >> wopen(os.path.join(path, '.run')), time.asctime()
bos@258 442 else:
bos@258 443 print_help(1, msg='no test names given, and --all not provided')
bos@566 444
bos@579 445 fp = wopen('auto-snippets.xml')
bos@566 446 for key in sorted(example.entities.iterkeys()):
bos@566 447 print >> fp, key
bos@566 448 fp.close()
bos@71 449 return errs
bos@3 450
bos@3 451 if __name__ == '__main__':
bos@258 452 try:
bos@258 453 sys.exit(main())
bos@258 454 except KeyboardInterrupt:
bos@258 455 print >> sys.stderr, 'interrupted!'
bos@258 456 sys.exit(1)