hgbook

annotate en/examples/run-example @ 580:8366882f67f2

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