3 # adt-run is part of autopkgtest
4 # autopkgtest is a tool for testing Debian binary packages
6 # autopkgtest is Copyright (C) 2006 Canonical Ltd.
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 # See the file CREDITS for a full list of credits information (often
23 # installed as /usr/share/doc/autopkgtest/CREDITS).
39 from optparse import OptionParser
40 signal.signal(signal.SIGINT, signal.SIG_DFL) # undo stupid Python SIGINT thing
42 #---------- global variables
44 tmpdir = None # pathstring on host
45 testbed = None # Testbed
46 errorcode = 0 # exit status that we are going to use
47 binaries = None # Binaries (.debs we have registered)
49 #---------- errors we define
52 def __init__(q,ec,m): q.ec = ec; q.m = m
55 print >>sys.stderr, se
56 raise Quit(20, "unexpected error: %s" % m)
59 print >>sys.stderr, se
60 print 'blame: ', ' '.join(testbed.blamed)
61 raise Quit(12, "erroneous package: %s" % m)
63 def report(tname, result): print '%-20s %s' % (tname, result)
66 def __init__(u, lno, m):
67 if lno >= 0: u.m = '%s (control line %d)' % (m, lno)
72 report(tname, 'SKIP %s' % u.m)
76 if not opts.debug: return
77 print >>sys.stderr, 'atd-run: debug:', m
80 return reduce((lambda a,b: a + b), l, [])
82 #---------- fancy automatic file-copying class
86 # p.path[tb] None or path not None => path known
87 # p.file[tb] None or path not None => file exists
88 # p.spec string or not set
89 # p.spec_tbp True or False, or not set
92 def __init__(p, what):
101 if p.path[tbp] is None: out += '-'
102 elif p.file[tbp] is None: out += '?'+p.path[tbp]
103 else: out += '!'+p.path[tbp]
108 if p.has_key('spec'):
109 if p.spec_tb: out += '<'
116 if p.has_key('spec'): xtra = ' spec[%s]=%s' % (p.spec, p.spec_tb)
117 error "internal error: %s (%s)" % (how, p.__str__())
119 def _ensure_path(p, tbp):
120 if p.path[tbp] is None:
122 p.path[tbp] = tmpdir+'/'+what
124 p.path[tbp] = testbed.scratch.path[True]+'/'+what
126 def write(p, tbp=False):
129 if p.dir and not p.file[tbp]:
131 try: os.mkdir(p.path[tbp])
132 except IOError, oe: if oe.errno != errno.EEXIST: raise
135 'test -d "$1" || mkdir "$1"',
137 tf_what = urllib.quote(p.what).replace('/',' ')
138 (rc,se) = testbed.execute('mkdir-'+tf_what, cmdl)
139 if rc: bomb('failed to create directory %s' %
142 p.file[tbp] = p.path[tbp]
145 def read(p, tbp=False):
146 if p.file[not tbp] is None: p._wrong("requesting read but nonexistent")
149 if p.file[tbp] is None:
150 cud = ['copyup','copydown'][tbp]
151 src = p.file[not tbp] + p.dir
152 dst = p.file[tbp] + p.dir
153 testbed.command(cud, (src, dst))
157 def subpath(p, what, leaf, constructor):
158 if not p.dir: p._wrong("creating subpath of non-directory")
159 return constructor(what, p.spec+p.dir+leaf, p.spec_tbp)
160 def sibling(p, what, leaf, constructor):
161 dir = os.path.dirname(p.spec)
163 return constructor(what, dir+leaf, p.spec_tbp)
165 def invalidate(p, tbp=False):
169 for tbp in [False,True]:
170 for pf in [t.path, t.file]:
171 if pf[tbp] is None: continue
172 if not pf[tbp]: bomb('empty path specified for '+p.what)
173 if p.dir and pf[tbp].endswith('/'):
174 pf[tbp] = pf[tbp].rstrip('/')
175 if not pf[tbp]: pf[tbp] = '/'
176 if not p.dir and pf[tbp].endswith('/'):
177 bomb("directory `%s' specified for "
178 "non-directory %s" % (pf[tbp], p.what))
180 class InputFile(Path):
181 def __init__(p, what, spec, spec_tbp=False):
182 AutoFile.__init__(p, what)
184 p.spec_tbp = spec_tbp
185 p.path[spec_tbp] = p.file[spec_tbp] = spec
188 class InputDir(Path):
189 def __init__(p, what, spec, spec_tbp=False):
190 InputFile.__init__(p,what,spec,spec_tbp)
194 class OutputFile(Path):
195 def __init__(p, what, spec, spec_tbp=False):
196 AutoFile.__init__(p, what)
198 p.spec_tbp = spec_tbp
199 p.path[spec_tbp] = spec
202 class OutputDir(Path):
203 def __init__(p, what, spec, spec_tbp=False):
204 OutputFile.__init__(p,what,spec,spec_tbp)
208 class TemporaryFile(Path):
209 def __init__(p, what):
210 AutoFile.__init__(p, what)
212 #---------- parsing and representation of the arguments
215 def __init__(a, kind, af, arghandling, what):
216 # extra attributes get added during processing
224 usage = "%prog <options> -- <virt-server>..."
225 parser = OptionParser(usage=usage)
226 pa = parser.add_option
227 pe = parser.add_option
232 'deb_forbuilds': 'auto',
233 'deb_fortests': 'auto',
235 'override_control': None
237 initial_arghandling = arghandling.copy()
241 # actions (ie, test sets to run, sources to build, binaries to use):
243 def cb_action(op,optstr,value,parser, long,kindpath,is_act):
244 parser.largs.append((value,kindpath))
247 def pa_action(long, metavar, kindpath, help, is_act=True):
248 pa('','--'+long, action='callback', callback=cb_action,
249 nargs=1, type='string',
250 callback_args=(long,kindpath,is_act), help=help)
252 pa_action('build-tree', 'TREE', '@/',
253 help='run tests from build tree TREE')
255 pa_action('source', 'DSC', '@.dsc',
256 help='build DSC and use its tests and/or'
257 ' generated binary packages')
259 pa_action('binary', 'DEB', '@.deb',
260 help='use binary package DEB according'
261 ' to most recent --binaries-* settings')
263 pa_action('override-control', 'CONTROL', ('control',), is_act=0,
264 help='run tests from control file CONTROL instead,
265 ' (applies to next test suite only)')
268 # argument handling settings (what ways to use action
269 # arguments, and pathname processing):
271 def cb_setah(option, opt_str, value, parser, toset,setval):
272 if type(setval) == list:
273 if not value in setval:
274 parser.error('value for %s option (%s) is not '
275 'one of the permitted values (%s)' %
276 (value, opt_str, setval.join(' ')))
277 elif setval is not None:
280 arghandling[v] = value
281 parser.largs.append(arghandling.copy())
283 def pa_setah(long, affected,effect, **kwargs):
284 type = metavar; if type: type = 'string'
285 pa('',long, action='callback', callback=cb_setah,
286 callback_args=(affected,effect), **kwargs)
287 ' according to most recent --binaries-* settings')
289 #---- paths: host or testbed:
291 pa_setah('--paths-testbed', ['tb'],True,
292 help='subsequent path specifications refer to the testbed')
293 pa_setah('--paths-host', ['tb'],False,
294 help='subsequent path specifications refer to the host')
296 #---- source processing settings:
298 pa_setah('--sources-tests', ['dsc_tests'],True,
299 help='run tests from builds of subsequent sources')
300 pa_setah('--sources-no-tests', ['dsc_tests'],False,
301 help='do not run tests from builds of subsequent sources')
303 pa_setah('--built-binaries-filter', ['dsc_filter'],None,
304 type=string, metavar='PATTERN-LIST',
305 help='from subsequent sources, use binaries matching'
306 ' PATTERN-LIST (comma-separated glob patterns)'
307 ' according to most recent --binaries-* settings')
308 pa_setah('--no-built-binaries', ['dsc_filter'], '_',
309 help='from subsequent sources, do not use any binaries')
311 #---- binary package processing settings:
313 def pa_setahbins(long,toset,how):
314 pa_setah(long, toset,['ignore','auto','install'],
315 type=string, metavar='IGNORE|AUTO|INSTALL', default='auto',
316 help=how+' ignore binaries, install them as needed'
317 ' for dependencies, or unconditionally install'
318 ' them, respectively')
319 pa_setahbins('--binaries', ['deb_forbuilds','deb_fortests'], '')
320 pa_setahbins('--binaries-forbuilds', ['deb_forbuilds'], 'for builds, ')
321 pa_setahbins('--binaries-fortests', ['deb_fortests'], 'for tests, ')
326 def cb_vserv(op,optstr,value,parser):
327 parser.values.vserver = list(parser.rargs)
330 def cb_path(op,optstr,value,parser, constructor,long,dir):
331 name = long.replace('-','_')
332 af = constructor(arghandling['tb'], value, long, dir)
333 setattr(parser.values, name, af)
335 def pa_path(long, constructor, help, dir=False):
336 pa('','--'+long, action='callback', callback=cb_path,
337 callback_args=(constructor,long,dir),
338 nargs=1, type='string',
339 help=help, metavar='PATH')
341 pa_path('output-dir', OutputDir, dir=True,
342 help='write stderr/out files in PATH')
344 pa('','--tmp-dir', type='string', dest='tmpdir',
345 help='write temporary files to TMPDIR, emptying it'
346 ' beforehand and leaving it behind at the end')
348 pa('','--user', type='string', dest='user',
349 help='run tests as USER (needs root on testbed)')
350 pa('','--gain-root', type='string', dest='gainroot',
351 help='prefix debian/rules binary with GAINROOT')
352 pa('-d', '--debug', action='store_true', dest='debug');
353 pa('','--gnupg-home', type='string', dest='gnupghome',
354 default='~/.autopkgtest/gpg',
355 help='use GNUPGHOME rather than ~/.autopkgtest (for
356 " signing private apt archive);"
357 " `fresh' means generate new key each time.")
362 class SpecialOption(optparse.Option): pass
363 vs_op = SpecialOption('','--VSERVER-DUMMY')
364 vs_op.action = 'callback'
368 vs_op.callback = cb_vserv
369 vs_op.callback_args = ( )
370 vs_op.callback_kwargs = { }
371 vs_op.help = 'introduces virtualisation server and args'
372 vs_op._short_opts = []
373 vs_op._long_opts = ['---']
377 (opts,args) = parser.parse_args()
378 if not hasattr(opts,'vserver'):
379 parser.error('you must specifiy --- <virt-server>...')
381 parser.error('nothing to do specified')
383 arghandling = initial_arghandling
387 if type(act) == dict:
390 elif type(act) == tuple:
392 elif type(act) == string:
395 error "unknown action in list `%s' having"
396 "type `%s' % (act, type(act))
397 (pathstr, kindpath) = act
399 constructor = InputPath
400 if type(kindpath) is tuple: kind = kindpath[0]
401 elif kindpath.endswith('.deb'): kind = 'deb'
402 elif kindpath.endswith('.dsc'): kind = 'dsc'
403 elif kindpath.endswith('/'):
405 constructor = InputPathDir
406 else: parser.error("do not know how to handle filename \`%s';"
407 " specify --source --binary or --build-tree")
409 what = '%s%s' % (kind,ix); ix++
411 af = constructor(what+'-'+kind, pathstr, arghandling['tb'])
412 opts.actions.append(Action(kind, af, arghandling, what))
414 def finalise_options():
417 if opts.user is None and 'root-on-testbed' not in tb.caps:
420 if opts.user is None:
421 su = 'suggested-normal-user='
433 if 'root-on-testbed' not in tb.caps:
434 print >>sys.stderr, "warning: virtualisation"
435 " system does not offer root on testbed,"
436 " but --user option specified: failure likely"
437 opts.user_wrap = lambda x: 'su %s -c "%s"' % (opts.user, x)
439 opts.user_wrap = lambda x: x
441 if opts.gainroot is None:
444 'root-on-testbed' not in tb.caps:
445 opts.gainroot = 'fakeroot'
447 if opts.gnupghome.startswith('~/'):
448 try: home = os.environ['HOME']
450 parser.error("HOME environment variable"
451 " not set, needed for --gnupghome=`%s"
453 opts.gnupghome = home + opts.gnupghome[1:]
454 elif opts.gnupghome == 'fresh':
455 opts.gnupghome = None
457 #---------- testbed management - the Testbed class
468 tb.sp = subprocess.Popen(opts.vserver,
469 stdin=p, stdout=p, stderr=None)
471 tb.caps = tb.commandr('capabilities')
474 if tb.sp is None: return
475 ec = tb.sp.returncode
482 tb.bomb('testbed gave exit status %d after quit' % ec)
484 if tb.scratch is not None: return
485 pl = tb.commandr('open')
486 tb.scratch = OutputDir('tb-scratch', pl[0], True)
488 if tb.scratch is None: return
490 if tb.sp is None: return
493 if tb.modified and 'reset' in tb.caps:
497 binaries.publish(act)
503 if tb.sp is not None:
507 if ec: print >>sys.stderr, ('adt-run: testbed failing,'
508 ' exit status %d' % ec)
510 raise Quit(16, 'testbed failed: %s' % m)
511 def send(tb, string):
515 print >>tb.sp.stdin, string
519 (type, value, dummy) = sys.exc_info()
520 tb.bomb('cannot send to testbed: %s' % traceback.
521 format_exception_only(type, value))
522 def expect(tb, keyword, nresults=-1):
523 l = tb.sp.stdout.readline()
524 if not l: tb.bomb('unexpected eof from the testbed')
525 if not l.endswith('\n'): tb.bomb('unterminated line from the testbed')
529 if not ll: tb.bomb('unexpected whitespace-only line from the testbed')
531 if tb.lastsend is None:
532 tb.bomb("got banner `%s', expected `%s...'" %
535 tb.bomb("sent `%s', got `%s', expected `%s...'" %
536 (tb.lastsend, l, keyword))
538 if nresults >= 0 and len(ll) != nresults:
539 tb.bomb("sent `%s', got `%s' (%d result parameters),"
540 " expected %d result parameters" %
541 (string, l, len(ll), nresults))
543 def commandr(tb, cmd, nresults, args=()):
544 if type(cmd) is str: cmd = [cmd]
545 al = cmd + map(urllib.quote, args)
546 tb.send(string.join(al))
547 ll = tb.expect('ok', nresults)
548 rl = map(urllib.unquote, ll)
550 def command(tb, cmd, args=()):
551 tb.commandr(cmd, 0, args)
552 def commandr1(tb, cmd, args=()):
553 rl = tb.commandr(cmd, 1, args)
555 def execute(tb, what, cmdargs,
556 si='/dev/null', so='/dev/null', se=None, cwd=None)
557 if cwd is None: cwd = tb.tbscratch.write(True)
560 se_use = TemporaryFile('xerr-'+what).write(True)
561 rc = tb.commandr1(['execute',
562 ','.join(map(urllib.quote, cmdargs))],
565 except ValueError: bomb("execute for %s gave invalid response `%s'"
567 if se is not None: return rc
568 return (rc, file(se.read()).read())
570 #---------- representation of test control files: Field*, Test, etc.
573 def __init__(f, fname, stz, base, tnames, vl):
583 r = map((lambda w: (lno, w)), r)
585 return flatten(map(distribute, f.vl))
590 raise Unsupported(f.vl[1][0],
591 'only one %s field allowed' % fn)
594 class FieldIgnore(FieldBase):
598 def __init__(r,rname,base): pass
600 class Restriction_rw_tests_tree(Restriction): pass
601 class Restriction_breaks_testbed(Restriction):
602 if 'reset' not in tb.caps:
603 raise Unsupported(f.lno,
604 'Test breaks testbed but testbed cannot reset')
606 class Field_Restrictions(FieldBase):
608 for wle in f.words():
610 rname = rname.replace('-','_')
611 try: rclass = globals()['Restriction_'+rname]
612 except KeyError: raise Unsupported(lno,
613 'unknown restriction %s' % rname)
614 r = rclass(rname, f.base)
615 f.base['restrictions'].append(r)
617 class Field_Tests(FieldIgnore): pass
619 class Field_Tests_directory(FieldBase):
622 if td.startswith('/'): raise Unspported(f.lno,
623 'Tests-Directory may not be absolute')
624 base['testsdir'] = td
626 def run_tests(stanzas):
628 for stanza in stanzas:
629 tests = stanza[' tests']
631 report('*', 'SKIP no tests in this package')
636 if 'breaks-testbed' in t.restrictions:
637 testbed.needs_reset()
638 testbed.needs_reset()
641 def __init__(t, tname, base, act_what):
642 if '/' in tname: raise Unsupported(base[' lno'],
643 'test name may not contain / character')
644 for k in base: setattr(t,k,base[k])
646 t.what = act_what+'-'+tname
647 if len(base['testsdir']): tpath = base['testsdir'] + '/' + tname
649 t.af = opts.tests_tree.subpath('test-'+tname, tpath, InputFile)
652 def reportfail(t, m):
655 report(t.what, 'FAIL ' + m)
658 idstr = oe + '-' + t.what
659 if opts.output_dir is not None and opts.output_dir.tb:
660 use_dir = opts.output_dir
662 use_dir = testbed.scratch
663 return use_dir.subpath(idstr, idstr, OutputFile)
665 so = stdouterr('stdout')
666 se = stdouterr('stderr')
667 rc = testbed.execute('test-'+t.what,
668 [opts.user_wrap(t.af.read(True))],
669 so=so, se=se, cwd=opts.tests_tree.write(True))
671 stab = os.stat(se.read())
672 if stab.st_size != 0:
673 l = file(se.read()).readline()
674 l = l.rstrip('\n \t\r')
675 if len(l) > 40: l = l[:40] + '...'
676 t.reportfail('status: %d, stderr: %s' % (rc, l))
678 t.reportfail('non-zero exit status %d' % rc)
682 def read_control(act, tree, control_override):
685 if control_override is not None:
686 control_af = control_override
687 testbed.blame('arg:'+control_override.spec)
689 control_af = tree.subpath(act.what+'-testcontrol',
690 'debian/tests/control', InputFile)
693 control = file(control_af.read(), 'r')
695 if oe[0] != errno.ENOENT: raise
699 def badctrl(m): act.bomb('tests/control line %d: %s' % (lno, m))
700 stz = None # stz[field_name][index] = (lno, value)
701 # special field names:
702 # stz[' lno'] = number
703 # stz[' tests'] = list of Test objects
705 if stz is None: return
711 initre = regexp.compile('([A-Z][-0-9a-z]*)\s*\:\s*(.*)$')
713 l = control.readline()
716 if not l.endswith('\n'): badctrl('unterminated line')
717 if regexp.compile('\s*\#').match(l): continue
718 if not regexp.compile('\S').match(l): end_stanza(stz); continue
719 initmat = initre.match(l)
721 (fname, l) = initmat.groups()
722 fname = string.capwords(fname)
724 stz = { ' lno': lno, ' tests': [] }
725 if not stz.has_key(fname): stz[fname] = [ ]
726 hcurrent = stz[fname]
727 elif regexp.compile('\s').match(l):
728 if not hcurrent: badctrl('unexpected continuation')
730 badctrl('syntax error')
731 hcurrent.append((lno, l))
734 def testbadctrl(stz, lno, m):
735 report_badctrl(lno, m)
740 try: tnames = stz['Tests']
743 raise Unsupported(stz[' lno'],
745 tnames = map((lambda lt: lt[1]), tnames)
746 tnames = string.join(tnames).split()
749 'testsdir': 'debian/tests'
751 for fname in stz.keys():
752 if fname.startswith(' '): continue
754 try: fclass = globals()['Field_'+
755 fname.replace('-','_')]
756 except KeyError: raise Unsupported(vl[0][0],
757 'unknown metadata field %s' % fname)
758 f = fclass(stz, fname, base, tnames, vl)
761 t = Test(tname, base, act.what)
762 stz[' tests'].append(t)
763 except Unsupported, u:
764 for tname in tnames: u.report(tname)
769 def print_exception(ei, msgprefix=''):
770 if msgprefix: print >>sys.stderr, msgprefix
773 print >>sys.stderr, 'adt-run:', q.m
776 print >>sys.stderr, "adt-run: unexpected, exceptional, error:"
777 traceback.print_exc()
783 if tmpdir is not None:
784 shutil.rmtree(tmpdir)
785 if testbed is not None:
787 if rm_ec: bomb('rm -rf -- %s failed, code %d' % (tmpdir, ec))
789 print_exception(sys.exc_info(),
790 '\nadt-run: error cleaning up:\n')
793 #---------- registration, installation etc. of .deb's: Binaries
795 def determine_package(act):
796 cmd = 'dpkg-deb --info --'.split(' ')+[act.af.read(),'control']
797 running = Popen(cmd, stdout=PIPE)
798 output = running.communicate()[0]
800 if rc: badpkg('failed to parse binary package, code %d' % rc)
801 re = regexp.compile('^\s*Package\s*:\s*([0-9a-z][-+.0-9a-z]*)\s*$')
803 for l in '\n'.split(output):
806 if act.pkg: badpkg('two Package: lines in control file')
808 if not act.pkg: badpkg('no good Package: line in control file')
812 b.dir = TemporaryDir('binaries')
814 if opts.gnupghome is None:
815 opts.gnupghome = tmpdir+'/gnupg'
818 for x in ['pubring','secring']:
819 os.stat(opts.gnupghome + '/' + x + '.gpg')
821 if oe.errno != errno.ENOENT: raise
823 try: os.mkdir(opts.gnupghome, 0700)
824 except IOError, oe: if oe.errno != errno.EEXIST: raise
827 exec >key-gen-log 2>&1
828 cat <<"END" >key-gen-params
832 Name-Real: autopkgtest per-run key
833 Name-Comment: do not trust this key
834 Name-Email: autopkgtest@example.com
837 gpg --homedir="$1" --batch --gen-key key-gen-params
839 cmdl = ['sh','-ec',script,'x',opts.gnupghome]
840 rc = subprocess.call(cmdl)
843 f = open(opts.gnupghome+'/key-gen-log')
845 except IOError, e: tp = e
846 print >>sys.stderr, tp
847 bomb('key generation failed, code %d' % rc)
850 shutil.rmtree(b.dir.read())
855 def register(b, act, pkg, af, forwhat, blamed):
856 if act.ah['deb_'+forwhat] == 'ignore': return
858 b.blamed += testbed.blamed
860 leafname = pkg+'.deb'
861 dest = b.dir.subpath('binaries--'+leafname, leafname, OutputFile)
863 try: os.remove(dest.write())
865 if oe.errno != errno.ENOENT: raise e
867 try: os.link(af.read(), dest.write())
869 if oe.errno != errno.EXDEV: raise e
870 shutil.copy(af.read(), dest)
872 if act.ah['deb_'+forwhat] == 'install':
873 b.install.append(pkg)
878 apt-ftparchive packages . >Packages
880 apt-ftparchive release . >Release
881 gpg --homedir="$2" --batch --detach-sign --armour -o Release.gpg Release
882 gpg --homedir="$2" --batch --export >archive-key.pgp
884 cmdl = ['sh','-ec',script,'x',b.dir.write(),opts.gnupghome]
885 rc = subprocess.call(cmd)
886 if rc: bomb('apt-ftparchive or signature failed, code %d' % rc)
888 b.dir.invalidate(True)
889 apt_source = b.dir.read(True)
892 apt-key add archive-key.pgp
893 echo "deb file:///'+apt_source+'/ /" >/etc/apt/sources.list.d/autopkgtest
895 (rc,se) = testbed.execute('aptkey-'+what, ['sh','-ec','script'], b.dir)
896 if rc: bomb('apt setup failed with exit code %d' % rc, se)
898 testbed.blamed += b.blamed
900 for pkg in b.install:
902 (rc,se) = testbed.execute('install-%s'+act.what,
903 ['apt-get','-qy','install',pkg])
904 if rc: badpkg("installation of %s failed, exit code %d"
907 #---------- processing of sources (building)
909 def source_rules_command(act,script,which,work,results_lines=0):
910 script = "exec 3>&1 >&2\n" + '\n'.join(script)
911 so = TemporaryFile('%s-%s-results' % (what,which))
912 se = TemporaryFile('%s-%s-log' & (what,which))
913 rc = testbed.execute('%s-%s' % (what,which),
914 ['sh','-xec',script],
915 so=so, se=se, cwd= work.write(True))
916 results = file(so.read()).read().split("\n")
917 if rc: badpkg_se("%s failed with exit code %d" % (which,rc), se)
918 if results_lines is not None and len(results) != results_lines:
919 badpkg_se("got %d lines of results from %s where %d expected"
920 % (len(results), which, results_lines), se)
921 if results_lines==1: return results[0]
924 def build_source(act):
925 act.blame = 'arg:'+act.af.spec()
926 testbed.blame(act.blame)
927 testbed.needs_reset()
929 what = act.ah['what']
932 dsc_what = what+'/'+basename
934 dsc_file = open(dsc.read())
936 fre = regexp.compile('^\s+[0-9a-f]+\s+\d+\s+([^/.][^/]*)$')
938 if l.startswith('Files:'): in_files = True
939 elif l.startswith('#'): pass
940 elif not l.startswith(' '):
942 if l.startswith('Source:'):
943 act.blame = 'dsc:'+l[7:].strip()
944 testbed.blame(act.blame)
945 elif not in_files: pass
948 if not m: badpkg(".dsc contains unparseable line"
949 " in Files: `%s'" % (`dsc`,l))
950 subfile = dsc.sibling(
951 dsc_what+'/'+m.groups(0), m.groups(0),
956 work = TemporaryDir(what+'-build')
959 'cd '+work.write(True),
960 'gdebi '+dsc.read(True),
961 'dpkg-source -x '+dsc.read(True),
964 opts.user_wrap('debian/rules build'),
966 result_pwd = source_rules_command(act,script,what,'build',work,1)
968 if os.path.dirname(result_pwd) != work.read(True):
969 badpkg_se("results dir `%s' is not in expected parent dir `%s'"
970 % (results[0], work.read(True)), se)
972 act.tests_tree = InputDir(dsc_what+'tests-tree',
973 work.read(True)+os.path.basename(results[0]),
975 if act.ah['dsc_tests']:
976 act.tests_tree.read()
977 act.tests_tree.invalidate(True)
979 act.blamed = testbed.blamed.copy()
982 if act.ah['dsc_filter'] != '_':
984 'cd '+work.write(True)+'/*/.',
985 opts.user_wrap(opts.gainroot+' debian/rules binary'),
989 result_debs = source_rules_command(act,script,what,
990 'debian/rules binary',work,1)
991 if result_debs == '*': debs = []
992 else: debs = debs.split(' ')
993 re = regexp.compile('^([-+.0-9a-z]+)_[^_/]+(?:_[^_/]+)\.deb$')
996 if not m: badpkg("badly-named binary `%s'" % deb)
998 for pat in act.ah['dsc_filter'].split(','):
999 if fnmatch.fnmatchcase(pkg,pat):
1000 deb_af = work.read()+'/'+deb
1001 deb_what = pkg+'_'+what+'.deb'
1002 bin = InputFile(deb_what,deb_af,True)
1004 binaries.register(act,pkg,bin,'builds',
1006 act.binaries.subpath((pkg,bin))
1009 #---------- main processing loop and main program
1011 def process_actions():
1015 binaries = Binaries()
1018 for act in opts.actions:
1020 if act.kind == 'deb':
1021 blame('arg:'+act.af.spec)
1022 determine_package(act)
1023 blame('deb:'+act.pkg)
1024 binaries.register(act,act.pkg,act.af,'builds',
1026 if act.kind == 'dsc':
1030 control_override = None
1031 for act in opts.actions:
1033 if act.kind == 'control':
1034 control_override = act.af
1035 if act.kind == 'deb':
1036 binaries.register(act,act.pkg,act.af,'tests',
1038 if act.kind == 'dsc':
1039 for (pkg,bin) in act.binaries:
1040 binaries.register(act,pkg,bin,'tests',
1042 if act.ah['dsc_tests']:
1043 stanzas = read_control(act, act.tests_tree,
1045 testbed.blamed += act.blamed
1046 run_tests(act, stanzas)
1047 control_override = None
1048 if act.kind == 'tree':
1049 testbed.blame('arg:'+act.af.spec)
1050 stanzas = read_control(act, act.af,
1052 run_tests(act, stanzas)
1053 control_override = None
1060 except SystemExit, se:
1063 tmpdir = tempfile.mkdtemp()
1069 ec = print_exception(sys.exc_info(), '')