hgbook

annotate en/examples/run-example @ 545:d8913b7869b5

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