code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
import sys
import os
import time
import shutil
import subprocess
import django
from django.utils.translation import ugettext as _
import forms
import models
import viewlib
import botslib
import pluglib
import botsglobal
import glob
from botsconfig import *
def server_error(request, template_name='500.html'):
""" the 500 error handler.
Templates: `500.html`
Context: None
"""
import traceback
exc_info = traceback.format_exc(None).decode('utf-8','ignore')
botsglobal.logger.info(_(u'Ran into server error: "%s"'),str(exc_info))
t = django.template.loader.get_template(template_name) # You need to create a 500.html template.
return django.http.HttpResponseServerError(t.render(django.template.Context({'exc_info':exc_info})))
def index(request,*kw,**kwargs):
return django.shortcuts.render_to_response('admin/base.html', {},context_instance=django.template.RequestContext(request))
def home(request,*kw,**kwargs):
return django.shortcuts.render_to_response('bots/about.html', {'botsinfo':botslib.botsinfo()},context_instance=django.template.RequestContext(request))
def reports(request,*kw,**kwargs):
#~ print 'reports received',kw,kwargs,request.POST,request.GET
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectReports()
return viewlib.render(request,formout)
else: #via menu, go to view form
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectReports(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewReports(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
if '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectReports(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'report2incoming' in request.POST: #coming from ViewIncoming, go to incoming
request.POST = viewlib.preparereport2view(request.POST,int(request.POST['report2incoming']))
return incoming(request)
elif 'report2outgoing' in request.POST: #coming from ViewIncoming, go to incoming
request.POST = viewlib.preparereport2view(request.POST,int(request.POST['report2outgoing']))
return outgoing(request)
elif 'report2process' in request.POST: #coming from ViewIncoming, go to incoming
request.POST = viewlib.preparereport2view(request.POST,int(request.POST['report2process']))
return process(request)
elif 'report2errors' in request.POST: #coming from ViewIncoming, go to incoming
newpost = viewlib.preparereport2view(request.POST,int(request.POST['report2errors']))
newpost['statust'] = ERROR
request.POST = newpost
return incoming(request)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.report.objects.all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewReports(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def incoming(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectIncoming()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2outgoing' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='in2out')
return outgoing(request)
elif '2process' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='2process')
return process(request)
elif '2confirm' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='in2confirm')
return process(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectIncoming(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else: #coming from ViewIncoming
formin = forms.ViewIncoming(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #go to select form using same criteria
formout = forms.SelectIncoming(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'retransmit' in request.POST: #coming from ViewIncoming
idta,reportidta = request.POST[u'retransmit'].split('-')
filereport = models.filereport.objects.get(idta=int(idta),reportidta=int(reportidta))
filereport.retransmit = not filereport.retransmit
filereport.save()
elif 'delete' in request.POST: #coming from ViewIncoming
idta = int(request.POST[u'delete'])
#~ query = models.filereport.objects.filter(idta=int(idta)).all().delete()
models.filereport.objects.filter(idta=idta).delete()
ta = models.ta.objects.get(idta=idta)
viewlib.gettrace(ta)
viewlib.trace2delete(ta)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.filereport.objects.all()
pquery = viewlib.filterquery(query,cleaned_data,incoming=True)
formout = forms.ViewIncoming(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def outgoing(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectOutgoing()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2incoming' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='out2in')
return incoming(request)
elif '2process' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='2process')
return process(request)
elif '2confirm' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='out2confirm')
return process(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectOutgoing(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewOutgoing(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectOutgoing(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'retransmit' in request.POST: #coming from ViewIncoming
ta = models.ta.objects.get(idta=int(request.POST[u'retransmit']))
ta.retransmit = not ta.retransmit
ta.save()
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(status=EXTERNOUT,statust=DONE).all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewOutgoing(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def document(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectDocument()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'idta','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'idta','sortedasc':False}
else: # request.method == 'POST'
if 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectDocument(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewDocument(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectDocument(formin.cleaned_data)
return viewlib.render(request,formout)
elif 'retransmit' in request.POST: #coming from Documents, no reportidta
idta = request.POST[u'retransmit']
filereport = models.filereport.objects.get(idta=int(idta),statust=DONE)
filereport.retransmit = not filereport.retransmit
filereport.save()
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(django.db.models.Q(status=SPLITUP)|django.db.models.Q(status=TRANSLATED)).all()
pquery = viewlib.filterquery(query,cleaned_data)
viewlib.trace_document(pquery)
formout = forms.ViewDocument(initial=cleaned_data)
#~ from django.db import connections
#~ print django.db.connection.queries
return viewlib.render(request,formout,pquery)
def process(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectProcess()
return viewlib.render(request,formout)
elif 'all' in request.GET: #via menu, go to all runs
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'lastrun':True,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2incoming' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='fromprocess')
return incoming(request)
elif '2outgoing' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='fromprocess')
return outgoing(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectProcess(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
if 'retry' in request.POST:
idta = request.POST[u'retry']
ta = models.ta.objects.get(idta=int(idta))
ta.retransmit = not ta.retransmit
ta.save()
formin = forms.ViewProcess(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectProcess(formin.cleaned_data)
return viewlib.render(request,formout)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(status=PROCESS,statust=ERROR).all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewProcess(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def detail(request,*kw,**kwargs):
''' in: the idta, either as parameter in or out.
in: is idta of incoming file.
out: idta of outgoing file, need to trace back for incoming file.
return list of ta's for display in detail template.
This list is formatted and ordered for display.
first, get a tree (trace) starting with the incoming ta ;
than make up the details for the trace
'''
if request.method == 'GET':
if 'inidta' in request.GET:
rootta = models.ta.objects.get(idta=int(request.GET['inidta']))
viewlib.gettrace(rootta)
detaillist = viewlib.trace2detail(rootta)
return django.shortcuts.render_to_response('bots/detail.html', {'detaillist':detaillist,'rootta':rootta,},context_instance=django.template.RequestContext(request))
else:
#trace back to root:
rootta = viewlib.django_trace_origin(int(request.GET['outidta']),{'status':EXTERNIN})[0]
viewlib.gettrace(rootta)
detaillist = viewlib.trace2detail(rootta)
return django.shortcuts.render_to_response('bots/detail.html', {'detaillist':detaillist,'rootta':rootta,},context_instance=django.template.RequestContext(request))
def confirm(request,*kw,**kwargs):
if request.method == 'GET':
if 'select' in request.GET: #via menu, go to select form
formout = forms.SelectConfirm()
return viewlib.render(request,formout)
else: #via menu, go to view form for last run
cleaned_data = {'page':1,'sortedby':'ts','sortedasc':False}
else: # request.method == 'POST'
if '2incoming' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='confirm2in')
return incoming(request)
elif '2outgoing' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
request.POST = viewlib.changepostparameters(request.POST,type='confirm2out')
return outgoing(request)
elif 'fromselect' in request.POST: #coming from select criteria screen
formin = forms.SelectConfirm(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif 'confirm' in request.POST: #coming from 'star' menu 'Manual confirm'
ta = models.ta.objects.get(idta=int(request.POST[u'confirm']))
if ta.confirmed == False and ta.confirmtype.startswith('ask'):
ta.confirmed = True
ta.confirmidta = '-1' # to indicate a manual confirmation
ta.save()
request.user.message_set.create(message='Manual confirmed.')
else:
request.user.message_set.create(message='Manual confirm not possible.')
# then just refresh the current view
formin = forms.ViewConfirm(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
else:
formin = forms.ViewConfirm(request.POST)
if not formin.is_valid():
return viewlib.render(request,formin)
elif '2select' in request.POST: #coming from ViewIncoming, change the selection criteria, go to select form
formout = forms.SelectConfirm(formin.cleaned_data)
return viewlib.render(request,formout)
else: #coming from ViewIncoming
viewlib.handlepagination(request.POST,formin.cleaned_data)
cleaned_data = formin.cleaned_data
query = models.ta.objects.filter(confirmasked=True).all()
pquery = viewlib.filterquery(query,cleaned_data)
formout = forms.ViewConfirm(initial=cleaned_data)
return viewlib.render(request,formout,pquery)
def filer(request,*kw,**kwargs):
''' handles bots file viewer. Only files in data dir of Bots are displayed.'''
nosuchfile = _(u'No such file.')
if request.method == 'GET':
try:
idta = request.GET['idta']
except:
return django.shortcuts.render_to_response('bots/filer.html', {'error_content': nosuchfile},context_instance=django.template.RequestContext(request))
if idta == 0: #for the 'starred' file names (eg multiple output)
return django.shortcuts.render_to_response('bots/filer.html', {'error_content': nosuchfile},context_instance=django.template.RequestContext(request))
try:
currentta = list(models.ta.objects.filter(idta=idta))[0]
if request.GET['action']=='downl':
response = django.http.HttpResponse(mimetype=currentta.contenttype)
if currentta.contenttype == 'text/html':
dispositiontype = 'inline'
else:
dispositiontype = 'attachment'
response['Content-Disposition'] = dispositiontype + '; filename=' + currentta.filename + '.txt'
#~ response['Content-Length'] = os.path.getsize(absfilename)
response.write(botslib.readdata(currentta.filename,charset=currentta.charset,errors='ignore'))
return response
elif request.GET['action']=='previous':
if currentta.parent: #has a explicit parent
talijst = list(models.ta.objects.filter(idta=currentta.parent))
else: #get list of ta's referring to this idta as child
talijst = list(models.ta.objects.filter(child=currentta.idta))
elif request.GET['action']=='this':
if currentta.status == EXTERNIN: #jump strait to next file, as EXTERNIN can not be displayed.
talijst = list(models.ta.objects.filter(parent=currentta.idta))
elif currentta.status == EXTERNOUT:
talijst = list(models.ta.objects.filter(idta=currentta.parent))
else:
talijst = [currentta]
elif request.GET['action']=='next':
if currentta.child: #has a explicit child
talijst = list(models.ta.objects.filter(idta=currentta.child))
else:
talijst = list(models.ta.objects.filter(parent=currentta.idta))
for ta in talijst:
ta.has_next = True
if ta.status == EXTERNIN:
ta.content = _(u'External file. Can not be displayed. Use "next".')
elif ta.status == EXTERNOUT:
ta.content = _(u'External file. Can not be displayed. Use "previous".')
ta.has_next = False
elif ta.statust in [OPEN,ERROR]:
ta.content = _(u'File has error status and does not exist. Use "previous".')
ta.has_next = False
elif not ta.filename:
ta.content = _(u'File can not be displayed.')
else:
if ta.charset: #guess charset; uft-8 is reasonable
ta.content = botslib.readdata(ta.filename,charset=ta.charset,errors='ignore')
else:
ta.content = botslib.readdata(ta.filename,charset='utf-8',errors='ignore')
return django.shortcuts.render_to_response('bots/filer.html', {'idtas': talijst},context_instance=django.template.RequestContext(request))
except:
#~ print botslib.txtexc()
return django.shortcuts.render_to_response('bots/filer.html', {'error_content': nosuchfile},context_instance=django.template.RequestContext(request))
def plugin(request,*kw,**kwargs):
if request.method == 'GET':
form = forms.UploadFileForm()
return django.shortcuts.render_to_response('bots/plugin.html', {'form': form},context_instance=django.template.RequestContext(request))
else:
if 'submit' in request.POST: #coming from ViewIncoming, go to outgoing form using same criteria
form = forms.UploadFileForm(request.POST, request.FILES)
if form.is_valid():
botsglobal.logger.info(_(u'Start reading plugin "%s".'),request.FILES['file'].name)
try:
if pluglib.load(request.FILES['file'].temporary_file_path()):
request.user.message_set.create(message='Renamed existing files.')
except botslib.PluginError,txt:
botsglobal.logger.info(u'%s',str(txt))
request.user.message_set.create(message='%s'%txt)
else:
botsglobal.logger.info(_(u'Finished reading plugin "%s" successful.'),request.FILES['file'].name)
request.user.message_set.create(message='Plugin "%s" is read successful.'%request.FILES['file'].name)
request.FILES['file'].close()
else:
request.user.message_set.create(message=_(u'No plugin read.'))
return django.shortcuts.redirect('/home')
def plugout(request,*kw,**kwargs):
if request.method == 'GET':
form = forms.PlugoutForm()
return django.shortcuts.render_to_response('bots/plugout.html', {'form': form},context_instance=django.template.RequestContext(request))
else:
if 'submit' in request.POST:
form = forms.PlugoutForm(request.POST)
if form.is_valid():
botsglobal.logger.info(_(u'Start writing plugin "%s".'),form.cleaned_data['filename'])
try:
pluglib.plugoutcore(form.cleaned_data)
except botslib.PluginError, txt:
botsglobal.logger.info(u'%s',str(txt))
request.user.message_set.create(message='%s'%txt)
else:
botsglobal.logger.info(_(u'Plugin "%s" created successful.'),form.cleaned_data['filename'])
request.user.message_set.create(message=_(u'Plugin %s created successful.')%form.cleaned_data['filename'])
return django.shortcuts.redirect('/home')
def delete(request,*kw,**kwargs):
if request.method == 'GET':
form = forms.DeleteForm()
return django.shortcuts.render_to_response('bots/delete.html', {'form': form},context_instance=django.template.RequestContext(request))
else:
if 'submit' in request.POST:
form = forms.DeleteForm(request.POST)
if form.is_valid():
botsglobal.logger.info(_(u'Start deleting in configuration.'))
if form.cleaned_data['deltransactions']:
#while testing with very big loads, deleting transaction when wrong. Using raw SQL solved this.
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("DELETE FROM ta")
cursor.execute("DELETE FROM filereport")
cursor.execute("DELETE FROM report")
transaction.commit_unless_managed()
request.user.message_set.create(message=_(u'Transactions are deleted.'))
botsglobal.logger.info(_(u' Transactions are deleted.'))
#clean data files
deletefrompath = botsglobal.ini.get('directories','data','botssys/data')
shutil.rmtree(deletefrompath,ignore_errors=True)
botslib.dirshouldbethere(deletefrompath)
request.user.message_set.create(message=_(u'Data files are deleted.'))
botsglobal.logger.info(_(u' Data files are deleted.'))
if form.cleaned_data['delconfiguration']:
models.confirmrule.objects.all().delete()
models.channel.objects.all().delete()
models.chanpar.objects.all().delete()
models.partner.objects.all().delete()
models.translate.objects.all().delete()
models.routes.objects.all().delete()
request.user.message_set.create(message=_(u'Database configuration is deleted.'))
botsglobal.logger.info(_(u' Database configuration is deleted.'))
if form.cleaned_data['delcodelists']:
models.ccode.objects.all().delete()
models.ccodetrigger.objects.all().delete()
request.user.message_set.create(message=_(u'User code lists are deleted.'))
botsglobal.logger.info(_(u' User code lists are deleted.'))
if form.cleaned_data['delinfile']:
deletefrompath = botslib.join(botsglobal.ini.get('directories','botssys','botssys'),'infile')
shutil.rmtree('bots/botssys/infile',ignore_errors=True)
request.user.message_set.create(message=_(u'Files in botssys/infile are deleted.'))
botsglobal.logger.info(_(u' Files in botssys/infile are deleted.'))
if form.cleaned_data['deloutfile']:
deletefrompath = botslib.join(botsglobal.ini.get('directories','botssys','botssys'),'outfile')
shutil.rmtree('bots/botssys/outfile',ignore_errors=True)
request.user.message_set.create(message=_(u'Files in botssys/outfile are deleted.'))
botsglobal.logger.info(_(u' Files in botssys/outfile are deleted.'))
if form.cleaned_data['deluserscripts']:
deletefrompath = botsglobal.ini.get('directories','usersysabs')
for root, dirs, files in os.walk(deletefrompath):
head, tail = os.path.split(root)
if tail == 'charsets':
del dirs[:]
continue
for bestand in files:
if bestand != '__init__.py':
os.remove(os.path.join(root,bestand))
request.user.message_set.create(message=_(u'User scripts are deleted (in usersys).'))
botsglobal.logger.info(_(u' User scripts are deleted (in usersys).'))
elif form.cleaned_data['delbackup']:
deletefrompath = botsglobal.ini.get('directories','usersysabs')
for root, dirs, files in os.walk(deletefrompath):
head, tail = os.path.split(root)
if tail == 'charsets':
del dirs[:]
continue
for bestand in files:
name,ext = os.path.splitext(bestand)
if ext and len(ext) == 15 and ext[1:].isdigit() :
os.remove(os.path.join(root,bestand))
request.user.message_set.create(message=_(u'Backupped user scripts are deleted/purged (in usersys).'))
botsglobal.logger.info(_(u' Backupped user scripts are deleted/purged (in usersys).'))
botsglobal.logger.info(_(u'Finished deleting in configuration.'))
return django.shortcuts.redirect('/home')
def runengine(request,*kw,**kwargs):
if request.method == 'GET':
#check if bots-engine is not already running
if list(models.mutex.objects.filter(mutexk=1).all()):
request.user.message_set.create(message=_(u'Trying to run "bots-engine", but database is locked by another run in progress. Please try again later.'))
botsglobal.logger.info(_(u'Trying to run "bots-engine", but database is locked by another run in progress.'))
return django.shortcuts.redirect('/home')
#find out the right arguments to use
botsenginepath = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),'bots-engine.py') #find the bots-engine
lijst = [sys.executable,botsenginepath] + sys.argv[1:]
if 'clparameter' in request.GET:
lijst.append(request.GET['clparameter'])
try:
botsglobal.logger.info(_(u'Run bots-engine with parameters: "%s"'),str(lijst))
terug = subprocess.Popen(lijst).pid
request.user.message_set.create(message=_(u'Bots-engine is started.'))
except:
txt = botslib.txtexc()
request.user.message_set.create(message=_(u'Errors while trying to run bots-engine.'))
botsglobal.logger.info(_(u'Errors while trying to run bots-engine:\n%s.'),txt)
return django.shortcuts.redirect('/home')
def unlock(request,*kw,**kwargs):
if request.method == 'GET':
lijst = list(models.mutex.objects.filter(mutexk=1).all())
if lijst:
lijst[0].delete()
request.user.message_set.create(message=_(u'Unlocked database.'))
botsglobal.logger.info(_(u'Unlocked database.'))
else:
request.user.message_set.create(message=_(u'Request to unlock database, but database was not locked.'))
botsglobal.logger.info(_(u'Request to unlock database, but database was not locked.'))
return django.shortcuts.redirect('/home')
def sendtestmailmanagers(request,*kw,**kwargs):
try:
sendornot = botsglobal.ini.getboolean('settings','sendreportiferror',False)
except botslib.BotsError:
sendornot = False
if not sendornot:
botsglobal.logger.info(_(u'Trying to send test mail, but in bots.ini, section [settings], "sendreportiferror" is not "True".'))
request.user.message_set.create(message=_(u'Trying to send test mail, but in bots.ini, section [settings], "sendreportiferror" is not "True".'))
return django.shortcuts.redirect('/home')
from django.core.mail import mail_managers
try:
mail_managers(_(u'testsubject'), _(u'test content of report'))
except:
txt = botslib.txtexc()
request.user.message_set.create(message=_(u'Sending test mail failed.'))
botsglobal.logger.info(_(u'Sending test mail failed, error:\n%s'), txt)
return django.shortcuts.redirect('/home')
request.user.message_set.create(message=_(u'Sending test mail succeeded.'))
botsglobal.logger.info(_(u'Sending test mail succeeded.'))
return django.shortcuts.redirect('/home')
| Python |
import os
import sys
import time
import zipfile
import zipimport
import operator
import django
from django.core import serializers
from django.utils.translation import ugettext as _
import models
import botslib
import botsglobal
'''
some tabel have 'id' as primary key. This is always an artificial key.
this is not usable for plugins: 'id' is never written to a plugin.
often a tabel with 'id' has an 'unique together' attribute.
than this is used to check if the entry already exists (this is reported).
existing entries are always overwritten.
exceptions:
- confirmrule; there is no clear unique key. AFAICS this will never be a problem.
- translate: may be confusing. But anyway, no existing translate will be overwritten....
'''
#plugincomparelist is used for filtering and sorting the plugins.
plugincomparelist = ['uniek','persist','mutex','ta','filereport','report','ccodetrigger','ccode', 'channel','partner','chanpar','translate','routes','confirmrule']
def pluglistcmp(key1,key2):
#sort by plugincomparelist
return plugincomparelist.index(key1) - plugincomparelist.index(key2)
def pluglistcmpisgroup(plug1,plug2):
#sort partnergroups before parters
if plug1['plugintype'] == 'partner' and plug2['plugintype'] == 'partner':
return int(plug2['isgroup']) - int(plug1['isgroup'])
else:
return 0
def writetodatabase(orgpluglist):
#sanity checks on pluglist
if not orgpluglist: #list of plugins is empty: is OK. DO nothing
return
if not isinstance(orgpluglist,list): #has to be a list!!
raise botslib.PluginError(_(u'plugins should be list of dicts. Nothing is written.'))
for plug in orgpluglist:
if not isinstance(plug,dict):
raise botslib.PluginError(_(u'plugins should be list of dicts. Nothing is written.'))
for key in plug.keys():
if not isinstance(key,basestring):
raise botslib.PluginError(_(u'key of dict is not a string: "%s". Nothing is written.')%(plug))
if 'plugintype' not in plug:
raise botslib.PluginError(_(u'"plugintype" missing in: "%s". Nothing is written.')%(plug))
#special case: compatibility with bots 1.* plugins.
#in bots 1.*, partnergroup was in separate tabel; in bots 2.* partnergroup is in partner
#later on, partnergroup will get filtered
for plug in orgpluglist[:]:
if plug['plugintype'] == 'partnergroup':
for plugpartner in orgpluglist:
if plugpartner['plugintype'] == 'partner' and plugpartner['idpartner'] == plug['idpartner']:
if 'group' in plugpartner:
plugpartner['group'].append(plug['idpartnergroup'])
else:
plugpartner['group'] = [plug['idpartnergroup']]
break
#copy & filter orgpluglist; do plugtype specific adaptions
pluglist = []
for plug in orgpluglist:
if plug['plugintype'] == 'ccode': #add ccodetrigger. #20101223: this is NOT needed; codetrigger shoudl be in plugin.
for seachccodetriggerplug in pluglist:
if seachccodetriggerplug['plugintype']=='ccodetrigger' and seachccodetriggerplug['ccodeid']==plug['ccodeid']:
break
else:
pluglist.append({'plugintype':'ccodetrigger','ccodeid':plug['ccodeid']})
elif plug['plugintype'] == 'translate': #make some fields None instead of '' (translate formpartner, topartner)
if not plug['frompartner']:
plug['frompartner'] = None
if not plug['topartner']:
plug['topartner'] = None
elif plug['plugintype'] in ['ta','filereport']: #sqlite can have errortexts that are to long. Chop these
plug['errortext'] = plug['errortext'][:2047]
elif plug['plugintype'] == 'routes':
plug['active'] = False
if not 'defer' in plug:
plug['defer'] = False
else:
if plug['defer'] is None:
plug['defer'] = False
elif plug['plugintype'] == 'confirmrule':
plug.pop('id', None) #id is an artificial key, delete,
elif plug['plugintype'] not in plugincomparelist: #if not in plugincomparelist: do not use
continue
pluglist.append(plug)
#sort pluglist: this is needed for relationships
pluglist.sort(cmp=pluglistcmp,key=operator.itemgetter('plugintype'))
#2nd sort: sort partenergroups before partners
pluglist.sort(cmp=pluglistcmpisgroup)
#~ for plug in pluglist:
#~ print 'list:',plug
for plug in pluglist:
botsglobal.logger.info(u' Start write to database for: "%s".'%plug)
#remember the plugintype
plugintype = plug['plugintype']
#~ print '\nstart plug', plug
table = django.db.models.get_model('bots',plug['plugintype'])
#~ print table
#delete fields not in model (create compatibility plugin-version)
loopdictionary = plug.keys()
for key in loopdictionary:
try:
table._meta.get_field(key)
except django.db.models.fields.FieldDoesNotExist:
del plug[key]
#get key(s), put in dict 'sleutel'
pk = table._meta.pk.name
if pk == 'id':
sleutel = {}
if table._meta.unique_together:
for key in table._meta.unique_together[0]:
sleutel[key]=plug.pop(key)
else:
sleutel = {pk:plug.pop(pk)}
#now we have:
#- sleutel: unique key fields. mind: translate and confirmrule have empty 'sleutel' now
#- plug: rest of database fields
sleutelorg = sleutel.copy() #make a copy of the original sleutel; this is needed later
#get real column names for fields in plug
loopdictionary = plug.keys()
for fieldname in loopdictionary:
fieldobject = table._meta.get_field_by_name(fieldname)[0]
try:
if fieldobject.column != fieldname: #if name in plug is not the real field name (in database)
plug[fieldobject.column] = plug[fieldname] #add new key in plug
del plug[fieldname] #delete old key in plug
#~ print 'replace _id for:',fieldname
except:
print 'no field column for:',fieldname #should this be raised?
#get real column names for fields in sleutel; basically the same loop but now for sleutel
loopdictionary = sleutel.keys()
for fieldname in loopdictionary:
fieldobject = table._meta.get_field_by_name(fieldname)[0]
try:
if fieldobject.column != fieldname:
sleutel[fieldobject.column] = sleutel[fieldname]
del sleutel[fieldname]
except:
print 'no field column for',fieldname
#now we have:
#- sleutel: unique key fields. mind: translate and confirmrule have empty 'sleutel' now
#- sleutelorg: original key fields
#- plug: rest of database fields
#- plugintype
#all fields have the right database name
#~ print 'plug attr',plug
#~ print 'orgsleutel',sleutelorg
#~ print 'sleutel',sleutel
#existing ccodetriggers are not overwritten (as deleting ccodetrigger also deletes ccodes)
if plugintype == 'ccodetrigger':
listexistingentries = table.objects.filter(**sleutelorg).all()
if listexistingentries:
continue
#now find the entry using the keys in sleutelorg; delete the existing entry.
elif sleutelorg: #not for translate and confirmrule; these have an have an empty 'sleutel'
listexistingentries = table.objects.filter(**sleutelorg).all()
elif plugintype == 'translate': #for translate: delete existing entry
listexistingentries = table.objects.filter(fromeditype=plug['fromeditype'],frommessagetype=plug['frommessagetype'],alt=plug['alt'],frompartner=plug['frompartner_id'],topartner=plug['topartner_id']).all()
elif plugintype == 'confirmrule': #for confirmrule: delete existing entry; but how to find this??? what are keys???
listexistingentries = table.objects.filter(confirmtype=plug['confirmtype'],
ruletype=plug['ruletype'],
negativerule=plug['negativerule'],
idroute=plug.get('idroute'),
idchannel=plug.get('idchannel_id'),
editype=plug.get('editype'),
messagetype=plug.get('messagetype'),
frompartner=plug.get('frompartner_id'),
topartner=plug.get('topartner_id')).all()
if listexistingentries:
for entry in listexistingentries:
entry.delete()
botsglobal.logger.info(_(u' Existing entry in database is deleted.'))
dbobject = table(**sleutel) #create db-object
if plugintype == 'partner': #for partners, first the partner needs to be saved before groups can be made
dbobject.save()
for key,value in plug.items():
setattr(dbobject,key,value)
dbobject.save()
botsglobal.logger.info(_(u' Write to database is OK.'))
@django.db.transaction.commit_on_success #if no exception raised: commit, else rollback.
def load(pathzipfile):
''' process uploaded plugin. '''
#test is valid zipfile
if not zipfile.is_zipfile(pathzipfile):
raise botslib.PluginError(_(u'Plugin is not a valid file.'))
#read index file
try:
Zipimporter = zipimport.zipimporter(pathzipfile)
importedbotsindex = Zipimporter.load_module('botsindex')
pluglist = importedbotsindex.plugins[:]
if 'botsindex' in sys.modules:
del sys.modules['botsindex']
except:
txt = botslib.txtexc()
raise botslib.PluginError(_(u'Error in plugin. Nothing is written. Error:\n%s')%(txt))
else:
botsglobal.logger.info(_(u'Plugin is OK.'))
botsglobal.logger.info(_(u'Start writing to database.'))
#write content of index file to the bots database
try:
writetodatabase(pluglist)
except:
txt = botslib.txtexc()
raise botslib.PluginError(_(u'Error writing plugin to database. Nothing is written. Error:\n%s'%(txt)))
else:
botsglobal.logger.info(u'Writing to database is OK.')
botsglobal.logger.info(u'Start writing to files')
#write files to the file system.
try:
warnrenamed = False #to report in GUI files have been overwritten.
z = zipfile.ZipFile(pathzipfile, mode="r")
orgtargetpath = botsglobal.ini.get('directories','botspath')
if (orgtargetpath[-1:] in (os.path.sep, os.path.altsep) and len(os.path.splitdrive(orgtargetpath)[1]) > 1):
orgtargetpath = orgtargetpath[:-1]
for f in z.infolist():
if f.filename not in ['botsindex.py','README','botssys/sqlitedb/botsdb','config/bots.ini'] and os.path.splitext(f.filename)[1] not in ['.pyo','.pyc']:
#~ botsglobal.logger.info(u'filename in zip "%s".',f.filename)
if f.filename[0] == '/':
targetpath = f.filename[1:]
else:
targetpath = f.filename
targetpath = targetpath.replace('usersys',botsglobal.ini.get('directories','usersysabs'),1)
targetpath = targetpath.replace('botssys',botsglobal.ini.get('directories','botssys'),1)
targetpath = botslib.join(orgtargetpath, targetpath)
#targetpath is OK now.
botsglobal.logger.info(_(u' Start writing file: "%s".'),targetpath)
if botslib.dirshouldbethere(os.path.dirname(targetpath)):
botsglobal.logger.info(_(u' Create directory "%s".'),os.path.dirname(targetpath))
if f.filename[-1] == '/': #check if this is a dir; if so continue
continue
if os.path.isfile(targetpath): #check if file already exists
try: #this ***sometimes*** fails. (python25, for static/help/home.html...only there...)
os.rename(targetpath,targetpath+'.'+time.strftime('%Y%m%d%H%M%S'))
warnrenamed=True
botsglobal.logger.info(_(u' Renamed existing file "%(from)s" to "%(to)s".'),{'from':targetpath,'to':targetpath+time.strftime('%Y%m%d%H%M%S')})
except:
pass
source = z.read(f.filename)
target = open(targetpath, "wb")
target.write(source)
target.close()
botsglobal.logger.info(_(u' File written: "%s".'),targetpath)
except:
txt = botslib.txtexc()
z.close()
raise botslib.PluginError(_(u'Error writing files to system. Nothing is written to database. Error:\n%s')%(txt))
else:
z.close()
botsglobal.logger.info(_(u'Writing files to filesystem is OK.'))
return warnrenamed
#*************************************************************
# generate a plugin (plugout)
#*************************************************************
def plugoutcore(cleaned_data):
pluginzipfilehandler = zipfile.ZipFile(cleaned_data['filename'], 'w', zipfile.ZIP_DEFLATED)
tmpbotsindex = plugout_database(cleaned_data)
pluginzipfilehandler.writestr('botsindex.py',tmpbotsindex) #write index file to pluginfile
files4plugin = plugout_files(cleaned_data)
for dirname, defaultdirname in files4plugin:
pluginzipfilehandler.write(dirname,defaultdirname)
botsglobal.logger.debug(_(u' write file "%s".'),defaultdirname)
pluginzipfilehandler.close()
def plugout_database(cleaned_data):
#collect all database objects
db_objects = []
if cleaned_data['databaseconfiguration']:
db_objects += \
list(models.channel.objects.all()) + \
list(models.partner.objects.all()) + \
list(models.chanpar.objects.all()) + \
list(models.translate.objects.all()) + \
list(models.routes.objects.all()) + \
list(models.confirmrule.objects.all())
if cleaned_data['umlists']:
db_objects += \
list(models.ccodetrigger.objects.all()) + \
list(models.ccode.objects.all())
if cleaned_data['databasetransactions']:
db_objects += \
list(models.uniek.objects.all()) + \
list(models.mutex.objects.all()) + \
list(models.ta.objects.all()) + \
list(models.filereport.objects.all()) + \
list(models.report.objects.all())
#~ list(models.persist.objects.all()) + \ #commetned out......does this need testing?
#serialize database objects
orgplugs = serializers.serialize("python", db_objects)
#write serialized objects to str/buffer
tmpbotsindex = u'import datetime\nversion = 2\nplugins = [\n'
for plug in orgplugs:
app,tablename = plug['model'].split('.',1)
plug['fields']['plugintype'] = tablename
table = django.db.models.get_model(app,tablename)
pk = table._meta.pk.name
if pk != 'id':
plug['fields'][pk] = plug['pk']
tmpbotsindex += repr(plug['fields']) + u',\n'
botsglobal.logger.debug(u' write in index: %s',plug['fields'])
#check confirmrule: id is non-artifical key?
tmpbotsindex += u']\n'
return tmpbotsindex
def plugout_files(cleaned_data):
''' gather list of files for the plugin that is generated '''
files2return = []
usersys = botsglobal.ini.get('directories','usersysabs')
botssys = botsglobal.ini.get('directories','botssys')
if cleaned_data['fileconfiguration']: #gather from usersys
files2return.extend(plugout_files_bydir(usersys,'usersys'))
if not cleaned_data['charset']: #if edifact charsets are not needed: remove them (are included in default bots installation).
charsetdirs = plugout_files_bydir(os.path.join(usersys,'charsets'),'usersys/charsets')
for charset in charsetdirs:
try:
index = files2return.index(charset)
files2return.pop(index)
except ValueError:
pass
if cleaned_data['config']:
config = botsglobal.ini.get('directories','config')
files2return.extend(plugout_files_bydir(config,'config'))
if cleaned_data['data']:
data = botsglobal.ini.get('directories','data')
files2return.extend(plugout_files_bydir(data,'botssys/data'))
if cleaned_data['database']:
files2return.extend(plugout_files_bydir(os.path.join(botssys,'sqlitedb'),'botssys/sqlitedb.copy')) #yeah...readign a plugin with a new database will cause a crash...do this manually...
if cleaned_data['infiles']:
files2return.extend(plugout_files_bydir(os.path.join(botssys,'infile'),'botssys/infile'))
if cleaned_data['logfiles']:
log_file = botsglobal.ini.get('directories','logging')
files2return.extend(plugout_files_bydir(log_file,'botssys/logging'))
return files2return
def plugout_files_bydir(dirname,defaultdirname):
''' gather all files from directory dirname'''
files2return = []
for root, dirs, files in os.walk(dirname):
head, tail = os.path.split(root)
if tail in ['.svn']: #skip .svn directries
del dirs[:] #os.walk will not look in subdirectories
continue
rootinplugin = root.replace(dirname,defaultdirname,1)
for bestand in files:
ext = os.path.splitext(bestand)[1]
if ext and (ext in ['.pyc','.pyo'] or bestand in ['__init__.py'] or (len(ext) == 15 and ext[1:].isdigit())):
continue
files2return.append([os.path.join(root,bestand),os.path.join(rootinplugin,bestand)])
return files2return
| Python |
try:
from pysqlite2 import dbapi2 as sqlite #prefer external modules for pylite
except ImportError:
import sqlite3 as sqlite #works OK for python26
#~ #bots engine uses:
#~ ''' SELECT *
#~ FROM ta
#~ WHERE idta=%(idta)s ''',
#~ {'idta':12345})
#~ #SQLite wants:
#~ ''' SELECT *
#~ FROM ta
#~ WHERE idta=:idta ''',
#~ {'idta': 12345}
import re
reformatparamstyle = re.compile(u'%\((?P<name>[^)]+)\)s')
def adapter4bool(boolfrompython):
#SQLite expects a string
if boolfrompython:
return '1'
else:
return '0'
def converter4bool(strfromdb):
#SQLite returns a string
if strfromdb == '1':
return True
else:
return False
sqlite.register_adapter(bool,adapter4bool)
sqlite.register_converter('BOOLEAN',converter4bool)
def connect(database):
con = sqlite.connect(database, factory=BotsConnection,detect_types=sqlite.PARSE_DECLTYPES, timeout=99.0, isolation_level='IMMEDIATE')
con.row_factory = sqlite.Row
con.execute('''PRAGMA synchronous=OFF''')
return con
class BotsConnection(sqlite.Connection):
def cursor(self):
return sqlite.Connection.cursor(self, factory=BotsCursor)
class BotsCursor(sqlite.Cursor):
def execute(self,string,parameters=None):
if parameters is None:
sqlite.Cursor.execute(self,string)
else:
sqlite.Cursor.execute(self,reformatparamstyle.sub(u''':\g<name>''',string),parameters)
| Python |
#!/usr/bin/env python
''' This script starts bots-engine.'''
import sys
import os
import atexit
import traceback
import logging
import datetime
logging.raiseExceptions = 0 #if errors occur in writing to log: ignore error; this will lead to a missing log line.
#it is better to have a missing log line than an error in a translation....
from django.utils.translation import ugettext as _
#bots-modules
import botslib
import botsinit
import botsglobal
import router
import automaticmaintenance
import cleanup
from botsconfig import *
def showusage():
usage = '''
This is "%(name)s", a part of Bots open source edi translator - http://bots.sourceforge.net.
The %(name)s does the actual translations and communications; it's the workhorse. It does not have a fancy interface.
Usage:
%(name)s [run-options] [config-option] [routes]
Run-options (can be combined, except for crashrecovery):
--new receive new edi files (default: if no run-option given: run as new).
--retransmit resend and rereceive as indicated by user.
--retry retry previous errors.
--crashrecovery reruns the run where the crash occurred. (when database is locked).
--automaticretrycommunication - automatically retry outgoing communication.
--retrycommunication retry outgoing communication process errors as indicated by user.
--cleanup remove older data from database.
Config-option:
-c<directory> directory for configuration files (default: config).
Routes: list of routes to run. Default: all active routes (in the database)
'''%{'name':os.path.basename(sys.argv[0])}
print usage
def start():
#exit codes:
# 0: OK, no errors
# 1: (system) errors
# 2: bots ran OK, but there are errors/process errors in the run
# 3: Database is locked, but "maxruntime" has not been exceeded.
#********command line arguments**************************
commandspossible = ['--new','--retry','--retransmit','--cleanup','--crashrecovery','--retrycommunication','--automaticretrycommunication']
commandstorun = []
routestorun = [] #list with routes to run
configdir = 'config'
for arg in sys.argv[1:]:
if not arg:
continue
if arg.startswith('-c'):
configdir = arg[2:]
if not configdir:
print 'Configuration directory indicated, but no directory name.'
sys.exit(1)
elif arg in commandspossible:
commandstorun.append(arg)
elif arg in ["?", "/?"] or arg.startswith('-'):
showusage()
sys.exit(0)
else: #pick up names of routes to run
routestorun.append(arg)
if not commandstorun: #if no command on command line, use new (default)
commandstorun = ['--new']
#**************init general: find locating of bots, configfiles, init paths etc.****************
botsinit.generalinit(configdir)
#set current working directory to botspath
#~ old_current_directory = os.getcwdu()
os.chdir(botsglobal.ini.get('directories','botspath'))
#**************initialise logging******************************
try:
botsinit.initenginelogging()
except:
print _('Error in initialising logging system.')
traceback.print_exc()
sys.exit(1)
else:
atexit.register(logging.shutdown)
for key,value in botslib.botsinfo(): #log start info
botsglobal.logger.info(u'%s: "%s".',key,value)
#**************connect to database**********************************
try:
botsinit.connect()
except:
botsglobal.logger.exception(_(u'Could not connect to database. Database settings are in bots/config/settings.py.'))
sys.exit(1)
else:
botsglobal.logger.info(_(u'Connected to database.'))
atexit.register(botsglobal.db.close)
#initialise user exits for the whole bots-engine (this script file)
try:
userscript,scriptname = botslib.botsimport('routescripts','botsengine')
except ImportError:
userscript = scriptname = None
#**************handle database lock****************************************
#try to set a lock on the database; if this is not possible, the database is already locked. Either:
#1 another instance bots bots-engine is (still) running
#2 or bots-engine had a severe crash.
#What to do?
#first: check ts of database lock. If below a certain value (set in bots.ini) we assume an other instance is running. Exit quietly - no errors, no logging.
# else: Warn user, give advise on what to do. gather data: nr files in, errors.
#next: warn with report & logging. advise a crashrecovery.
if not botslib.set_database_lock():
if '--crashrecovery' in commandstorun: #user starts recovery operation; the databaselock is ignored; the databaselock is unlocked when routes have run.
commandstorun = ['--crashrecovery'] #is an exclusive option!
else:
#when scheduling bots it is possible that the last run is still running. Check if maxruntime has passed:
vanaf = datetime.datetime.today() - datetime.timedelta(minutes=botsglobal.ini.getint('settings','maxruntime',60))
for row in botslib.query('''SELECT ts FROM mutex WHERE ts < %(vanaf)s ''',{'vanaf':vanaf}):
warn = _(u'!Bots database is locked!\nBots-engine has ended in an unexpected way during the last run.\nThis happens, but is very very rare.\nPossible causes: bots-engine terminated by user, system crash, power-down, etc.\nA forced retry of the last run is advised; bots will (try to) repair the last run.')
botsglobal.logger.critical(warn)
botslib.sendbotserrorreport(_(u'[Bots severe error]Database is locked'),warn)
#add: count errors etc.
sys.exit(1)
else: #maxruntime has not passed. Exit silently, nothing reported
botsglobal.logger.info(_(u'Database is locked, but "maxruntime" has not been exceeded.'))
sys.exit(3)
else:
if '--crashrecovery' in commandstorun: #user starts recovery operation but there is no databaselock.
warn = _(u'User started a forced retry of the last run.\nOnly use this when the database is locked.\nThe database was not locked (database is OK).\nSo Bots has done nothing now.')
botsglobal.logger.error(warn)
botslib.sendbotserrorreport(_(u'[Bots Error Report] User started a forced retry of last run, but this was not needed'),warn)
botslib.remove_database_lock()
sys.exit(1)
#*************get list of routes to run****************************************
#~ raise Exception('locked database') #for testing database lock: abort, database will be locked
if routestorun:
botsglobal.logger.info(u'Run routes from command line: "%s".',str(routestorun))
else: # no routes from command line parameters: fetch all active routes from database
for row in botslib.query('''SELECT DISTINCT idroute
FROM routes
WHERE active=%(active)s
AND (notindefaultrun=%(notindefaultrun)s OR notindefaultrun IS NULL)
ORDER BY idroute ''',
{'active':True,'notindefaultrun':False}):
routestorun.append(row['idroute'])
botsglobal.logger.info(_(u'Run active routes from database: "%s".'),str(routestorun))
#routestorun is now either a list with routes from commandline, or the list of active routes for the routes table in the db.
#**************run the routes for retry, retransmit and new runs*************************************
try:
#commandstorun determines the type(s) of run
#routes to run is a listof the routes that are runs (for each command to run
#botsglobal.incommunicate is used to control if there is communication in; only 'new' incommunicates.
#botsglobal.minta4query controls which ta's are queried by the routes.
#stuff2evaluate controls what is evaluated in automatic maintenance.
errorinrun = 0 #detect if there has been some error. Only used for good exit() code
botsglobal.incommunicate = False
if '--crashrecovery' in commandstorun:
botsglobal.logger.info(_(u'Run crash recovery.'))
stuff2evaluate = botslib.set_minta4query_crashrecovery()
if stuff2evaluate:
router.routedispatcher(routestorun)
errorinrun += automaticmaintenance.evaluate('--crashrecovery',stuff2evaluate)
else:
botsglobal.logger.info(_(u'No retry of the last run - there was no last run.'))
if userscript and hasattr(userscript,'postcrashrecovery'):
botslib.runscript(userscript,scriptname,'postcrashrecovery',routestorun=routestorun)
if '--retrycommunication' in commandstorun:
botsglobal.logger.info(_(u'Run communication retry.'))
stuff2evaluate = router.routedispatcher(routestorun,'--retrycommunication')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--retrycommunication',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run recommunicate: nothing to recommunicate.'))
if userscript and hasattr(userscript,'postretrycommunication'):
botslib.runscript(userscript,scriptname,'postretrycommunication',routestorun=routestorun)
if '--automaticretrycommunication' in commandstorun:
botsglobal.logger.info(_(u'Run automatic communication retry.'))
stuff2evaluate = router.routedispatcher(routestorun,'--automaticretrycommunication')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--automaticretrycommunication',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run automatic recommunicate: nothing to recommunicate.'))
if userscript and hasattr(userscript,'postautomaticretrycommunication'):
botslib.runscript(userscript,scriptname,'postautomaticretrycommunication',routestorun=routestorun)
if '--retry' in commandstorun:
botsglobal.logger.info(u'Run retry.')
stuff2evaluate = router.routedispatcher(routestorun,'--retry')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--retry',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run retry: nothing to retry.'))
if userscript and hasattr(userscript,'postretry'):
botslib.runscript(userscript,scriptname,'postretry',routestorun=routestorun)
if '--retransmit' in commandstorun:
botsglobal.logger.info(u'Run retransmit.')
stuff2evaluate = router.routedispatcher(routestorun,'--retransmit')
if stuff2evaluate:
errorinrun += automaticmaintenance.evaluate('--retransmit',stuff2evaluate)
else:
botsglobal.logger.info(_(u'Run retransmit: nothing to retransmit.'))
if userscript and hasattr(userscript,'postretransmit'):
botslib.runscript(userscript,scriptname,'postretransmit',routestorun=routestorun)
if '--new' in commandstorun:
botsglobal.logger.info('Run new.')
botsglobal.incommunicate = True
botsglobal.minta4query = 0 #meaning: reset. the actual value is set later (in routedispatcher)
stuff2evaluate = router.routedispatcher(routestorun)
errorinrun += automaticmaintenance.evaluate('--new',stuff2evaluate)
if userscript and hasattr(userscript,'postnewrun'):
botslib.runscript(userscript,scriptname,'postnewrun',routestorun=routestorun)
if '--cleanup' in commandstorun or botsglobal.ini.get('settings','whencleanup','always')=='always':
botsglobal.logger.debug(u'Do cleanup.')
cleanup.cleanup()
botslib.remove_database_lock()
except Exception,e:
botsglobal.logger.exception(_(u'Severe error in bots system:\n%s')%(e)) #of course this 'should' not happen.
sys.exit(1)
else:
if errorinrun:
sys.exit(2) #indicate: error(s) in run(s)
else:
sys.exit(0) #OK
if __name__=='__main__':
start()
| Python |
''' Reading/lexing/parsing/splitting an edifile.'''
import StringIO
import time
import sys
try:
import cPickle as pickle
except:
import pickle
try:
import cElementTree as ET
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
try:
from xml.etree import cElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET
try:
import json as simplejson
except ImportError:
import simplejson
from django.utils.translation import ugettext as _
import botslib
import botsglobal
import outmessage
import message
import node
import grammar
from botsconfig import *
def edifromfile(**ta_info):
''' Read,lex, parse edi-file. Is a dispatch function for Inmessage and subclasses.'''
try:
classtocall = globals()[ta_info['editype']] #get inmessage class to call (subclass of Inmessage)
except KeyError:
raise botslib.InMessageError(_(u'Unknown editype for incoming message: $editype'),editype=ta_info['editype'])
ediobject = classtocall(ta_info)
ediobject.initfromfile()
return ediobject
def _edifromparsed(editype,inode,ta_info):
''' Get a edi-message (inmessage-object) from node in tree.
is used in splitting edi-messages.'''
classtocall = globals()[editype]
ediobject = classtocall(ta_info)
ediobject.initfromparsed(inode)
return ediobject
#*****************************************************************************
class Inmessage(message.Message):
''' abstract class for incoming ediobject (file or message).
Can be initialised from a file or a tree.
'''
def __init__(self,ta_info):
super(Inmessage,self).__init__()
self.records = [] #init list of records
self.confirminfo = {}
self.ta_info = ta_info #here ta_info is only filled with parameters from db-ta
def initfromfile(self):
''' initialisation from a edi file '''
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype']) #read grammar, after sniffing. Information from sniffing can be used (eg name editype for edifact, using version info from UNB)
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set
self.ta_info['charset'] =self.defmessage.syntax['charset'] #always use charset of edi file.
self._readcontent_edifile()
self._sniff() #some hard-coded parsing of edi file; eg ta_info can be overruled by syntax-parameters in edi-file
#start lexing and parsing
self._lex()
del self.rawinput
#~ self.display(self.records) #show lexed records (for protocol debugging)
self.root = node.Node() #make root Node None.
result = self._parse(self.defmessage.structure,self._nextrecord(self.records),self.root)
if result:
raise botslib.InMessageError(_(u'Unknown data beyond end of message; mostly problem with separators or message structure: "$content"'),content=result)
del self.records
#end parsing; self.root is root of a tree (of nodes).
self.checkenvelope()
#~ self.root.display() #show tree of nodes (for protocol debugging)
#~ self.root.displayqueries() #show queries in tree of nodes (for protocol debugging)
def initfromparsed(self,node):
''' initialisation from a tree (node is passed).
to initialise message in an envelope
'''
self.root = node
def handleconfirm(self,ta_fromfile,error):
''' end of edi file handling.
eg writing of confirmations etc.
'''
pass
def _formatfield(self,value,grammarfield,record):
''' Format of a field is checked and converted if needed.
Input: value (string), field definition.
Output: the formatted value (string)
Parameters of self.ta_info are used: triad, decimaal
for fixed field: same handling; length is not checked.
'''
if grammarfield[BFORMAT] in ['A','D','T']:
if isinstance(self,var): #check length fields in variable records
valuelength=len(value)
if valuelength > grammarfield[LENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too big (max $max): "$content".'),record=record,field=grammarfield[ID],content=value,max=grammarfield[LENGTH])
if valuelength < grammarfield[MINLENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too small (min $min): "$content".'),record=record,field=grammarfield[ID],content=value,min=grammarfield[MINLENGTH])
value = value.strip()
if not value:
pass
elif grammarfield[BFORMAT] == 'A':
pass
elif grammarfield[BFORMAT] == 'D':
try:
lenght = len(value)
if lenght==6:
time.strptime(value,'%y%m%d')
elif lenght==8:
time.strptime(value,'%Y%m%d')
else:
raise ValueError(u'To be catched')
except ValueError:
raise botslib.InMessageFieldError(_(u'Record "$record" date field "$field" not a valid date: "$content".'),record=record,field=grammarfield[ID],content=value)
elif grammarfield[BFORMAT] == 'T':
try:
lenght = len(value)
if lenght==4:
time.strptime(value,'%H%M')
elif lenght==6:
time.strptime(value,'%H%M%S')
elif lenght==7 or lenght==8:
time.strptime(value[0:6],'%H%M%S')
if not value[6:].isdigit():
raise ValueError(u'To be catched')
else:
raise ValueError(u'To be catched')
except ValueError:
raise botslib.InMessageFieldError(_(u'Record "$record" time field "$field" not a valid time: "$content".'),record=record,field=grammarfield[ID],content=value)
else: #numerics (R, N, I)
value = value.strip()
if not value:
if self.ta_info['acceptspaceinnumfield']:
value='0'
else:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" has numeric format but contains only space.'),record=record,field=grammarfield[ID])
#~ return '' #when num field has spaces as content, spaces are stripped. Field should be numeric.
if value[-1] == u'-': #if minus-sign at the end, put it in front.
value = value[-1] + value[:-1]
value = value.replace(self.ta_info['triad'],u'') #strip triad-separators
value = value.replace(self.ta_info['decimaal'],u'.',1) #replace decimal sign by canonical decimal sign
if 'E' in value or 'e' in value:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" format "$format" contains exponent: "$content".'),record=record,field=grammarfield[ID],content=value,format=grammarfield[BFORMAT])
if isinstance(self,var): #check length num fields in variable records
if self.ta_info['lengthnumericbare']:
length = botslib.countunripchars(value,'-+.')
else:
length = len(value)
if length > grammarfield[LENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too big (max $max): "$content".'),record=record,field=grammarfield[ID],content=value,max=grammarfield[LENGTH])
if length < grammarfield[MINLENGTH]:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" too small (min $min): "$content".'),record=record,field=grammarfield[ID],content=value,min=grammarfield[MINLENGTH])
if grammarfield[BFORMAT] == 'I':
if '.' in value:
raise botslib.InMessageFieldError(_(u'Record "$record" field "$field" has format "I" but contains decimal sign: "$content".'),record=record,field=grammarfield[ID],content=value)
try: #convert to decimal in order to check validity
valuedecimal = float(value)
valuedecimal = valuedecimal / 10**grammarfield[DECIMALS]
value = '%.*F'%(grammarfield[DECIMALS],valuedecimal)
except:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has non-numerical content: "$content".'),record=record,field=grammarfield[ID],content=value)
elif grammarfield[BFORMAT] == 'N':
lendecimal = len(value[value.find('.'):])-1
if lendecimal != grammarfield[DECIMALS]:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has invalid nr of decimals: "$content".'),record=record,field=grammarfield[ID],content=value)
try: #convert to decimal in order to check validity
valuedecimal = float(value)
value = '%.*F'%(lendecimal,valuedecimal)
except:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has non-numerical content: "$content".'),record=record,field=grammarfield[ID],content=value)
elif grammarfield[BFORMAT] == 'R':
lendecimal = len(value[value.find('.'):])-1
try: #convert to decimal in order to check validity
valuedecimal = float(value)
value = '%.*F'%(lendecimal,valuedecimal)
except:
raise botslib.InMessageFieldError(_(u'Record "$record" numeric field "$field" has non-numerical content: "$content".'),record=record,field=grammarfield[ID],content=value)
return value
def _parse(self,tab,_nextrecord,inode,rec2parse=None,argmessagetype=None,argnewnode=None):
''' parse the lexed records. validate message against grammar.
add grammar-info to records in self.records: field-tag,mpath.
Tab: current grammar/segmentgroup of the grammar-structure.
Read the records one by one.
Lookup record in tab.
if found:
if headersegment (tabrecord has own tab):
go recursive.
if not found:
if trailer:
jump back recursive, returning the unparsed record.
'''
for tabrec in tab: #clear counts for tab-records (start fresh).
tabrec[COUNT] = 0
tabindex = 0
tabmax = len(tab)
if rec2parse is None:
parsenext = True
subparse=False
else: #only for subparsing
parsenext = False
subparse=True
while 1:
if parsenext:
try:
rec2parse = _nextrecord.next()
except StopIteration: #catch when no more rec2parse.
rec2parse = None
parsenext = False
if rec2parse is None or tab[tabindex][ID] != rec2parse[ID][VALUE]:
#for StopIteration(loop rest of grammar) or when rec2parse
if tab[tabindex][COUNT] < tab[tabindex][MIN]:
try:
raise botslib.InMessageError(_(u'line:$line pos:$pos; record:"$record" not in grammar; looked in grammar until mandatory record: "$looked".'),record=rec2parse[ID][VALUE],line=rec2parse[ID][LIN],pos=rec2parse[ID][POS],looked=tab[tabindex][MPATH])
except TypeError:
raise botslib.InMessageError(_(u'missing mandatory record at message-level: "$record"'),record=tab[tabindex][MPATH])
#TODO: line/pos of original file in error...when this is possible, XML?
tabindex += 1
if tabindex >= tabmax: #rec2parse is not in this level. Go level up
return rec2parse #return either None (for StopIteration) or the last record2parse (not found in this level)
#continue while-loop (parsenext is false)
else: #if found in grammar
tab[tabindex][COUNT] += 1
if tab[tabindex][COUNT] > tab[tabindex][MAX]:
raise botslib.InMessageError(_(u'line:$line pos:$pos; too many repeats record "$record".'),line=rec2parse[ID][LIN],pos=rec2parse[ID][POS],record=tab[tabindex][ID])
if argmessagetype: #that is, header segment of subtranslation
newnode = argnewnode #use old node that is already parsed
newnode.queries = {'messagetype':argmessagetype} #copy messagetype into 1st segment of subtranslation (eg UNH, ST)
argmessagetype=None
else:
newnode = node.Node(record=self._parsefields(rec2parse,tab[tabindex][FIELDS]),BOTSIDnr=tab[tabindex][BOTSIDnr]) #make new node
if botsglobal.ini.getboolean('settings','readrecorddebug',False):
botsglobal.logger.debug(u'read record "%s" (line %s pos %s):',tab[tabindex][ID],rec2parse[ID][LIN],rec2parse[ID][POS])
for key,value in newnode.record.items():
botsglobal.logger.debug(u' "%s" : "%s"',key,value)
if SUBTRANSLATION in tab[tabindex]: # subparse starts here: tree is build for this messagetype; the messagetype is read from the edifile
messagetype = self._getmessagetype(newnode.enhancedget(tab[tabindex][SUBTRANSLATION],replace=True),inode)
if not messagetype:
raise botslib.InMessageError(_(u'could not find SUBTRANSLATION "$sub" in (sub)message.'),sub=tab[tabindex][SUBTRANSLATION])
defmessage = grammar.grammarread(self.__class__.__name__,messagetype)
rec2parse = self._parse(defmessage.structure,_nextrecord,inode,rec2parse=rec2parse,argmessagetype=messagetype,argnewnode=newnode)
#~ end subparse for messagetype
else:
inode.append(newnode) #append new node to current node
if LEVEL in tab[tabindex]: #if header, go to subgroup
rec2parse = self._parse(tab[tabindex][LEVEL],_nextrecord,newnode)
if subparse: #back in top level of subparse: return (to motherparse)
return rec2parse
else:
parsenext = True
self.get_queries_from_edi(inode.children[-1],tab[tabindex])
def _getmessagetype(self,messagetypefromsubtranslation,inode):
return messagetypefromsubtranslation
def get_queries_from_edi(self,node,trecord):
''' extract information from edifile using QUERIES in grammar.structure; information will be placed in ta_info and in db-ta
'''
if QUERIES in trecord:
#~ print 'Print QUERIES'
tmpdict = {}
#~ print trecord[QUERIES]
for key,value in trecord[QUERIES].items():
found = node.enhancedget(value) #search in last added node
if found:
#~ print ' found',found,value
tmpdict[key] = found #copy key to avoid memory problems
#~ else:
#~ print ' not found',value
node.queries = tmpdict
def _readcontent_edifile(self):
''' read content of edi file to memory.
'''
#TODO test, catch exceptions
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
self.rawinput = botslib.readdata(filename=self.ta_info['filename'],charset=self.ta_info['charset'],errors=self.ta_info['checkcharsetin'])
def _sniff(self):
''' sniffing: hard coded parsing of edi file.
method is specified in subclasses.
'''
pass
def checkenvelope(self):
pass
@staticmethod
def _nextrecord(records):
''' generator for records that are lexed.'''
for record in records:
yield record
def nextmessage(self):
''' Generates each message as a separate Inmessage.
'''
#~ self.root.display()
if self.defmessage.nextmessage is not None: #if nextmessage defined in grammar: split up messages
first = True
for message in self.getloop(*self.defmessage.nextmessage): #get node of each message
if first:
self.root.processqueries({},len(self.defmessage.nextmessage))
first = False
ta_info = self.ta_info.copy()
ta_info.update(message.queries)
#~ ta_info['botsroot']=self.root
yield _edifromparsed(self.__class__.__name__,message,ta_info)
if self.defmessage.nextmessage2 is not None: #edifact needs nextmessage2...OK
first = True
for message in self.getloop(*self.defmessage.nextmessage2):
if first:
self.root.processqueries({},len(self.defmessage.nextmessage2))
first = False
ta_info = self.ta_info.copy()
ta_info.update(message.queries)
#~ ta_info['botsroot']=self.root
yield _edifromparsed(self.__class__.__name__,message,ta_info)
elif self.defmessage.nextmessageblock is not None: #for csv/fixed: nextmessageblock indicates which field determines a message (as long as the field is the same, it is one message)
#there is only one recordtype (this is checked in grammar.py).
first = True
for line in self.root.children:
kriterium = line.get(self.defmessage.nextmessageblock)
if first:
first = False
newroot = node.Node() #make new empty root node.
oldkriterium = kriterium
elif kriterium != oldkriterium:
ta_info = self.ta_info.copy()
ta_info.update(oldline.queries) #update ta_info with information (from previous line) 20100905
#~ ta_info['botsroot']=self.root #give mapping script access to all information in edi file: all records
yield _edifromparsed(self.__class__.__name__,newroot,ta_info)
newroot = node.Node() #make new empty root node.
oldkriterium = kriterium
else:
pass #if kriterium is the same
newroot.append(line)
oldline = line #save line 20100905
else:
if not first:
ta_info = self.ta_info.copy()
ta_info.update(line.queries) #update ta_info with information (from last line) 20100904
#~ ta_info['botsroot']=self.root
yield _edifromparsed(self.__class__.__name__,newroot,ta_info)
else: #no split up indicated in grammar;
if self.root.record or self.ta_info['pass_all']: #if contains root-record or explicitly indicated (csv): pass whole tree
ta_info = self.ta_info.copy()
ta_info.update(self.root.queries)
#~ ta_info['botsroot']=None #??is the same as self.root, so I use None??.
yield _edifromparsed(self.__class__.__name__,self.root,ta_info)
else: #pass nodes under root one by one
for child in self.root.children:
ta_info = self.ta_info.copy()
ta_info.update(child.queries)
#~ ta_info['botsroot']=self.root #give mapping script access to all information in edi file: all roots
yield _edifromparsed(self.__class__.__name__,child,ta_info)
class fixed(Inmessage):
''' class for record of fixed length.'''
def _lex(self):
''' lexes file with fixed records to list of records (self.records).'''
linenr = 0
startrecordID = self.ta_info['startrecordID']
endrecordID = self.ta_info['endrecordID']
self.rawinputfile = StringIO.StringIO(self.rawinput) #self.rawinputfile is an iterator
for line in self.rawinputfile:
linenr += 1
line=line.rstrip('\r\n')
self.records += [ [{VALUE:line[startrecordID:endrecordID].strip(),LIN:linenr,POS:0,FIXEDLINE:line}] ] #append record to recordlist
self.rawinputfile.close()
def _parsefields(self,recordEdiFile,trecord):
''' Parse fields from one fixed message-record (from recordEdiFile[ID][FIXEDLINE] using positions.
fields are placed in dict, where key=field-info from grammar and value is from fixedrecord.'''
recorddict = {} #start with empty dict
fixedrecord = recordEdiFile[ID][FIXEDLINE] #shortcut to fixed record we are parsing
lenfixed = len(fixedrecord)
recordlength = 0
for field in trecord: #calculate total length of record from field lengths
recordlength += field[LENGTH]
if recordlength > lenfixed and self.ta_info['checkfixedrecordtooshort']:
raise botslib.InMessageError(_(u'line $line record "$record" too short; is $pos pos, defined is $defpos pos: "$content".'),line=recordEdiFile[ID][LIN],record=recordEdiFile[ID][VALUE],pos=lenfixed,defpos=recordlength,content=fixedrecord)
if recordlength < lenfixed and self.ta_info['checkfixedrecordtoolong']:
raise botslib.InMessageError(_(u'line $line record "$record" too long; is $pos pos, defined is $defpos pos: "$content".'),line=recordEdiFile[ID][LIN],record=recordEdiFile[ID][VALUE],pos=lenfixed,defpos=recordlength,content=fixedrecord)
pos = 0
for field in trecord: #for fields in this record
value = fixedrecord[pos:pos+field[LENGTH]]
try:
value = self._formatfield(value,field,fixedrecord)
except botslib.InMessageFieldError:
txt=botslib.txtexc()
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos. Error:\n$txt'),line=recordEdiFile[ID][LIN],pos=pos,txt=txt)
if value:
recorddict[field[ID][:]] = value #copy id string to avoid memory problem ; value is already a copy
else:
if field[MANDATORY]==u'M':
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; mandatory field "$field" not in record "$record".'),line=recordEdiFile[ID][LIN],pos=pos,field=field[ID],record=recordEdiFile[ID][VALUE])
pos += field[LENGTH]
#~ if pos > lenfixed:
#~ break
return recorddict
class idoc(fixed):
''' class for idoc ediobjects.
for incoming the same as fixed.
SAP does strip all empty fields for record; is catered for in grammar.defaultsyntax
'''
def _sniff(self):
''' examine a read file for syntax parameters and correctness of protocol
eg parse UNA, find UNB, get charset and version
'''
#goto char that is not whitespace
for count,c in enumerate(self.rawinput):
if not c.isspace():
self.rawinput = self.rawinput[count:] #here the interchange should start
break
else:
raise botslib.InMessageError(_(u'edi file only contains whitespace.'))
if self.rawinput[:6] != 'EDI_DC':
raise botslib.InMessageError(_(u'expect "EDI_DC", found "$content". Probably no SAP idoc.'),content=self.rawinput[:6])
class var(Inmessage):
''' abstract class for ediobjects with records of variabele length.'''
def _lex(self):
''' lexes file with variable records to list of records, fields and subfields (self.records).'''
quote_char = self.ta_info['quote_char']
skip_char = self.ta_info['skip_char'] #skip char (ignore);
escape = self.ta_info['escape'] #char after escape-char is not interpreted as seperator
field_sep = self.ta_info['field_sep'] + self.ta_info['record_tag_sep'] #for tradacoms; field_sep and record_tag_sep have same function.
sfield_sep = self.ta_info['sfield_sep']
record_sep = self.ta_info['record_sep']
mode_escape = 0 #0=not escaping, 1=escaping
mode_quote = 0 #0=not in quote, 1=in quote
mode_2quote = 0 #0=not escaping quote, 1=escaping quote.
mode_inrecord = 0 #indicates if lexing a record. If mode_inrecord==0: skip whitespace
sfield = False # True: is subveld, False is geen subveld
value = u'' #the value of the current token
record = []
valueline = 1 #starting line of token
valuepos = 1 #starting position of token
countline = 1
countpos = 0
#bepaal tekenset, separators etc adhv UNA/UNOB
for c in self.rawinput: #get next char
if c == u'\n': #line within file
countline += 1
countpos = 0 #new line, pos back to 0
#no continue, because \n can be record separator. In edifact: catched with skip_char
else:
countpos += 1 #position within line
if mode_quote: #within a quote: quote-char is also escape-char
if mode_2quote and c == quote_char: #thus we were escaping quote_char
mode_2quote = 0
value += c #append quote_char
continue
elif mode_escape: #tricky: escaping a quote char
mode_escape = 0
value += c
continue
elif mode_2quote: #thus is was a end-quote
mode_2quote = 0
mode_quote= 0
#go on parsing
elif c==quote_char: #either end-quote or escaping quote_char,we do not know yet
mode_2quote = 1
continue
elif c == escape:
mode_escape = 1
continue
else:
value += c
continue
if mode_inrecord:
pass #do nothing, is already in mode_inrecord
else:
if c.isspace():
continue #not in mode_inrecord, and a space: ignore space between records.
else:
mode_inrecord = 1
if c in skip_char: #after mode_quote, but before mode_escape!!
continue
if mode_escape: #always append in escaped_mode
mode_escape = 0
value += c
continue
if not value: #if no char in token: this is a new token, get line and pos for (new) token
valueline = countline
valuepos = countpos
if c == quote_char:
mode_quote = 1
continue
if c == escape:
mode_escape = 1
continue
if c in field_sep: #for tradacoms: record_tag_sep is appended to field_sep; in lexing they have the same function
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
value = u''
sfield = False
continue
if c == sfield_sep:
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
value = u''
sfield = True
continue
if c in record_sep:
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
self.records += [record] #write record to recordlist
record=[]
value = u''
sfield = False
mode_inrecord=0
continue
value += c #just a char: append char to value
#end of for-loop. all characters have been processed.
#in a perfect world, value should always be empty now, but:
#it appears a csv record is not always closed properly, so force the closing of the last record of csv file:
if mode_inrecord and isinstance(self,csv) and self.ta_info['allow_lastrecordnotclosedproperly']:
record += [{VALUE:value,SFIELD:sfield,LIN:valueline,POS:valuepos}] #append element in record
self.records += [record] #write record to recordlist
elif value.strip('\x00\x1a'):
raise botslib.InMessageError(_(u'translation problem with lexing; probably a seperator-problem, or extra characters after interchange'))
def _striprecord(self,recordEdiFile):
#~ return [field[VALUE] for field in recordEdiFile]
terug = ''
for field in recordEdiFile:
terug += field[VALUE] + ' '
if len(terug) > 35:
terug = terug[:35] + ' (etc)'
return terug
def _parsefields(self,recordEdiFile,trecord):
''' Check all fields in message-record with field-info in grammar
Build a dictionary of fields (field-IDs are unique within record), and return this.
'''
recorddict = {}
#****************** first: identify fields: assign field id to lexed fields
tindex = -1 #elementcounter; composites count as one
tsubindex=0 #sub-element couner (witin composite))
for rfield in recordEdiFile: #handle both fields and sub-fields
if rfield[SFIELD]:
tsubindex += 1
try:
field = trecord[tindex][SUBFIELDS][tsubindex]
except TypeError: #field has no SUBFIELDS
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; expect field, is a subfield; record "$record".'),line=rfield[LIN],pos=rfield[POS],record=self._striprecord(recordEdiFile))
except IndexError: #tsubindex is not in the subfields
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; too many subfields; record "$record".'),line=rfield[LIN],pos=rfield[POS],record=self._striprecord(recordEdiFile))
else:
tindex += 1
try:
field = trecord[tindex]
except IndexError:
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos; too many fields; record "$record".'),line=rfield[LIN],pos=rfield[POS],record=self._striprecord(recordEdiFile))
if not field[ISFIELD]: #if field is subfield
tsubindex = 0
field = trecord[tindex][SUBFIELDS][tsubindex]
#*********if field has content: check format and add to recorddictionary
if rfield[VALUE]:
try:
rfield[VALUE] = self._formatfield(rfield[VALUE],field,recordEdiFile[0][VALUE])
except botslib.InMessageFieldError:
txt=botslib.txtexc()
raise botslib.InMessageFieldError(_(u'line:$line pos:$pos. Error:\n$txt'),line=rfield[LIN],pos=rfield[POS],txt=txt)
recorddict[field[ID][:]]=rfield[VALUE][:] #copy string to avoid memory problems
#****************** then: check M/C
for tfield in trecord:
if tfield[ISFIELD]: #tfield is normal field (not a composite)
if tfield[MANDATORY]==u'M' and tfield[ID] not in recorddict:
raise botslib.InMessageError(_(u'line:$line mandatory field "$field" not in record "$record".'),line=recordEdiFile[0][LIN],field=tfield[ID],record=self._striprecord(recordEdiFile))
else:
compositefilled = False
for sfield in tfield[SUBFIELDS]: #t[2]: subfields in grammar
if sfield[ID] in recorddict:
compositefilled = True
break
if compositefilled:
for sfield in tfield[SUBFIELDS]: #t[2]: subfields in grammar
if sfield[MANDATORY]==u'M' and sfield[ID] not in recorddict:
raise botslib.InMessageError(_(u'line:$line mandatory subfield "$field" not in composite, record "$record".'),line=recordEdiFile[0][LIN],field=sfield[ID],record=self._striprecord(recordEdiFile))
if not compositefilled and tfield[MANDATORY]==u'M':
raise botslib.InMessageError(_(u'line:$line mandatory composite "$field" not in record "$record".'),line=recordEdiFile[0][LIN],field=tfield[ID],record=self._striprecord(recordEdiFile))
return recorddict
class csv(var):
''' class for ediobjects with Comma Separated Values'''
def _lex(self):
super(csv,self)._lex()
if self.ta_info['skip_firstline']: #if first line for CSV should be skipped (contains field names)
del self.records[0]
if self.ta_info['noBOTSID']: #if read records contain no BOTSID: add it
botsid = self.defmessage.structure[0][ID] #add the recordname as BOTSID
for record in self.records:
record[0:0]=[{VALUE: botsid, POS: 0, LIN: 0, SFIELD: False}]
class edifact(var):
''' class for edifact inmessage objects.'''
def _readcontent_edifile(self):
''' read content of edi file in memory.
For edifact: not unicode. after sniffing unicode is used to check charset (UNOA etc)
In sniff: determine charset; then decode according to charset
'''
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
self.rawinput = botslib.readdata(filename=self.ta_info['filename'],errors=self.ta_info['checkcharsetin'])
def _sniff(self):
''' examine a read file for syntax parameters and correctness of protocol
eg parse UNA, find UNB, get charset and version
'''
#goto char that is alphanumeric
for count,c in enumerate(self.rawinput):
if c.isalnum():
break
else:
raise botslib.InMessageError(_(u'edi file only contains whitespace.'))
if self.rawinput[count:count+3] == 'UNA':
unacharset=True
self.ta_info['sfield_sep'] = self.rawinput[count+3]
self.ta_info['field_sep'] = self.rawinput[count+4]
self.ta_info['decimaal'] = self.rawinput[count+5]
self.ta_info['escape'] = self.rawinput[count+6]
self.ta_info['reserve'] = '' #self.rawinput[count+7] #for now: no support of repeating dataelements
self.ta_info['record_sep'] = self.rawinput[count+8]
#goto char that is alphanumeric
for count2,c in enumerate(self.rawinput[count+9:]):
if c.isalnum():
break
self.rawinput = self.rawinput[count+count2+9:] #here the interchange should start; UNA is no longer needed
else:
unacharset=False
self.rawinput = self.rawinput[count:] #here the interchange should start
if self.rawinput[:3] != 'UNB':
raise botslib.InMessageError(_(u'No "UNB" at the start of file. Maybe not edifact.'))
self.ta_info['charset'] = self.rawinput[4:8]
self.ta_info['version'] = self.rawinput[9:10]
if not unacharset:
if self.rawinput[3:4]=='+' and self.rawinput[8:9]==':': #assume standard separators.
self.ta_info['sfield_sep'] = ':'
self.ta_info['field_sep'] = '+'
self.ta_info['decimaal'] = '.'
self.ta_info['escape'] = '?'
self.ta_info['reserve'] = '' #for now: no support of repeating dataelements
self.ta_info['record_sep'] = "'"
elif self.rawinput[3:4]=='\x1D' and self.rawinput[8:9]=='\x1F': #check if UNOB separators are used
self.ta_info['sfield_sep'] = '\x1F'
self.ta_info['field_sep'] = '\x1D'
self.ta_info['decimaal'] = '.'
self.ta_info['escape'] = ''
self.ta_info['reserve'] = '' #for now: no support of repeating dataelements
self.ta_info['record_sep'] = '\x1C'
else:
raise botslib.InMessageError(_(u'Incoming edi file uses non-standard separators - should use UNA.'))
try:
self.rawinput = self.rawinput.decode(self.ta_info['charset'],self.ta_info['checkcharsetin'])
except LookupError:
raise botslib.InMessageError(_(u'Incoming edi file has unknown charset "$charset".'),charset=self.ta_info['charset'])
except UnicodeDecodeError, flup:
raise botslib.InMessageError(_(u'not allowed chars in incoming edi file (for translation) at/after filepos: $content'),content=flup[2])
def checkenvelope(self):
self.confirmationlist = [] #information about the edifact file for confirmation/CONTRL; for edifact this is done per interchange (UNB-UNZ)
for nodeunb in self.getloop({'BOTSID':'UNB'}):
botsglobal.logmap.debug(u'Start parsing edifact envelopes')
sender = nodeunb.get({'BOTSID':'UNB','S002.0004':None})
receiver = nodeunb.get({'BOTSID':'UNB','S003.0010':None})
UNBreference = nodeunb.get({'BOTSID':'UNB','0020':None})
UNZreference = nodeunb.get({'BOTSID':'UNB'},{'BOTSID':'UNZ','0020':None})
if UNBreference != UNZreference:
raise botslib.InMessageError(_(u'UNB-reference is "$UNBreference"; should be equal to UNZ-reference "$UNZreference".'),UNBreference=UNBreference,UNZreference=UNZreference)
UNZcount = nodeunb.get({'BOTSID':'UNB'},{'BOTSID':'UNZ','0036':None})
messagecount = len(nodeunb.children) - 1
if int(UNZcount) != messagecount:
raise botslib.InMessageError(_(u'Count in messages in UNZ is $UNZcount; should be equal to number of messages $messagecount.'),UNZcount=UNZcount,messagecount=messagecount)
self.confirmationlist.append({'UNBreference':UNBreference,'UNZcount':UNZcount,'sender':sender,'receiver':receiver,'UNHlist':[]}) #gather information about functional group (GS-GE)
for nodeunh in nodeunb.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
UNHtype = nodeunh.get({'BOTSID':'UNH','S009.0065':None})
UNHversion = nodeunh.get({'BOTSID':'UNH','S009.0052':None})
UNHrelease = nodeunh.get({'BOTSID':'UNH','S009.0054':None})
UNHcontrollingagency = nodeunh.get({'BOTSID':'UNH','S009.0051':None})
UNHassociationassigned = nodeunh.get({'BOTSID':'UNH','S009.0057':None})
UNHreference = nodeunh.get({'BOTSID':'UNH','0062':None})
UNTreference = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0062':None})
if UNHreference != UNTreference:
raise botslib.InMessageError(_(u'UNH-reference is "$UNHreference"; should be equal to UNT-reference "$UNTreference".'),UNHreference=UNHreference,UNTreference=UNTreference)
UNTcount = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0074':None})
segmentcount = nodeunh.getcount()
if int(UNTcount) != segmentcount:
raise botslib.InMessageError(_(u'Segmentcount in UNT is $UNTcount; should be equal to number of segments $segmentcount.'),UNTcount=UNTcount,segmentcount=segmentcount)
self.confirmationlist[-1]['UNHlist'].append({'UNHreference':UNHreference,'UNHtype':UNHtype,'UNHversion':UNHversion,'UNHrelease':UNHrelease,'UNHcontrollingagency':UNHcontrollingagency,'UNHassociationassigned':UNHassociationassigned}) #add info per message to interchange
for nodeung in nodeunb.getloop({'BOTSID':'UNB'},{'BOTSID':'UNG'}):
UNGreference = nodeung.get({'BOTSID':'UNG','0048':None})
UNEreference = nodeung.get({'BOTSID':'UNG'},{'BOTSID':'UNE','0048':None})
if UNGreference != UNEreference:
raise botslib.InMessageError(_(u'UNG-reference is "$UNGreference"; should be equal to UNE-reference "$UNEreference".'),UNGreference=UNGreference,UNEreference=UNEreference)
UNEcount = nodeung.get({'BOTSID':'UNG'},{'BOTSID':'UNE','0060':None})
groupcount = len(nodeung.children) - 1
if int(UNEcount) != groupcount:
raise botslib.InMessageError(_(u'Groupcount in UNE is $UNEcount; should be equal to number of groups $groupcount.'),UNEcount=UNEcount,groupcount=groupcount)
for nodeunh in nodeung.getloop({'BOTSID':'UNG'},{'BOTSID':'UNH'}):
UNHreference = nodeunh.get({'BOTSID':'UNH','0062':None})
UNTreference = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0062':None})
if UNHreference != UNTreference:
raise botslib.InMessageError(_(u'UNH-reference is "$UNHreference"; should be equal to UNT-reference "$UNTreference".'),UNHreference=UNHreference,UNTreference=UNTreference)
UNTcount = nodeunh.get({'BOTSID':'UNH'},{'BOTSID':'UNT','0074':None})
segmentcount = nodeunh.getcount()
if int(UNTcount) != segmentcount:
raise botslib.InMessageError(_(u'Segmentcount in UNT is $UNTcount; should be equal to number of segments $segmentcount.'),UNTcount=UNTcount,segmentcount=segmentcount)
botsglobal.logmap.debug(u'Parsing edifact envelopes is OK')
def handleconfirm(self,ta_fromfile,error):
''' end of edi file handling.
eg writing of confirmations etc.
send CONTRL messages
parameter 'error' is not used
'''
#filter the confirmationlist
tmpconfirmationlist = []
for confirmation in self.confirmationlist:
tmpmessagelist = []
for message in confirmation['UNHlist']:
if message['UNHtype'] == 'CONTRL': #do not generate CONTRL for a CONTRL message
continue
if botslib.checkconfirmrules('send-edifact-CONTRL',idroute=self.ta_info['idroute'],idchannel=self.ta_info['fromchannel'],
topartner=confirmation['sender'],frompartner=confirmation['receiver'],
editype='edifact',messagetype=message['UNHtype']):
tmpmessagelist.append(message)
confirmation['UNHlist'] = tmpmessagelist
if not tmpmessagelist: #if no messages/transactions in interchange
continue
tmpconfirmationlist.append(confirmation)
self.confirmationlist = tmpconfirmationlist
for confirmation in self.confirmationlist:
reference=str(botslib.unique('messagecounter'))
ta_confirmation = ta_fromfile.copyta(status=TRANSLATED,reference=reference)
filename = str(ta_confirmation.idta)
out = outmessage.outmessage_init(editype='edifact',messagetype='CONTRL22UNEAN002',filename=filename) #make outmessage object
out.ta_info['frompartner']=confirmation['receiver']
out.ta_info['topartner']=confirmation['sender']
out.put({'BOTSID':'UNH','0062':reference,'S009.0065':'CONTRL','S009.0052':'2','S009.0054':'2','S009.0051':'UN','S009.0057':'EAN002'})
out.put({'BOTSID':'UNH'},{'BOTSID':'UCI','0083':'8','S002.0004':confirmation['sender'],'S003.0010':confirmation['sender'],'0020':confirmation['UNBreference']}) #8: interchange received
for message in confirmation['UNHlist']:
lou = out.putloop({'BOTSID':'UNH'},{'BOTSID':'UCM'})
lou.put({'BOTSID':'UCM','0083':'7','S009.0065':message['UNHtype'],'S009.0052':message['UNHversion'],'S009.0054':message['UNHrelease'],'S009.0051':message['UNHcontrollingagency'],'0062':message['UNHreference']})
lou.put({'BOTSID':'UCM','S009.0057':message['UNHassociationassigned']})
out.put({'BOTSID':'UNH'},{'BOTSID':'UNT','0074':out.getcount()+1,'0062':reference}) #last line (counts the segments produced in out-message)
out.writeall() #write tomessage (result of translation)
botsglobal.logger.debug(u'Send edifact confirmation (CONTRL) route "%s" fromchannel "%s" frompartner "%s" topartner "%s".',
self.ta_info['idroute'],self.ta_info['fromchannel'],confirmation['receiver'],confirmation['sender'])
self.confirminfo = dict(confirmtype='send-edifact-CONTRL',confirmed=True,confirmasked = True,confirmidta=ta_confirmation.idta) #this info is used in transform.py to update the ta.....ugly...
ta_confirmation.update(statust=OK,**out.ta_info) #update ta for confirmation
class x12(var):
''' class for edifact inmessage objects.'''
def _getmessagetype(self,messagetypefromsubtranslation,inode):
if messagetypefromsubtranslation is None:
return None
return messagetypefromsubtranslation + inode.record['GS08']
def _sniff(self):
''' examine a file for syntax parameters and correctness of protocol
eg parse ISA, get charset and version
'''
#goto char that is not whitespace
for count,c in enumerate(self.rawinput):
if not c.isspace():
self.rawinput = self.rawinput[count:] #here the interchange should start
break
else:
raise botslib.InMessageError(_(u'edifile only contains whitespace.'))
if self.rawinput[:3] != 'ISA':
raise botslib.InMessageError(_(u'expect "ISA", found "$content". Probably no x12?'),content=self.rawinput[:7])
count = 0
for c in self.rawinput[:120]:
if c in '\r\n' and count!=105:
continue
count +=1
if count==4:
self.ta_info['field_sep'] = c
elif count==105:
self.ta_info['sfield_sep'] = c
elif count==106:
self.ta_info['record_sep'] = c
break
# ISA-version: if <004030: SHOULD use repeating element?
self.ta_info['reserve']=''
self.ta_info['skip_char'] = self.ta_info['skip_char'].replace(self.ta_info['record_sep'],'') #if <CR> is segment terminator: cannot be in the skip_char-string!
#more ISA's in file: find IEA+
def checkenvelope(self):
''' check envelopes, gather information to generate 997 '''
self.confirmationlist = [] #information about the x12 file for confirmation/997; for x12 this is done per functional group
#~ self.root.display()
for nodeisa in self.getloop({'BOTSID':'ISA'}):
botsglobal.logmap.debug(u'Start parsing X12 envelopes')
sender = nodeisa.get({'BOTSID':'ISA','ISA06':None})
receiver = nodeisa.get({'BOTSID':'ISA','ISA08':None})
ISAreference = nodeisa.get({'BOTSID':'ISA','ISA13':None})
IEAreference = nodeisa.get({'BOTSID':'ISA'},{'BOTSID':'IEA','IEA02':None})
if ISAreference != IEAreference:
raise botslib.InMessageError(_(u'ISA-reference is "$ISAreference"; should be equal to IEA-reference "$IEAreference".'),ISAreference=ISAreference,IEAreference=IEAreference)
IEAcount = nodeisa.get({'BOTSID':'ISA'},{'BOTSID':'IEA','IEA01':None})
groupcount = nodeisa.getcountoccurrences({'BOTSID':'ISA'},{'BOTSID':'GS'})
if int(IEAcount) != groupcount:
raise botslib.InMessageError(_(u'Count in IEA-IEA01 is $IEAcount; should be equal to number of groups $groupcount.'),IEAcount=IEAcount,groupcount=groupcount)
for nodegs in nodeisa.getloop({'BOTSID':'ISA'},{'BOTSID':'GS'}):
GSqualifier = nodegs.get({'BOTSID':'GS','GS01':None})
GSreference = nodegs.get({'BOTSID':'GS','GS06':None})
GEreference = nodegs.get({'BOTSID':'GS'},{'BOTSID':'GE','GE02':None})
if GSreference != GEreference:
raise botslib.InMessageError(_(u'GS-reference is "$GSreference"; should be equal to GE-reference "$GEreference".'),GSreference=GSreference,GEreference=GEreference)
GEcount = nodegs.get({'BOTSID':'GS'},{'BOTSID':'GE','GE01':None})
messagecount = len(nodegs.children) - 1
if int(GEcount) != messagecount:
raise botslib.InMessageError(_(u'Count in GE-GE01 is $GEcount; should be equal to number of transactions: $messagecount.'),GEcount=GEcount,messagecount=messagecount)
self.confirmationlist.append({'GSqualifier':GSqualifier,'GSreference':GSreference,'GEcount':GEcount,'sender':sender,'receiver':receiver,'STlist':[]}) #gather information about functional group (GS-GE)
for nodest in nodegs.getloop({'BOTSID':'GS'},{'BOTSID':'ST'}):
STqualifier = nodest.get({'BOTSID':'ST','ST01':None})
STreference = nodest.get({'BOTSID':'ST','ST02':None})
SEreference = nodest.get({'BOTSID':'ST'},{'BOTSID':'SE','SE02':None})
#referencefields are numerical; should I compare values??
if STreference != SEreference:
raise botslib.InMessageError(_(u'ST-reference is "$STreference"; should be equal to SE-reference "$SEreference".'),STreference=STreference,SEreference=SEreference)
SEcount = nodest.get({'BOTSID':'ST'},{'BOTSID':'SE','SE01':None})
segmentcount = nodest.getcount()
if int(SEcount) != segmentcount:
raise botslib.InMessageError(_(u'Count in SE-SE01 is $SEcount; should be equal to number of segments $segmentcount.'),SEcount=SEcount,segmentcount=segmentcount)
self.confirmationlist[-1]['STlist'].append({'STreference':STreference,'STqualifier':STqualifier}) #add info per message to functional group
botsglobal.logmap.debug(u'Parsing X12 envelopes is OK')
def handleconfirm(self,ta_fromfile,error):
''' end of edi file handling.
eg writing of confirmations etc.
send 997 messages
parameter 'error' is not used
'''
#filter the confirmationlist
tmpconfirmationlist = []
for confirmation in self.confirmationlist:
if confirmation['GSqualifier'] == 'FA': #do not generate 997 for 997
continue
tmpmessagelist = []
for message in confirmation['STlist']:
if botslib.checkconfirmrules('send-x12-997',idroute=self.ta_info['idroute'],idchannel=self.ta_info['fromchannel'],
topartner=confirmation['sender'],frompartner=confirmation['receiver'],
editype='x12',messagetype=message['STqualifier']):
tmpmessagelist.append(message)
confirmation['STlist'] = tmpmessagelist
if not tmpmessagelist: #if no messages/transactions in GS-GE
continue
tmpconfirmationlist.append(confirmation)
self.confirmationlist = tmpconfirmationlist
for confirmation in self.confirmationlist:
reference=str(botslib.unique('messagecounter'))
ta_confirmation = ta_fromfile.copyta(status=TRANSLATED,reference=reference)
filename = str(ta_confirmation.idta)
out = outmessage.outmessage_init(editype='x12',messagetype='997004010',filename=filename) #make outmessage object
out.ta_info['frompartner']=confirmation['receiver']
out.ta_info['topartner']=confirmation['sender']
out.put({'BOTSID':'ST','ST01':'997','ST02':reference})
out.put({'BOTSID':'ST'},{'BOTSID':'AK1','AK101':confirmation['GSqualifier'],'AK102':confirmation['GSreference']})
out.put({'BOTSID':'ST'},{'BOTSID':'AK9','AK901':'A','AK902':confirmation['GEcount'],'AK903':confirmation['GEcount'],'AK904':confirmation['GEcount']})
for message in confirmation['STlist']:
lou = out.putloop({'BOTSID':'ST'},{'BOTSID':'AK2'})
lou.put({'BOTSID':'AK2','AK201':message['STqualifier'],'AK202':message['STreference']})
lou.put({'BOTSID':'AK2'},{'BOTSID':'AK5','AK501':'A'})
out.put({'BOTSID':'ST'},{'BOTSID':'SE','SE01':out.getcount()+1,'SE02':reference}) #last line (counts the segments produced in out-message)
out.writeall() #write tomessage (result of translation)
botsglobal.logger.debug(u'Send x12 confirmation (997) route "%s" fromchannel "%s" frompartner "%s" topartner "%s".',
self.ta_info['idroute'],self.ta_info['fromchannel'],confirmation['receiver'],confirmation['sender'])
self.confirminfo = dict(confirmtype='send-x12-997',confirmed=True,confirmasked = True,confirmidta=ta_confirmation.idta) #this info is used in transform.py to update the ta.....ugly...
ta_confirmation.update(statust=OK,**out.ta_info) #update ta for confirmation
class tradacoms(var):
def checkenvelope(self):
for nodeSTX in self.getloop({'BOTSID':'STX'}):
botsglobal.logmap.debug(u'Start parsing tradacoms envelopes')
ENDcount = nodeSTX.get({'BOTSID':'STX'},{'BOTSID':'END','NMST':None})
messagecount = len(nodeSTX.children) - 1
if int(ENDcount) != messagecount:
raise botslib.InMessageError(_(u'Count in messages in END is $ENDcount; should be equal to number of messages $messagecount'),ENDcount=ENDcount,messagecount=messagecount)
firstmessage = True
for nodeMHD in nodeSTX.getloop({'BOTSID':'STX'},{'BOTSID':'MHD'}):
if firstmessage: #
nodeSTX.queries = {'messagetype':nodeMHD.queries['messagetype']}
firstmessage = False
MTRcount = nodeMHD.get({'BOTSID':'MHD'},{'BOTSID':'MTR','NOSG':None})
segmentcount = nodeMHD.getcount()
if int(MTRcount) != segmentcount:
raise botslib.InMessageError(_(u'Segmentcount in MTR is $MTRcount; should be equal to number of segments $segmentcount'),MTRcount=MTRcount,segmentcount=segmentcount)
botsglobal.logmap.debug(u'Parsing tradacoms envelopes is OK')
class xml(var):
''' class for ediobjects in XML. Uses ElementTree'''
def initfromfile(self):
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
filename=botslib.abspathdata(self.ta_info['filename'])
if self.ta_info['messagetype'] == 'mailbag':
''' the messagetype is not know.
bots reads file usersys/grammars/xml/mailbag.py, and uses 'mailbagsearch' to determine the messagetype
mailbagsearch is a list, containing python dicts. Dict consist of 'xpath', 'messagetype' and (optionally) 'content'.
'xpath' is a xpath to use on xml-file (using elementtree xpath functionality)
if found, and 'content' in the dict; if 'content' is equal to value found by xpath-search, then set messagetype.
if found, and no 'content' in the dict; set messagetype.
'''
try:
module,grammarname = botslib.botsimport('grammars','xml.mailbag')
mailbagsearch = getattr(module, 'mailbagsearch')
except AttributeError:
botsglobal.logger.error(u'missing mailbagsearch in mailbag definitions for xml.')
raise
except ImportError:
botsglobal.logger.error(u'missing mailbag definitions for xml, should be there.')
raise
parser = ET.XMLParser()
try:
extra_character_entity = getattr(module, 'extra_character_entity')
for key,value in extra_character_entity.items():
parser.entity[key] = value
except AttributeError:
pass #there is no extra_character_entity in the mailbag definitions, is OK.
etree = ET.ElementTree() #ElementTree: lexes, parses, makes etree; etree is quite similar to bots-node trees but conversion is needed
etreeroot = etree.parse(filename, parser)
for item in mailbagsearch:
if 'xpath' not in item or 'messagetype' not in item:
raise botslib.InMessageError(_(u'invalid search parameters in xml mailbag.'))
#~ print 'search' ,item
found = etree.find(item['xpath'])
if found is not None:
#~ print ' found'
if 'content' in item and found.text != item['content']:
continue
self.ta_info['messagetype'] = item['messagetype']
#~ print ' found right messagedefinition'
#~ continue
break
else:
raise botslib.InMessageError(_(u'could not find right xml messagetype for mailbag.'))
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by sniffing
else:
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by sniffing
parser = ET.XMLParser()
for key,value in self.ta_info['extra_character_entity'].items():
parser.entity[key] = value
etree = ET.ElementTree() #ElementTree: lexes, parses, makes etree; etree is quite similar to bots-node trees but conversion is needed
etreeroot = etree.parse(filename, parser)
self.stack = []
self.root = self.etree2botstree(etreeroot) #convert etree to bots-nodes-tree
self.normalisetree(self.root)
def etree2botstree(self,xmlnode):
self.stack.append(xmlnode.tag)
newnode = node.Node(record=self.etreenode2botstreenode(xmlnode))
for xmlchildnode in xmlnode: #for every node in mpathtree
if self.isfield(xmlchildnode): #if no child entities: treat as 'field': this misses xml where attributes are used as fields....testing for repeating is no good...
if xmlchildnode.text and not xmlchildnode.text.isspace(): #skip empty xml entity
newnode.record[xmlchildnode.tag]=xmlchildnode.text #add as a field
hastxt = True
else:
hastxt = False
for key,value in xmlchildnode.items(): #convert attributes to fields.
if not hastxt:
newnode.record[xmlchildnode.tag]='' #add empty content
hastxt = True
newnode.record[xmlchildnode.tag + self.ta_info['attributemarker'] + key]=value #add as a field
else: #xmlchildnode is a record
newnode.append(self.etree2botstree(xmlchildnode)) #add as a node/record
#~ if botsglobal.ini.getboolean('settings','readrecorddebug',False):
#~ botsglobal.logger.debug('read record "%s":',newnode.record['BOTSID'])
#~ for key,value in newnode.record.items():
#~ botsglobal.logger.debug(' "%s" : "%s"',key,value)
self.stack.pop()
#~ print self.stack
return newnode
def etreenode2botstreenode(self,xmlnode):
''' build a dict from xml-node'''
build = dict((xmlnode.tag + self.ta_info['attributemarker'] + key,value) for key,value in xmlnode.items()) #convert attributes to fields.
build['BOTSID']=xmlnode.tag #'record' tag
if xmlnode.text and not xmlnode.text.isspace():
build['BOTSCONTENT']=xmlnode.text
return build
def isfield(self,xmlchildnode):
''' check if xmlchildnode is field (or record)'''
#~ print 'examine record in stack',xmlchildnode.tag,self.stack
str_recordlist = self.defmessage.structure
for record in self.stack: #find right level in structure
for str_record in str_recordlist:
#~ print ' find right level comparing',record,str_record[0]
if record == str_record[0]:
if 4 not in str_record: #structure record contains no level: must be an attribute
return True
str_recordlist = str_record[4]
break
else:
raise botslib.InMessageError(_(u'Unknown XML-tag in "$record".'),record=record)
for str_record in str_recordlist: #see if xmlchildnode is in structure
#~ print ' is xmlhildnode in this level comparing',xmlchildnode.tag,str_record[0]
if xmlchildnode.tag == str_record[0]:
#~ print 'found'
return False
#xml tag not found in structure: so must be field; validity is check later on with grammar
if len(xmlchildnode)==0:
return True
return False
class xmlnocheck(xml):
''' class for ediobjects in XML. Uses ElementTree'''
def normalisetree(self,node):
pass
def isfield(self,xmlchildnode):
if len(xmlchildnode)==0:
return True
return False
class json(var):
def initfromfile(self):
self.defmessage = grammar.grammarread(self.ta_info['editype'],self.ta_info['messagetype'])
botslib.updateunlessset(self.ta_info,self.defmessage.syntax) #write values from grammar to self.ta_info - unless these values are already set eg by sniffing
self._readcontent_edifile()
jsonobject = simplejson.loads(self.rawinput)
del self.rawinput
if isinstance(jsonobject,list):
self.root=node.Node() #initialise empty node.
self.root.children = self.dojsonlist(jsonobject,self.getrootID()) #fill root with children
for child in self.root.children:
if not child.record: #sanity test: the children must have content
raise botslib.InMessageError(_(u'no usable content.'))
self.normalisetree(child)
elif isinstance(jsonobject,dict):
if len(jsonobject)==1 and isinstance(jsonobject.values()[0],dict):
# best structure: {rootid:{id2:<dict, list>}}
self.root = self.dojsonobject(jsonobject.values()[0],jsonobject.keys()[0])
elif len(jsonobject)==1 and isinstance(jsonobject.values()[0],list) :
#root dict has no name; use value from grammar for rootID; {id2:<dict, list>}
self.root=node.Node(record={'BOTSID': self.getrootID()}) #initialise empty node.
self.root.children = self.dojsonlist(jsonobject.values()[0],jsonobject.keys()[0])
else:
#~ print self.getrootID()
self.root = self.dojsonobject(jsonobject,self.getrootID())
#~ print self.root
if not self.root:
raise botslib.InMessageError(_(u'no usable content.'))
self.normalisetree(self.root)
else:
#root in JSON is neither dict or list.
raise botslib.InMessageError(_(u'Content must be a "list" or "object".'))
def getrootID(self):
return self.defmessage.structure[0][ID]
def dojsonlist(self,jsonobject,name):
lijst=[] #initialise empty list, used to append a listof (converted) json objects
for i in jsonobject:
if isinstance(i,dict): #check list item is dict/object
newnode = self.dojsonobject(i,name)
if newnode:
lijst.append(newnode)
elif self.ta_info['checkunknownentities']:
raise botslib.InMessageError(_(u'List content in must be a "object".'))
return lijst
def dojsonobject(self,jsonobject,name):
thisnode=node.Node(record={}) #initialise empty node.
for key,value in jsonobject.items():
if value is None:
continue
elif isinstance(value,basestring): #json field; map to field in node.record
thisnode.record[key]=value
elif isinstance(value,dict):
newnode = self.dojsonobject(value,key)
if newnode:
thisnode.append(newnode)
elif isinstance(value,list):
thisnode.children.extend(self.dojsonlist(value,key))
elif isinstance(value,(int,long,float)): #json field; map to field in node.record
thisnode.record[key]=str(value)
else:
if self.ta_info['checkunknownentities']:
raise botslib.InMessageError(_(u'Key "$key" value "$value": is not string, list or dict.'),key=key,value=value)
thisnode.record[key]=str(value)
if not thisnode.record and not thisnode.children:
return None #node is empty...
thisnode.record['BOTSID']=name
return thisnode
class jsonnocheck(json):
def normalisetree(self,node):
pass
def getrootID(self):
return self.ta_info['defaultBOTSIDroot'] #as there is no structure in grammar, use value form syntax.
class database(jsonnocheck):
pass
class db(Inmessage):
''' the database-object is unpickled, and passed to the mapping script.
'''
def initfromfile(self):
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
f = botslib.opendata(filename=self.ta_info['filename'],mode='rb')
self.root = pickle.load(f)
f.close()
def nextmessage(self):
yield self
class raw(Inmessage):
''' the file object is just read and passed to the mapping script.
'''
def initfromfile(self):
botsglobal.logger.debug(u'read edi file "%s".',self.ta_info['filename'])
f = botslib.opendata(filename=self.ta_info['filename'],mode='rb')
self.root = f.read()
f.close()
def nextmessage(self):
yield self
| Python |
import copy
from django.utils.translation import ugettext as _
import botslib
import botsglobal
from botsconfig import *
def grammarread(editype,grammarname):
''' dispatch function for class Grammar or subclass
read whole grammar
'''
try:
classtocall = globals()[editype]
except KeyError:
raise botslib.GrammarError(_(u'Read grammar for editype "$editype" messagetype "$messagetype", but editype is unknown.'), editype=editype, messagetype=grammarname)
terug = classtocall('grammars',editype,grammarname)
terug.initsyntax(includedefault=True)
terug.initrestofgrammar()
return terug
def syntaxread(soortpythonfile,editype,grammarname):
''' dispatch function for class Grammar or subclass
read only grammar
'''
try:
classtocall = globals()[editype]
except KeyError:
raise botslib.GrammarError(_(u'Read grammar for type "$soort" editype "$editype" messagetype "$messagetype", but editype is unknown.'), soort=soortpythonfile,editype=editype, messagetype=grammarname)
terug = classtocall(soortpythonfile,editype,grammarname)
terug.initsyntax(includedefault=False)
return terug
class Grammar(object):
''' Class for translation grammar. The grammar is used in reading or writing an edi file.
Description of the grammar file: see user manual.
The grammar is read from the grammar file.
Grammar file has several grammar parts , eg 'structure'and 'recorddefs'.
every grammar part is in a module is either the grammar part itself or a import from another module.
every module is read once, (default python import-machinery).
The information in a grammar is checked and manipulated.
structure of self.grammar:
is a list of dict
attributes of dict: see header.py
- ID record id
- MIN min #occurences record or group
- MAX max #occurences record of group
- COUNT added after read
- MPATH mpath of record (only record-ids). added after read
- FIELDS tuple of the fields in record. Added ather read from separate record.py-file
- LEVEL child-records
structure of fields:
fields is tuple of (field or subfield)
field is tuple of (ID, MANDATORY, LENGTH, FORMAT)
subfield is tuple of (ID, MANDATORY, tuple of fields)
if a structure or recorddef has been read, Bots remembers this and skip most of the checks.
'''
_checkstructurerequired=True
def __init__(self,soortpythonfile,editype,grammarname):
self.module,self.grammarname = botslib.botsimport(soortpythonfile,editype + '.' + grammarname)
def initsyntax(self,includedefault):
''' Update default syntax from class with syntax read from grammar. '''
if includedefault:
self.syntax = copy.deepcopy(self.__class__.defaultsyntax) #copy syntax from class data
else:
self.syntax = {}
try:
syntaxfromgrammar = getattr(self.module, 'syntax')
except AttributeError:
pass #there is no syntax in the grammar, is OK.
else:
if not isinstance(syntaxfromgrammar,dict):
raise botslib.GrammarError(_(u'Grammar "$grammar": syntax is not a dict{}.'),grammar=self.grammarname)
self.syntax.update(syntaxfromgrammar)
def initrestofgrammar(self):
try:
self.nextmessage = getattr(self.module, 'nextmessage')
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
self.nextmessage = None
try:
self.nextmessage2 = getattr(self.module, 'nextmessage2')
if self.nextmessage is None:
raise botslib.GrammarError(_(u'Grammar "$grammar": if nextmessage2: nextmessage has to be used.'),grammar=self.grammarname)
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
self.nextmessage2 = None
try:
self.nextmessageblock = getattr(self.module, 'nextmessageblock')
if self.nextmessage:
raise botslib.GrammarError(_(u'Grammar "$grammar": nextmessageblock and nextmessage not both allowed.'),grammar=self.grammarname)
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
self.nextmessageblock = None
if self._checkstructurerequired:
try:
self._dostructure()
except AttributeError: #if grammarpart does not exist set to None; test required grammarpart elsewhere
raise botslib.GrammarError(_(u'Grammar "$grammar": no structure, is required.'),grammar=self.grammarname)
except:
self.structurefromgrammar[0]['error'] = True #mark the structure as having errors
raise
try:
self._dorecorddefs()
except:
self.recorddefs['BOTS_1$@#%_error'] = True #mark structure has been read with errors
raise
else:
self.recorddefs['BOTS_1$@#%_error'] = False #mark structure has been read and checked
self.structure = copy.deepcopy(self.structurefromgrammar) #(deep)copy structure for use in translation (in translation values are changed, so use a copy)
self._checkbotscollision(self.structure)
self._linkrecorddefs2structure(self.structure)
def _dorecorddefs(self):
''' 1. check the recorddefinitions for validity.
2. adapt in field-records: normalise length lists, set bool ISFIELD, etc
'''
try:
self.recorddefs = getattr(self.module, 'recorddefs')
except AttributeError:
raise botslib.GrammarError(_(u'Grammar "$grammar": no recorddefs.'),grammar=self.grammarname)
if not isinstance(self.recorddefs,dict):
raise botslib.GrammarError(_(u'Grammar "$grammar": recorddefs is not a dict{}.'),grammar=self.grammarname)
#check if grammar is read & checked earlier in this run. If so, we can skip all checks.
if 'BOTS_1$@#%_error' in self.recorddefs: #if checked before
if self.recorddefs['BOTS_1$@#%_error']: #if grammar had errors
raise botslib.GrammarError(_(u'Grammar "$grammar" has error that is already reported in this run.'),grammar=self.grammarname)
return #no error, skip checks
for recordID ,fields in self.recorddefs.iteritems():
if not isinstance(recordID,basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": is not a string.'),grammar=self.grammarname,record=recordID)
if not recordID:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": recordID with empty string.'),grammar=self.grammarname,record=recordID)
if not isinstance(fields,list):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": no correct fields found.'),grammar=self.grammarname,record=recordID)
if isinstance(self,(xml,json)):
if len (fields) < 1:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": too few fields.'),grammar=self.grammarname,record=recordID)
else:
if len (fields) < 2:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": too few fields.'),grammar=self.grammarname,record=recordID)
hasBOTSID = False #to check if BOTSID is present
fieldnamelist = [] #to check for double fieldnames
for field in fields:
self._checkfield(field,recordID)
if not field[ISFIELD]: # if composite
for sfield in field[SUBFIELDS]:
self._checkfield(sfield,recordID)
if sfield[ID] in fieldnamelist:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": field "$field" appears twice. Field names should be unique within a record.'),grammar=self.grammarname,record=recordID,field=sfield[ID])
fieldnamelist.append(sfield[ID])
else:
if field[ID] == 'BOTSID':
hasBOTSID = True
if field[ID] in fieldnamelist:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": field "$field" appears twice. Field names should be unique within a record.'),grammar=self.grammarname,record=recordID,field=field[ID])
fieldnamelist.append(field[ID])
if not hasBOTSID: #there is no field 'BOTSID' in record
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record": no field BOTSID.'),grammar=self.grammarname,record=recordID)
if self.syntax['noBOTSID'] and len(self.recorddefs) != 1:
raise botslib.GrammarError(_(u'Grammar "$grammar": if syntax["noBOTSID"]: there can be only one record in recorddefs.'),grammar=self.grammarname)
if self.nextmessageblock is not None and len(self.recorddefs) != 1:
raise botslib.GrammarError(_(u'Grammar "$grammar": if nextmessageblock: there can be only one record in recorddefs.'),grammar=self.grammarname)
def _checkfield(self,field,recordID):
#'normalise' field: make list equal length
if len(field) == 3: # that is: composite
field +=[None,False,None,None,'A']
elif len(field) == 4: # that is: field (not a composite)
field +=[True,0,0,'A']
elif len(field) == 8: # this happens when there are errors in a table and table is read again
raise botslib.GrammarError(_(u'Grammar "$grammar": error in grammar; error is already reported in this run.'),grammar=self.grammarname)
else:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": list has invalid number of arguments.') ,grammar=self.grammarname,record=recordID,field=field[ID])
if not isinstance(field[ID],basestring) or not field[ID]:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": fieldID has to be a string.'),grammar=self.grammarname,record=recordID,field=field[ID])
if not isinstance(field[MANDATORY],basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": mandatory/conditional has to be a string.'),grammar=self.grammarname,record=recordID,field=field[ID])
if not field[MANDATORY] or field[MANDATORY] not in ['M','C']:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": mandatory/conditional must be "M" or "C".'),grammar=self.grammarname,record=recordID,field=field[ID])
if field[ISFIELD]: # that is: field, and not a composite
#get MINLENGTH (from tuple or if fixed
if isinstance(field[LENGTH],tuple):
if not isinstance(field[LENGTH][0],(int,float)):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": min length "$min" has to be a number.'),grammar=self.grammarname,record=recordID,field=field[ID],min=field[LENGTH])
if not isinstance(field[LENGTH][1],(int,float)):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": max length "$max" has to be a number.'),grammar=self.grammarname,record=recordID,field=field[ID],max=field[LENGTH])
if field[LENGTH][0] > field[LENGTH][1]:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": min length "$min" must be > max length "$max".'),grammar=self.grammarname,record=recordID,field=field[ID],min=field[LENGTH][0],max=field[LENGTH][1])
field[MINLENGTH]=field[LENGTH][0]
field[LENGTH]=field[LENGTH][1]
elif isinstance(field[LENGTH],(int,float)):
if isinstance(self,fixed):
field[MINLENGTH]=field[LENGTH]
else:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": length "$len" has to be number or (min,max).'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH])
if field[LENGTH] < 1:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": length "$len" has to be at least 1.'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH])
if field[MINLENGTH] < 0:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": minlength "$len" has to be at least 0.'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH])
#format
if not isinstance(field[FORMAT],basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": format "$format" has to be a string.'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT])
self._manipulatefieldformat(field,recordID)
if field[BFORMAT] in ['N','I','R']:
if isinstance(field[LENGTH],float):
field[DECIMALS] = int( round((field[LENGTH]-int(field[LENGTH]))*10) ) #fill DECIMALS
field[LENGTH] = int( round(field[LENGTH]))
if field[DECIMALS] >= field[LENGTH]:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": field length "$len" has to be greater that nr of decimals "$decimals".'),grammar=self.grammarname,record=recordID,field=field[ID],len=field[LENGTH],decimals=field[DECIMALS])
if isinstance(field[MINLENGTH],float):
field[MINLENGTH] = int( round(field[MINLENGTH]))
else: #if format 'R', A, D, T
if isinstance(field[LENGTH],float):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": if format "$format", no length "$len".'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT],len=field[LENGTH])
if isinstance(field[MINLENGTH],float):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": if format "$format", no minlength "$len".'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT],len=field[MINLENGTH])
else: #check composite
if not isinstance(field[SUBFIELDS],list):
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": is a composite field, has to have subfields.'),grammar=self.grammarname,record=recordID,field=field[ID])
if len(field[SUBFIELDS]) < 2:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field" has < 2 sfields.'),grammar=self.grammarname,record=recordID,field=field[ID])
def _linkrecorddefs2structure(self,structure):
''' recursive
for each record in structure: add the pointer to the right recorddefinition.
'''
for i in structure:
try:
i[FIELDS] = self.recorddefs[i[ID]]
except KeyError:
raise botslib.GrammarError(_(u'Grammar "$grammar": in recorddef no record "$record".'),grammar=self.grammarname,record=i[ID])
if LEVEL in i:
self._linkrecorddefs2structure(i[LEVEL])
def _dostructure(self):
''' 1. check the structure for validity.
2. adapt in structure: Add keys: mpath, count
3. remember that structure is checked and adapted (so when grammar is read again, no checking/adapt needed)
'''
self.structurefromgrammar = getattr(self.module, 'structure')
if len(self.structurefromgrammar) != 1: #every structure has only 1 root!!
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: only one root record allowed.'),grammar=self.grammarname)
#check if structure is read & checked earlier in this run. If so, we can skip all checks.
if 'error' in self.structurefromgrammar[0]:
pass # grammar has been read before, but there are errors. Do nothing here, same errors will be raised again.
elif MPATH in self.structurefromgrammar[0]:
return # grammar has been red before, with no errors. Do no checks.
self._checkstructure(self.structurefromgrammar,[])
if self.syntax['checkcollision']:
self._checkbackcollision(self.structurefromgrammar)
self._checknestedcollision(self.structurefromgrammar)
def _checkstructure(self,structure,mpath):
''' Recursive
1. Check structure.
2. Add keys: mpath, count
'''
if not isinstance(structure,list):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": not a list.'),grammar=self.grammarname,mpath=mpath)
for i in structure:
if not isinstance(i,dict):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record should be a dict: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if ID not in i:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record without ID: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not isinstance(i[ID],basestring):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": recordID of record is not a string: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not i[ID]:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": recordID of record is empty: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if MIN not in i:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record without MIN: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if MAX not in i:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record without MAX: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not isinstance(i[MIN],int):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record where MIN is not whole number: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if not isinstance(i[MAX],int):
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record where MAX is not whole number: "$record".'),grammar=self.grammarname,mpath=mpath,record=i)
if i[MIN] > i[MAX]:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure, at "$mpath": record where MIN > MAX: "$record".'),grammar=self.grammarname,mpath=mpath,record=str(i)[:100])
i[MPATH]=mpath+[[i[ID]]]
i[COUNT]=0
if LEVEL in i:
self._checkstructure(i[LEVEL],i[MPATH])
def _checkbackcollision(self,structure,collision=None):
''' Recursive.
Check if grammar has collision problem.
A message with collision problems is ambiguous.
'''
headerissave = False
if not collision:
collision=[]
for i in structure:
#~ print 'check back',i[MPATH], 'with',collision
if i[ID] in collision:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: back-collision detected at record "$mpath".'),grammar=self.grammarname,mpath=i[MPATH])
if i[MIN]:
collision = []
headerissave = True
collision.append(i[ID])
if LEVEL in i:
returncollision,returnheaderissave = self._checkbackcollision(i[LEVEL],[i[ID]])
collision += returncollision
if returnheaderissave: #if one of segment(groups) is required, there is always a segment after the header segment; so remove header from nowcollision:
collision.remove(i[ID])
return collision,headerissave #collision is used to update on higher level; cleared indicates the header segment can not collide anymore
def _checkbotscollision(self,structure):
''' Recursive.
Within one level: if twice the same tag: use BOTSIDnr.
'''
collision={}
for i in structure:
if i[ID] in collision:
#~ raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: bots-collision detected at record "$mpath".'),grammar=self.grammarname,mpath=i[MPATH])
i[BOTSIDnr] = str(collision[i[ID]] + 1)
collision[i[ID]] = collision[i[ID]] + 1
else:
i[BOTSIDnr] = '1'
collision[i[ID]] = 1
if LEVEL in i:
self._checkbotscollision(i[LEVEL])
return
def _checknestedcollision(self,structure,collision=None):
''' Recursive.
Check if grammar has collision problem.
A message with collision problems is ambiguous.
'''
if not collision:
levelcollision = []
else:
levelcollision = collision[:]
for i in reversed(structure):
checkthissegment = True
if LEVEL in i:
checkthissegment = self._checknestedcollision(i[LEVEL],levelcollision + [i[ID]])
#~ print 'check nested',checkthissegment, i[MPATH], 'with',levelcollision
if checkthissegment and i[ID] in levelcollision:
raise botslib.GrammarError(_(u'Grammar "$grammar", in structure: nesting collision detected at record "$mpath".'),grammar=self.grammarname,mpath=i[MPATH])
if i[MIN]:
levelcollision = [] #enecessarympty uppercollision
return bool(levelcollision)
def display(self,structure,level=0):
''' Draw grammar, with indentation for levels.
For debugging.
'''
for i in structure:
print 'Record: ',i[MPATH],i
for field in i[FIELDS]:
print ' Field: ',field
if LEVEL in i:
self.display(i[LEVEL],level+1)
#bots interpretats the format from the grammer; left side are the allowed values; right side are the internal forams bots uses.
#the list directly below are the default values for the formats, subclasses can have their own list.
#this makes it possible to use x12-formats for x12, edifact-formats for edifact etc
formatconvert = {
'A':'A', #alfanumerical
'AN':'A', #alfanumerical
#~ 'AR':'A', #right aligned alfanumerical field, used in fixed records.
'D':'D', #date
'DT':'D', #date-time
'T':'T', #time
'TM':'T', #time
'N':'N', #numerical, fixed decimal. Fixed nr of decimals; if no decimal used: whole number, integer
#~ 'NL':'N', #numerical, fixed decimal. In fixed format: no preceding zeros, left aligned,
#~ 'NR':'N', #numerical, fixed decimal. In fixed format: preceding blancs, right aligned,
'R':'R', #numerical, any number of decimals; the decimal point is 'floating'
#~ 'RL':'R', #numerical, any number of decimals. fixed: no preceding zeros, left aligned
#~ 'RR':'R', #numerical, any number of decimals. fixed: preceding blancs, right aligned
'I':'I', #numercial, implicit decimal
}
def _manipulatefieldformat(self,field,recordID):
try:
field[BFORMAT] = self.formatconvert[field[FORMAT]]
except KeyError:
raise botslib.GrammarError(_(u'Grammar "$grammar", record "$record", field "$field": format "$format" has to be one of "$keys".'),grammar=self.grammarname,record=recordID,field=field[ID],format=field[FORMAT],keys=self.formatconvert.keys())
#grammar subclasses. contain the defaultsyntax
class test(Grammar):
defaultsyntax = {
'checkcollision':True,
'noBOTSID':False,
}
class csv(Grammar):
defaultsyntax = {
'acceptspaceinnumfield':True, #only really used in fixed formats
'add_crlfafterrecord_sep':'',
'allow_lastrecordnotclosedproperly':False, #in csv sometimes the last record is no closed correctly. This is related to communciation over email. Beware: when using this, other checks will not be enforced!
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'text/csv',
'decimaal':'.',
'envelope':'',
'escape':"",
'field_sep':':',
'forcequote': 1, #(if quote_char is set) 0:no force: only quote if necessary:1:always force: 2:quote if alfanumeric
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'pass_all':True,
'quote_char':"'",
'record_sep':"\r\n",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'skip_firstline':False,
'stripfield_sep':False, #safe choice, as csv is no real standard
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
}
class fixed(Grammar):
formatconvert = {
'A':'A', #alfanumerical
'AN':'A', #alfanumerical
'AR':'A', #right aligned alfanumerical field, used in fixed records.
'D':'D', #date
'DT':'D', #date-time
'T':'T', #time
'TM':'T', #time
'N':'N', #numerical, fixed decimal. Fixed nr of decimals; if no decimal used: whole number, integer
'NL':'N', #numerical, fixed decimal. In fixed format: no preceding zeros, left aligned,
'NR':'N', #numerical, fixed decimal. In fixed format: preceding blancs, right aligned,
'R':'R', #numerical, any number of decimals; the decimal point is 'floating'
'RL':'R', #numerical, any number of decimals. fixed: no preceding zeros, left aligned
'RR':'R', #numerical, any number of decimals. fixed: preceding blancs, right aligned
'I':'I', #numercial, implicit decimal
}
defaultsyntax = {
'acceptspaceinnumfield':True, #only really used in fixed formats
'add_crlfafterrecord_sep':'',
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkfixedrecordtoolong':True,
'checkfixedrecordtooshort':False,
'checkunknownentities': True,
'contenttype':'text/plain',
'decimaal':'.',
'endrecordID':3,
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"\r\n",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'startrecordID':0,
'stripfield_sep':False,
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
}
class idoc(fixed):
defaultsyntax = {
'acceptspaceinnumfield':True, #only really used in fixed formats
'add_crlfafterrecord_sep':'',
'automaticcount':True,
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkfixedrecordtoolong':False,
'checkfixedrecordtooshort':False,
'checkunknownentities': True,
'contenttype':'text/plain',
'decimaal':'.',
'endrecordID':10,
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"\r\n",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'startrecordID':0,
'stripfield_sep':False,
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'MANDT':'0',
'DOCNUM':'0',
}
class xml(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'attributemarker':'__',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': True, #??changed later
'contenttype':'text/xml ',
'decimaal':'.',
'DOCTYPE':'', #doctype declaration to use in xml header. DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"' will lead to: <!DOCTYPE mydoctype SYSTEM "mydoctype.dtd">
'envelope':'',
'extra_character_entity':{}, #additional character entities to resolve when parsing XML; mostly html character entities. Not in python 2.4. Example: {'euro':u'','nbsp':unichr(160),'apos':u'\u0027'}
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: xml output is one string (no cr/lf); True: xml output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'processing_instructions': None, #to generate processing instruction in xml prolog. is a list, consisting of tuples, each tuple consists of type of instruction and text for instruction.
#Example: processing_instructions': [('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')]
#leads to this output in xml-file: <?xml-stylesheet href="mystylesheet.xsl" type="text/xml"?><?type-of-ppi attr1="value1" attr2="value2"?>
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'standalone':None, #as used in xml prolog; values: 'yes' , 'no' or None (not used)
'stripfield_sep':False,
'triad':'',
'version':'1.0', #as used in xml prolog
}
class xmlnocheck(xml):
_checkstructurerequired=False
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'attributemarker':'__',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': False,
'contenttype':'text/xml ',
'decimaal':'.',
'DOCTYPE':'', #doctype declaration to use in xml header. DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"' will lead to: <!DOCTYPE mydoctype SYSTEM "mydoctype.dtd">
'envelope':'',
'escape':'',
'extra_character_entity':{}, #additional character entities to resolve when parsing XML; mostly html character entities. Not in python 2.4. Example: {'euro':u'','nbsp':unichr(160),'apos':u'\u0027'}
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: xml output is one string (no cr/lf); True: xml output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'processing_instructions': None, #to generate processing instruction in xml prolog. is a list, consisting of tuples, each tuple consists of type of instruction and text for instruction.
#Example: processing_instructions': [('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')]
#leads to this output in xml-file: <?xml-stylesheet href="mystylesheet.xsl" type="text/xml"?><?type-of-ppi attr1="value1" attr2="value2"?>
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'standalone':None, #as used in xml prolog; values: 'yes' , 'no' or None (not used)
'stripfield_sep':False,
'triad':'',
'version':'1.0', #as used in xml prolog
}
class template(Grammar):
_checkstructurerequired=False
defaultsyntax = { \
'add_crlfafterrecord_sep':'',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'contenttype':'text/xml',
'checkunknownentities': True,
'decimaal':'.',
'envelope':'template',
'envelope-template':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'output':'xhtml-strict',
'quote_char':"",
'pass_all':False,
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class templatehtml(Grammar):
_checkstructurerequired=False
defaultsyntax = { \
'add_crlfafterrecord_sep':'',
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'contenttype':'text/xml',
'checkunknownentities': True,
'decimaal':'.',
'envelope':'templatehtml',
'envelope-template':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'lengthnumericbare':False,
'merge':True,
'noBOTSID':False,
'output':'xhtml-strict',
'quote_char':"",
'pass_all':False,
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class edifact(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'\r\n',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'UNOA',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'application/EDIFACT',
'decimaal':'.',
'envelope':'edifact',
'escape':'?',
'field_sep':'+',
'forcequote':0, #csv only
'forceUNA' : False,
'lengthnumericbare':True,
'merge':True,
'noBOTSID':False,
'pass_all':False,
'quote_char':'',
'record_sep':"'",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'*',
'sfield_sep':':',
'skip_char':'\r\n',
'stripfield_sep':True,
'triad':'',
'version':'3',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'UNB.S002.0007':'14',
'UNB.S003.0007':'14',
'UNB.0026':'',
'UNB.0035':'0',
}
formatconvert = {
'A':'A',
'AN':'A',
'N':'R',
}
class x12(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'\r\n',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'application/X12',
'decimaal':'.',
'envelope':'x12',
'escape':'',
'field_sep':'*',
'forcequote':0, #csv only
'functionalgroup' : 'XX',
'lengthnumericbare':True,
'merge':True,
'noBOTSID':False,
'pass_all':False,
'quote_char':'',
'record_sep':"~",
'record_tag_sep':"", #Tradacoms/GTDI
'replacechar':'', #if separator found, replace by this character; if replacechar is an empty string: raise error
'reserve':'^',
'sfield_sep':'>', #advised '\'?
'skip_char':'\r\n',
'stripfield_sep':True,
'triad':'',
'version':'00403',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'ISA01':'00',
'ISA02':' ',
'ISA03':'00',
'ISA04':' ',
'ISA05':'01',
'ISA07':'01',
'ISA11':'U', #since ISA version 00403 this is the reserve/repetition separator. Bots does not use this anymore for ISA version >00403
'ISA14':'1',
'ISA15':'P',
'GS07':'X',
}
formatconvert = {
'AN':'A',
'DT':'D',
'TM':'T',
'N':'I',
'N0':'I',
'N1':'I',
'N2':'I',
'N3':'I',
'N4':'I',
'N5':'I',
'N6':'I',
'N7':'I',
'N8':'I',
'N9':'I',
'R':'R',
'B':'A',
'ID':'A',
}
def _manipulatefieldformat(self,field,recordID):
super(x12,self)._manipulatefieldformat(field,recordID)
if field[BFORMAT]=='I':
if field[FORMAT][1:]:
field[DECIMALS] = int(field[FORMAT][1])
else:
field[DECIMALS] = 0
class json(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': True, #??changed later
'contenttype':'text/xml ',
'decimaal':'.',
'defaultBOTSIDroot':'ROOT',
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: output is one string (no cr/lf); True: output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class jsonnocheck(json):
_checkstructurerequired=False
defaultsyntax = {
'add_crlfafterrecord_sep':'',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'utf-8',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':False,
'checkunknownentities': False,
'contenttype':'text/xml ',
'decimaal':'.',
'defaultBOTSIDroot':'ROOT',
'envelope':'',
'escape':'',
'field_sep':'',
'forcequote':0, #csv only
'indented':False, #False: output is one string (no cr/lf); True: output is indented/human readable
'lengthnumericbare':False,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':"",
'record_sep':"",
'record_tag_sep':"", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':'',
'skip_char':'',
'stripfield_sep':False,
'triad':'',
}
class tradacoms(Grammar):
defaultsyntax = {
'add_crlfafterrecord_sep':'\n',
'acceptspaceinnumfield':True, #only really used in fixed formats
'charset':'us-ascii',
'checkcharsetin':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcharsetout':'strict', #strict, ignore or botsreplace (replace with char as set in bots.ini).
'checkcollision':True,
'checkunknownentities': True,
'contenttype':'application/text',
'decimaal':'.',
'envelope':'tradacoms',
'escape':'?',
'field_sep':'+',
'forcequote':0, #csv only
'indented':False, #False: output is one string (no cr/lf); True: output is indented/human readable
'lengthnumericbare':True,
'merge':False,
'noBOTSID':False,
'pass_all':False,
'quote_char':'',
'record_sep':"'",
'record_tag_sep':"=", #Tradacoms/GTDI
'reserve':'',
'sfield_sep':':',
'skip_char':'\r\n',
'stripfield_sep':True,
'triad':'',
'wrap_length':0, #for producing wrapped format, where a file consists of fixed length records ending with crr/lf. Often seen in mainframe, as400
'STX.STDS1':'ANA',
'STX.STDS2':'1',
'STX.FROM.02':'',
'STX.UNTO.02':'',
'STX.APRF':'',
'STX.PRCD':'',
}
formatconvert = {
'X':'A',
'9':'R',
'9V9':'I',
}
class database(jsonnocheck):
pass
| Python |
import os
import glob
import time
import datetime
import stat
import shutil
from django.utils.translation import ugettext as _
#bots modules
import botslib
import botsglobal
from botsconfig import *
def cleanup():
''' public function, does all cleanup of the database and file system.'''
try:
_cleanupsession()
_cleandatafile()
_cleanarchive()
_cleanpersist()
_cleantransactions()
_cleanprocessnothingreceived()
except:
botsglobal.logger.exception(u'Cleanup error.')
def _cleanupsession():
''' delete all expired sessions. Bots-engine starts up much more often than web-server.'''
vanaf = datetime.datetime.today()
botslib.change('''DELETE FROM django_session WHERE expire_date < %(vanaf)s''', {'vanaf':vanaf})
def _cleanarchive():
''' delete all archive directories older than maxdaysarchive days.'''
vanaf = (datetime.date.today()-datetime.timedelta(days=botsglobal.ini.getint('settings','maxdaysarchive',180))).strftime('%Y%m%d')
for row in botslib.query('''SELECT archivepath FROM channel '''):
if row['archivepath']:
vanafdir = botslib.join(row['archivepath'],vanaf)
for dir in glob.glob(botslib.join(row['archivepath'],'*')):
if dir < vanafdir:
shutil.rmtree(dir,ignore_errors=True)
def _cleandatafile():
''' delete all data files older than xx days.'''
vanaf = time.time() - (botsglobal.ini.getint('settings','maxdays',30) * 3600 * 24)
frompath = botslib.join(botsglobal.ini.get('directories','data','botssys/data'),'*')
for filename in glob.glob(frompath):
statinfo = os.stat(filename)
if not stat.S_ISDIR(statinfo.st_mode):
try:
os.remove(filename) #remove files - should be no files in root of data dir
except:
botsglobal.logger.exception(_(u'Cleanup could not remove file'))
elif statinfo.st_mtime > vanaf :
continue #directory is newer than maxdays, which is also true for the data files in it. Skip it.
else: #check files in dir and remove all older than maxdays
frompath2 = botslib.join(filename,'*')
emptydir=True #track check if directory is empty after loop (should directory itself be deleted/)
for filename2 in glob.glob(frompath2):
statinfo2 = os.stat(filename2)
if statinfo2.st_mtime > vanaf or stat.S_ISDIR(statinfo2.st_mode): #check files in dir and remove all older than maxdays
emptydir = False
else:
try:
os.remove(filename2)
except:
botsglobal.logger.exception(_(u'Cleanup could not remove file'))
if emptydir:
try:
os.rmdir(filename)
except:
botsglobal.logger.exception(_(u'Cleanup could not remove directory'))
def _cleanpersist():
'''delete all persist older than xx days.'''
vanaf = datetime.datetime.today() - datetime.timedelta(days=botsglobal.ini.getint('settings','maxdayspersist',30))
botslib.change('''DELETE FROM persist WHERE ts < %(vanaf)s''',{'vanaf':vanaf})
def _cleantransactions():
''' delete records from report, filereport and ta.
best indexes are on idta/reportidta; this should go fast.
'''
vanaf = datetime.datetime.today() - datetime.timedelta(days=botsglobal.ini.getint('settings','maxdays',30))
for row in botslib.query('''SELECT max(idta) as max FROM report WHERE ts < %(vanaf)s''',{'vanaf':vanaf}):
maxidta = row['max']
break
else: #if there is no maxidta to delete, do nothing
return
botslib.change('''DELETE FROM report WHERE idta < %(maxidta)s''',{'maxidta':maxidta})
botslib.change('''DELETE FROM filereport WHERE reportidta < %(maxidta)s''',{'maxidta':maxidta})
botslib.change('''DELETE FROM ta WHERE idta < %(maxidta)s''',{'maxidta':maxidta})
#the most recent run that is older than maxdays is kept (using < instead of <=).
#Reason: when deleting in ta this would leave the ta-records of the most recent run older than maxdays (except the first ta-record).
#this will not lead to problems.
def _cleanprocessnothingreceived():
''' delete all --new runs that received no files; including all process under the run
processes are organised as trees, so recursive.
'''
def core(idta):
#select db-ta's referring to this db-ta
for row in botslib.query('''SELECT idta
FROM ta
WHERE idta > %(idta)s
AND script=%(idta)s''',
{'idta':idta}):
core(row['idta'])
ta=botslib.OldTransaction(idta)
ta.delete()
return
#select root-processes older than hoursnotrefferedarekept
vanaf = datetime.datetime.today() - datetime.timedelta(hours=botsglobal.ini.getint('settings','hoursrunwithoutresultiskept',1))
for row in botslib.query('''SELECT idta
FROM report
WHERE type = 'new'
AND lastreceived=0
AND ts < %(vanaf)s''',
{'vanaf':vanaf}):
core(row['idta'])
#delete report
botslib.change('''DELETE FROM report WHERE idta=%(idta)s ''',{'idta':row['idta']})
| Python |
#Globals used by Bots
incommunicate = False #used to set all incommunication off
db = None #db-object
ini = None #ini-file-object that is read (bots.ini)
routeid = '' #current route. This is used to set routeid for Processes.
preprocessnumber = 0 #different preprocessnumbers are needed for different preprocessing.
version = '2.1.0' #bots version
minta4query = 0 #used in retry; this determines which ta's are queried in a route
######################################
| Python |
#!/usr/bin/env python
from bots import xml2botsgrammar
if __name__=='__main__':
xml2botsgrammar.start()
| Python |
import os
import unittest
import shutil
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import filecmp
try:
import json as simplejson
except ImportError:
import simplejson
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
try:
import cElementTree as ET
except ImportError:
try:
import elementtree.ElementTree as ET
except ImportError:
try:
from xml.etree import cElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET
'''
PLUGIN: unitinmessagejson.zip
'''
class InmessageJson(unittest.TestCase):
#~ #***********************************************************************
#~ #***********test json eg list of article (as eg used in database comm *******
#~ #***********************************************************************
def testjson01(self):
filein = 'botssys/infile/unitinmessagejson/org/01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjson01nocheck(self):
filein = 'botssys/infile/unitinmessagejson/org/01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjson11(self):
filein = 'botssys/infile/unitinmessagejson/org/11.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjson11nocheck(self):
filein = 'botssys/infile/unitinmessagejson/org/11.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='articles')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='articles')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
#***********************************************************************
#*********json incoming tests complex structure*************************
#***********************************************************************
def testjsoninvoic01(self):
filein = 'botssys/infile/unitinmessagejson/org/invoic01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic01nocheck(self):
filein = 'botssys/infile/unitinmessagejson/org/invoic01.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic02(self):
''' check 01.xml the same after rad&write/check '''
filein = 'botssys/infile/unitinmessagejson/org/invoic02.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic02nocheck(self):
''' check 01.xml the same after rad&write/check '''
filein = 'botssys/infile/unitinmessagejson/org/invoic02.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic01.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
#***********************************************************************
#*********json incoming tests int,float*********************************
#***********************************************************************
def testjsoninvoic03(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic03xmlnocheck(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='json',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xmlnocheck',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic03nocheck(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xml',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsoninvoic03nocheckxmlnocheck(self):
''' test int, float in json '''
filein = 'botssys/infile/unitinmessagejson/org/invoic03.jsn'
filecomp = 'botssys/infile/unitinmessagejson/comp/invoic02.xml'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='invoic')
inn2 = inmessage.edifromfile(filename=filecomp,editype='xmlnocheck',messagetype='invoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testjsondiv(self):
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130101.json'), 'standaard test')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130101.json'), 'standaard test')
#empty object
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130102.json')
#unknown field
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130103.json'), 'unknown field')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130103.json'), 'unknown field')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130103.json') #unknown field
#compare standard test with standard est with extra unknown fields and objects: must give same tree:
in1 = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130101.json')
in2 = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130115.json')
self.failUnless(utilsunit.comparenode(in1.root,in2.root),'compare')
#numeriek field
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130104.json'), 'numeriek field')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130104.json'), 'numeriek field')
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130104.json'), 'numeriek field')
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130105.json'), 'fucked up')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130105.json'), 'fucked up')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130105.json') #fucked up
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130106.json'), 'fucked up')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130106.json'), 'fucked up')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130106.json') #fucked up
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130107.json'), 'fucked up')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130107.json'), 'fucked up')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130107.json') #fucked up
#root is list with 3 messagetrees
inn = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130108.json')
self.assertEqual(len(inn.root.children), 3,'should deliver 3 messagetrees')
inn = inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130108.json')
self.assertEqual(len(inn.root.children), 3,'should deliver 3 messagetrees')
#root is list, but list has a non-object member
self.failUnless(inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130109.json'), 'root is list, but list has a non-object member')
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130109.json'), 'root is list, but list has a non-object member')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130109.json') #root is list, but list has a non-object member
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130110.json') #too many occurences
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130111.json') #ent TEST1 should have a TEST2
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130111.json'), 'ent TEST1 should have a TEST2')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130111.json') #ent TEST1 should have a TEST2
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130112.json') #ent TEST1 has a TEST2
self.failUnless(inmessage.edifromfile(editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130112.json'), 'ent TEST1 has a TEST2')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=True,filename='botssys/infile/unitinmessagejson/org/130112.json') #ent TEST1 has a TEST2
#unknown entries
inn = inmessage.edifromfile(editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130113.json')
#empty file
self.assertRaises(ValueError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130114.json') #empty file
self.assertRaises(ValueError,inmessage.edifromfile, editype='jsonnocheck',messagetype='jsonnocheck',filename='botssys/infile/unitinmessagejson/org/130114.json') #empty file
#numeric key
self.assertRaises(ValueError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130116.json')
#key is list
self.assertRaises(ValueError,inmessage.edifromfile, editype='json',messagetype='testjsonorder01',checkunknownentities=False,filename='botssys/infile/unitinmessagejson/org/130117.json')
def testinisoutjson01(self):
filein = 'botssys/infile/unitinmessagejson/org/inisout01.json'
fileout1 = 'botssys/infile/unitinmessagejson/output/inisout01.json'
fileout3 = 'botssys/infile/unitinmessagejson/output/inisout03.json'
utilsunit.readwrite(editype='json',messagetype='jsonorder',filenamein=filein,filenameout=fileout1)
utilsunit.readwrite(editype='jsonnocheck',messagetype='jsonnocheck',filenamein=filein,filenameout=fileout3)
inn1 = inmessage.edifromfile(filename=fileout1,editype='jsonnocheck',messagetype='jsonnocheck')
inn2 = inmessage.edifromfile(filename=fileout3,editype='jsonnocheck',messagetype='jsonnocheck')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testinisoutjson02(self):
#fails. this is because list of messages is read; and these are written in one time....nice for next release...
filein = 'botssys/infile/unitinmessagejson/org/inisout05.json'
fileout = 'botssys/infile/unitinmessagejson/output/inisout05.json'
inn = inmessage.edifromfile(editype='json',messagetype='jsoninvoic',filename=filein)
out = outmessage.outmessage_init(editype='json',messagetype='jsoninvoic',filename=fileout,divtext='',topartner='') #make outmessage object
#~ inn.root.display()
out.root = inn.root
out.writeall()
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='jsonnocheck',defaultBOTSIDroot='HEA')
inn2 = inmessage.edifromfile(filename=fileout,editype='jsonnocheck',messagetype='jsonnocheck')
#~ inn1.root.display()
#~ inn2.root.display()
#~ self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
#~ rawfile1 = utilsunit.readfile(filein)
#~ rawfile2 = utilsunit.readfile(fileout)
#~ jsonobject1 = simplejson.loads(rawfile1)
#~ jsonobject2 = simplejson.loads(rawfile2)
#~ self.assertEqual(jsonobject1,jsonobject2,'CmpJson')
def testinisoutjson03(self):
''' non-ascii-char'''
filein = 'botssys/infile/unitinmessagejson/org/inisout04.json'
fileout = 'botssys/infile/unitinmessagejson/output/inisout04.json'
utilsunit.readwrite(editype='json',messagetype='jsonorder',filenamein=filein,filenameout=fileout)
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='jsonnocheck')
inn2 = inmessage.edifromfile(filename=fileout,editype='jsonnocheck',messagetype='jsonnocheck')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
def testinisoutjson04(self):
filein = 'botssys/infile/unitinmessagejson/org/inisout05.json'
inn1 = inmessage.edifromfile(filename=filein,editype='jsonnocheck',messagetype='jsonnocheck',defaultBOTSIDroot='HEA')
inn2 = inmessage.edifromfile(filename=filein,editype='json',messagetype='jsoninvoic')
self.failUnless(utilsunit.comparenode(inn1.root,inn2.root))
if __name__ == '__main__':
botsinit.generalinit('config')
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitinmessagejson/output/',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitinmessagejson/output')
unittest.main()
| Python |
import os
import unittest
import shutil
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import filecmp
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
''' pluging unitinmessagexml.zip'''
class TestInmessage(unittest.TestCase):
''' Read messages; some should be OK (True), some shoudl give errors (False).
Tets per editype.
'''
def setUp(self):
pass
def testxml(self):
#~ #empty file
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110401.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml', filename='botssys/infile/unitinmessagexml/xml/110401.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110401.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten', filename='botssys/infile/unitinmessagexml/xml/110401.xml')
#only root record in 110402.xml
self.failUnless(inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110402.xml'), 'only a root tag; should be OK')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110402.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110402.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110402.xml')
#root tag different from grammar
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110406.xml')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110406.xml')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110406.xml')
#root tag is double
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110407.xml')
#invalid: no closing tag
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110408.xml')
#invalid: extra closing tag
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110409.xml')
#invalid: mandatory xml-element missing
self.failUnless(inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110410.xml'), '')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110410.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110410.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110410.xml')
#invalid: to many occurences
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110411.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True, filename='botssys/infile/unitinmessagexml/xml/110411.xml')
#invalid: missing mandatory xml attribute
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110412.xml')
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110412.xml')
#unknown xml element
self.assertRaises(botslib.MessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110413.xml')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110414.xml')
#2x the same xml attribute
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110415.xml')
self.assertRaises(SyntaxError,inmessage.edifromfile, editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110415.xml')
#messages with all max occurences, use attributes, etc
in1 = inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110416.xml') #all elements, attributes
#other order of xml elements; should esult in the same node tree
in1 = inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110417.xml') #as 18., other order of elements
in2 = inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110418.xml')
self.failUnless(utilsunit.comparenode(in2.root,in1.root),'compare')
#??what is tested here??
inn7= inmessage.edifromfile(editype='xml',messagetype='testxml',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110405.xml') #with <?xml version="1.0" encoding="utf-8"?>
inn8= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',checkunknownentities=True,filename='botssys/infile/unitinmessagexml/xml/110405.xml') #with <?xml version="1.0" encoding="utf-8"?>
self.failUnless(utilsunit.comparenode(inn7.root,inn8.root),'compare')
#~ #test different file which should give equal results
in1= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #no grammar used
in5= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #no grammar used
in6= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #no grammar used
in2= inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #with <?xml version="1.0" encoding="utf-8"?>
in3= inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #without <?xml version="1.0" encoding="utf-8"?>
in4= inmessage.edifromfile(editype='xml',messagetype='testxml',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #use cr/lf and whitespace for 'nice' xml
self.failUnless(utilsunit.comparenode(in2.root,in1.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in3.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in4.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in5.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in6.root),'compare')
#~ #test different file which should give equal results; flattenxml=True,
in1= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #no grammar used
in5= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #no grammar used
in6= inmessage.edifromfile(editype='xmlnocheck',messagetype='xmlnocheck',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #no grammar used
in4= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110405.xml') #use cr/lf and whitespace for 'nice' xml
in2= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110403.xml') #with <?xml version="1.0" encoding="utf-8"?>
in3= inmessage.edifromfile(editype='xml',messagetype='testxmlflatten',filename='botssys/infile/unitinmessagexml/xml/110404.xml') #without <?xml version="1.0" encoding="utf-8"?>
self.failUnless(utilsunit.comparenode(in2.root,in1.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in3.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in4.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in5.root),'compare')
self.failUnless(utilsunit.comparenode(in2.root,in6.root),'compare')
class Testinisoutxml(unittest.TestCase):
def testxml01a(self):
''' check xml; new behaviour'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout01a.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml02a(self):
''' check xmlnoccheck; new behaviour'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout02tmpa.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout02a.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml03(self):
''' check xml (different grammar)'''
filenamein='botssys/infile/unitinmessagexml/xml/110419.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout03.xml'
utilsunit.readwrite(editype='xml',messagetype='testxmlflatten',charset='utf-8',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenamein,'bots/' + filenameout))
def testxml04(self):
''' check xmlnoccheck'''
filenamein='botssys/infile/unitinmessagexml/xml/110419.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout04tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout04.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',charset='utf-8',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='testxmlflatten',charset='utf-8',filenamein=filenametmp,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenamein,'bots/' + filenameout))
def testxml05(self):
''' test xml; iso-8859-1'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout03.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisoutcompare05.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout05.xml'
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenamein,filenameout=filenameout,charset='ISO-8859-1')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml06(self):
''' test xmlnocheck; iso-8859-1'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout03.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout05tmp.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisoutcompare05.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout05a.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,charset='ISO-8859-1')
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenametmp,filenameout=filenameout,charset='ISO-8859-1')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml09(self):
''' BOM;; BOM is not written....'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout05.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout04.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout09.xml'
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenamein,filenameout=filenameout,charset='utf-8')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml10(self):
''' BOM;; BOM is not written....'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout05.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout10tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout10.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout04.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='testxml',filenamein=filenametmp,filenameout=filenameout,charset='utf-8')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml11(self):
''' check xml; new behaviour; use standalone parameter'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout06.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout11.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout02.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,standalone=None)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml11a(self):
''' check xml; new behaviour; use standalone parameter'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout06.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout11a.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,standalone='no')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml12(self):
''' check xmlnoccheck; new behaviour use standalone parameter'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout06.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout12tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout12.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,standalone='no')
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,standalone='no')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml13(self):
''' check xml; read doctype&write doctype'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout13.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout13.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml14(self):
''' check xmlnoccheck; read doctype&write doctype'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout13.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout14tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout14.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"')
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"')
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml15(self):
''' check xml; read processing_instructions&write processing_instructions'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout15.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout15.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml16(self):
''' check xmlnoccheck; read processing_instructions&write processing_instructions'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout15.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout16tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout16.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamein))
def testxml17(self):
''' check xml; read processing_instructions&doctype&comments. Do not write these.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout17.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout17.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout02.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml18(self):
''' check xml; read processing_instructions&doctype&comments. Do not write these.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout17.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout18tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout18.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout02.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp)
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout)
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml19(self):
''' check xml; indented; use lot of options.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout19.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout19.xml'
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenamein,filenameout=filenameout,indented=True,standalone='yes',DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"',processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
def testxml20(self):
''' check xml; indented; use lot of options.'''
filenamein='botssys/infile/unitinmessagexml/xml/inisout02.xml'
filenametmp='botssys/infile/unitinmessagexml/output/inisout20tmp.xml'
filenameout='botssys/infile/unitinmessagexml/output/inisout20.xml'
filenamecmp='botssys/infile/unitinmessagexml/xml/inisout19.xml'
utilsunit.readwrite(editype='xmlnocheck',messagetype='xmlnocheck',filenamein=filenamein,filenameout=filenametmp,indented=True,standalone='yes',DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"',processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
utilsunit.readwrite(editype='xml',messagetype='xmlorder',filenamein=filenametmp,filenameout=filenameout,indented=True,standalone='yes',DOCTYPE = 'mydoctype SYSTEM "mydoctype.dtd"',processing_instructions=[('xml-stylesheet' ,'href="mystylesheet.xsl" type="text/xml"'),('type-of-ppi' ,'attr1="value1" attr2="value2"')])
self.failUnless(filecmp.cmp('bots/' + filenameout,'bots/' + filenamecmp))
if __name__ == '__main__':
botsinit.generalinit('config')
#~ botslib.initbotscharsets()
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitinmessagexml/output',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitinmessagexml/output')
unittest.main()
| Python |
import os
import unittest
import shutil
import filecmp
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import bots.botslib as botslib
import bots.botsinit as botsinit
'''plugin unitnode.zip'''
class Testnode(unittest.TestCase):
''' test node.py and message.py.
'''
def testedifact01(self):
inn = inmessage.edifromfile(editype='edifact',messagetype='invoicwithenvelope',filename='botssys/infile/unitnode/nodetest01.edi')
out = outmessage.outmessage_init(editype='edifact',messagetype='invoicwithenvelope',filename='botssys/infile/unitnode/output/inisout03.edi',divtext='',topartner='') #make outmessage object
out.root = inn.root
#* getloop **************************************
count = 0
for t in inn.getloop({'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'}):
count += 1
self.assertEqual(count,2,'Cmplines')
count = 0
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
count += 1
self.assertEqual(count,3,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'}):
count += 1
self.assertEqual(count,6,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'XXX'},{'BOTSID':'LIN'},{'BOTSID':'QTY'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'XXX'}):
count += 1
self.assertEqual(count,0,'Cmplines')
count = 0
for t in inn.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY'}):
count += 1
self.assertEqual(count,6,'Cmplines')
#* getcount, getcountmpath **************************************
count = 0
countlist=[5,0,1]
nrsegmentslist=[132,10,12]
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
count2 = 0
for u in t.getloop({'BOTSID':'UNH'},{'BOTSID':'LIN'}):
count2 += 1
count3 = t.getcountoccurrences({'BOTSID':'UNH'},{'BOTSID':'LIN'})
self.assertEqual(t.getcount(),nrsegmentslist[count],'Cmplines')
self.assertEqual(count2,countlist[count],'Cmplines')
self.assertEqual(count3,countlist[count],'Cmplines')
count += 1
self.assertEqual(out.getcountoccurrences({'BOTSID':'UNB'},{'BOTSID':'UNH'}),count,'Cmplines')
self.assertEqual(out.getcount(),sum(nrsegmentslist,4),'Cmplines')
#* get, getnozero, countmpath, sort**************************************
for t in out.getloop({'BOTSID':'UNB'},{'BOTSID':'UNH'}):
self.assertRaises(botslib.MappingRootError,out.get,())
self.assertRaises(botslib.MappingRootError,out.getnozero,())
self.assertRaises(botslib.MappingRootError,out.get,0)
self.assertRaises(botslib.MappingRootError,out.getnozero,0)
t.sort({'BOTSID':'UNH'},{'BOTSID':'LIN','C212.7140':None})
start='0'
for u in t.getloop({'BOTSID':'UNH'},{'BOTSID':'LIN'}):
nextstart = u.get({'BOTSID':'LIN','C212.7140':None})
self.failUnless(start<nextstart)
start = nextstart
t.sort({'BOTSID':'UNH'},{'BOTSID':'LIN','1082':None})
start='0'
for u in t.getloop({'BOTSID':'UNH'},{'BOTSID':'LIN'}):
nextstart = u.get({'BOTSID':'LIN','1082':None})
self.failUnless(start<nextstart)
start = nextstart
self.assertRaises(botslib.MappingRootError,out.get,())
self.assertRaises(botslib.MappingRootError,out.getnozero,())
#~ # self.assertRaises(botslib.MpathError,out.get,())
first=True
for t in out.getloop({'BOTSID':'UNB'}):
if first:
self.assertEqual('15',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN','1082':None}),'Cmplines')
self.assertEqual('8',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'47','C186.6060':None}),'Cmplines')
self.assertEqual('0',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'12','C186.6060':None}),'Cmplines')
self.assertEqual('54.4',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'MOA','C516.5025':'203','C516.5004':None}),'Cmplines')
first = False
else:
self.assertEqual('1',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'47','C186.6060':None}),'Cmplines')
self.assertEqual('0',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'QTY','C186.6063':'12','C186.6060':None}),'Cmplines')
self.assertEqual('0',t.getcountsum({'BOTSID':'UNB'},{'BOTSID':'UNH'},{'BOTSID':'LIN'},{'BOTSID':'MOA','C516.5025':'203','C516.5004':None}),'Cmplines')
def testedifact02(self):
#~ #display query correct? incluuding propagating 'down the tree'?
inn = inmessage.edifromfile(editype='edifact',messagetype='invoicwithenvelopetestquery',filename='botssys/infile/unitnode/nodetest01.edi')
inn.root.processqueries({},2)
inn.root.displayqueries()
if __name__ == '__main__':
import datetime
botsinit.generalinit('config')
botsinit.initenginelogging()
shutil.rmtree('bots/botssys/infile/unitnode/output',ignore_errors=True) #remove whole output directory
os.mkdir('bots/botssys/infile/unitnode/output')
unittest.main()
unittest.main()
unittest.main()
| Python |
#!/usr/bin/env python
if __name__ == '__main__':
import cProfile
cProfile.run('from bots import engine; engine.start()','profile.tmp')
import pstats
p = pstats.Stats('profile.tmp')
#~ p.sort_stats('cumulative').print_stats(25)
p.sort_stats('time').print_stats(25)
#~ p.print_callees('deepcopy').print_stats(1)
p.print_callees('mydeepcopy')
#~ p.sort_stats('time').print_stats('grammar.py',50)
| Python |
import unittest
import bots.inmessage as inmessage
import bots.botslib as botslib
import bots.botsinit as botsinit
import utilsunit
'''plugin unitinmessageedifact.zip'''
class TestInmessage(unittest.TestCase):
def testEdifact0401(self):
''' 0401 Errors in records'''
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040101.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040102.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040103.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040104.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040105.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040106.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0401/040107.edi')
def testedifact0403(self):
#~ #test charsets
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040301.edi') #UNOA-regular OK for UNOA as UNOC
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040302F-generated.edi') #UNOA-regular OK for UNOA as UNOC
in0= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040303.edi') #UNOA-regular also UNOA-strict
in1= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040306.edi') #UNOA regular
in2= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000005.edi') #UNOA regular
in3= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000006.edi') #UNOA regular
for in1node,in2node,in3node in zip(in1.nextmessage(),in2.nextmessage(),in3.nextmessage()):
self.failUnless(utilsunit.comparenode(in1node.root,in2node.root),'compare')
self.failUnless(utilsunit.comparenode(in1node.root,in3node.root),'compare')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040305.edi') #needs UNOA regular
#~ in1= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040305.edi') #needs UNOA extended
in7= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/040304.edi') #UNOB-regular
in5= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000008.edi') #UNOB regular
in4= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000007-generated.edi') #UNOB regular
in6= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0403/T0000000009.edi') #UNOC
def testedifact0404(self):
#envelope tests
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040401.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040402.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040403.edi'), 'standaard test')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040404.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040405.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040406.edi')
#self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040407.edi') #syntax version '0'; is not checked anymore
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040408.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040409.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040410.edi'), 'standaard test')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040411.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040412.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040413.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040414.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040415.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040416.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040417.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0404/040418.edi')
def testedifact0407(self):
#lex test with characters in strange places
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040701.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040702.edi'), 'standaard test')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040703.edi')
self.assertRaises(botslib.InMessageError,inmessage.edifromfile,editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040704.edi')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040705.edi'), 'standaard test')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040706.edi'), 'UNOA Crtl-Z at end')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040707.edi'), 'UNOB Crtl-Z at end')
self.failUnless(inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0407/040708.edi'), 'UNOC Crtl-Z at end')
def testedifact0408(self):
#differentenvelopingsamecontent: 1rst UNH per UNB, 2nd has 2 UNB for all UNH's, 3rd has UNG-UNE
in1= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0408/040801.edi')
in2= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0408/040802.edi')
in3= inmessage.edifromfile(editype='edifact',messagetype='edifact',filename='botssys/infile/unitinmessageedifact/0408/040803.edi')
for in1node,in2node,in3node in zip(in1.nextmessage(),in2.nextmessage(),in3.nextmessage()):
self.failUnless(utilsunit.comparenode(in1node.root,in2node.root),'compare')
self.failUnless(utilsunit.comparenode(in1node.root,in3node.root),'compare')
if __name__ == '__main__':
botsinit.generalinit('config')
botsinit.initenginelogging()
unittest.main()
| Python |
import filecmp
import glob
import shutil
import os
import sys
import subprocess
import logging
import logging
import bots.botslib as botslib
import bots.botsinit as botsinit
import bots.botsglobal as botsglobal
from bots.botsconfig import *
'''plugin unitretry.zip'''
#!!!activate rotues
''' input: mime (complex structure); 2 different edi attachments, and ' tekst' attachemnt
some user scripts are written in this unit test; so one runs errors will occur; write user script which prevents error in next run
before running: delete all transactions.
runs OK if no errors in unit tests
'''
def dummylogger():
botsglobal.logger = logging.getLogger('dummy')
botsglobal.logger.setLevel(logging.ERROR)
botsglobal.logger.addHandler(logging.StreamHandler(sys.stdout))
def getlastreport():
for row in botslib.query(u'''SELECT *
FROM report
ORDER BY idta DESC
'''):
#~ print row
return row
def mycompare(dict1,dict2):
for key,value in dict1.items():
if value != dict2[key]:
raise Exception('error comparing "%s": should be %s but is %s (in db),'%(key,value,dict2[key]))
def scriptwrite(path,content):
f = open(path,'w')
f.write(content)
f.close()
if __name__ == '__main__':
pythoninterpreter = 'python2.7'
newcommand = [pythoninterpreter,'bots-engine.py',]
retrycommand = [pythoninterpreter,'bots-engine.py','--retry']
botsinit.generalinit('config')
botssys = botsglobal.ini.get('directories','botssys')
usersys = botsglobal.ini.get('directories','usersysabs')
dummylogger()
botsinit.connect()
try:
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.py'))
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.pyc'))
except:
pass
scriptwrite(os.path.join(usersys,'mappings','edifact','unitretry_2.py'),
'''
import bots.transform as transform
def main(inn,out):
raise Exception('test mapping')
transform.inn2out(inn,out)''')
#~ os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'))
#~ os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.pyc'))
scriptwrite(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'),
'''
def accept_incoming_attachment(channeldict,ta,charset,content,contenttype):
if not content.startswith('UNB'):
raise Exception('test')
return True
''')
#
#new; error in mime-handling
subprocess.call(newcommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':0},getlastreport())
#retry: again same error
subprocess.call(retrycommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':0},getlastreport())
#
os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'))
os.remove(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.pyc'))
scriptwrite(os.path.join(usersys,'communicationscripts','unitretry_mime1_in.py'),
'''
def accept_incoming_attachment(channeldict,ta,charset,content,contenttype):
if not content.startswith('UNB'):
return False
return True
''')
#retry: mime is OK< but mapping error will occur
subprocess.call(retrycommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':1},getlastreport())
#retry: mime is OK, same mapping error
subprocess.call(retrycommand)
mycompare({'status':1,'lastreceived':1,'lasterror':1,'lastdone':0,'send':0},getlastreport())
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.py'))
os.remove(os.path.join(usersys,'mappings','edifact','unitretry_2.pyc'))
scriptwrite(os.path.join(usersys,'mappings','edifact','unitretry_2.py'),
'''
import bots.transform as transform
def main(inn,out):
transform.inn2out(inn,out)''')
#retry: whole translation is OK
subprocess.call(retrycommand)
mycompare({'status':0,'lastreceived':1,'lasterror':0,'lastdone':1,'send':2},getlastreport())
#new; whole transaltion is OK
subprocess.call(newcommand)
mycompare({'status':0,'lastreceived':1,'lasterror':0,'lastdone':1,'send':2},getlastreport())
logging.shutdown()
botsglobal.db.close | Python |
import unittest
import bots.botslib as botslib
import bots.botsinit as botsinit
import bots.grammar as grammar
import bots.inmessage as inmessage
import bots.outmessage as outmessage
import utilsunit
''' plugin unitgrammar.zip '''
class TestGrammar(unittest.TestCase):
def testgeneralgrammarerrors(self):
self.assertRaises(botslib.GrammarError,grammar.grammarread,'flup','edifact') #not eexisting editype
self.assertRaises(botslib.GrammarError,grammar.syntaxread,'grammars','flup','edifact') #not eexisting editype
self.assertRaises(ImportError,grammar.grammarread,'edifact','flup') #not existing messagetype
self.assertRaises(ImportError,grammar.syntaxread,'grammars','edifact','flup') #not existing messagetype
self.assertRaises(botslib.GrammarError,grammar.grammarread,'test','test3') #no structure
self.assertRaises(ImportError,grammar.grammarread,'test','test4') #No tabel - Reference to not-existing tabel
self.assertRaises(botslib.ScriptImportError,grammar.grammarread,'test','test5') #Error in tabel: structure is not valid python list (syntax-error)
self.assertRaises(botslib.GrammarError,grammar.grammarread,'test','test6') #Error in tabel: record in structure not in recorddefs
self.assertRaises(ImportError,grammar.grammarread,'edifact','test7') #error in syntax
self.assertRaises(ImportError,grammar.syntaxread,'grammars','edifact','test7') #error in syntax
def testgramfieldedifact_and_general(self):
tabel = grammar.grammarread('edifact','edifact')
gramfield = tabel._checkfield
#edifact formats to bots formats
field = ['S001.0001','M', 1,'A']
fieldresult = ['S001.0001','M', 1,'A',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N']
fieldresult = ['S001.0001','M', 4,'N',True,0,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'AN']
fieldresult = ['S001.0001','M', 4,'AN',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
#min&max length
field = ['S001.0001','M', (2,4),'AN']
fieldresult = ['S001.0001','M', 4,'AN',True,0,2,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', (0,4),'AN']
fieldresult = ['S001.0001','M', 4,'AN',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
#decimals
field = ['S001.0001','M', 3.2,'N']
fieldresult = ['S001.0001','M', 3,'N',True,2,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', (4,4.3),'N']
fieldresult = ['S001.0001','M', 4,'N',True,3,4,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult),
field = ['S001.0001','M', (3.2,4.2),'N']
fieldresult = ['S001.0001','M', 4,'N',True,2,3,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult),
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#test all types of fields (I,R,N,A,D,T); tests not needed repeat for other editypes
#check field itself
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'','M', 4,'','M'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'','M', 4,''],'')
#check ID
self.assertRaises(botslib.GrammarError,gramfield,['','M', 4,'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,[None,'M', 4,'A'],'')
#check M/C
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','A',4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','',4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001',[],4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','MC',4,'I'],'')
#check format
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'N7'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,''],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,5],'')
#check length
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M','N','N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',0,'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',-2,'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',-3.2,'N'],'')
#length for formats without float
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',2.1,'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(2.1,3),'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(2,3.2),'A'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(3,2),'A'],'')
#length for formats with float
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',1.1,'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',('A',5),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(-1,1),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(5,None),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(0,1.1),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(0,0),'N'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',(2,1),'N'],'')
def testgramfieldx12(self):
tabel = grammar.grammarread('x12','x12')
gramfield = tabel._checkfield
#x12 formats to bots formats
field = ['S001.0001','M', 1,'AN']
fieldresult = ['S001.0001','M', 1,'AN',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'DT']
fieldresult = ['S001.0001','M', 4,'DT',True,0,0,'D']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'TM']
fieldresult = ['S001.0001','M', 4,'TM',True,0,0,'T']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'B']
fieldresult = ['S001.0001','M', 4,'B',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'ID']
fieldresult = ['S001.0001','M', 4,'ID',True,0,0,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'R']
fieldresult = ['S001.0001','M', 4,'R',True,0,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N']
fieldresult = ['S001.0001','M', 4,'N',True,0,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N0']
fieldresult = ['S001.0001','M', 4,'N0',True,0,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N3']
fieldresult = ['S001.0001','M', 4,'N3',True,3,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'N9']
fieldresult = ['S001.0001','M', 4,'N9',True,9,0,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
#decimals
field = ['S001.0001','M', 3,'R']
fieldresult = ['S001.0001','M', 3,'R',True,0,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M',4.3,'R']
fieldresult = ['S001.0001','M', 4,'R',True,3,0,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'D'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4.3,'I'],'')
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4.3,'NO'],'')
def testgramfieldfixed(self):
tabel = grammar.grammarread('fixed','invoicfixed')
gramfield = tabel._checkfield
#fixed formats to bots formats
field = ['S001.0001','M', 1,'A']
fieldresult = ['S001.0001','M', 1,'A',True,0,1,'A']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'D']
fieldresult = ['S001.0001','M', 4,'D',True,0,4,'D']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'T']
fieldresult = ['S001.0001','M', 4,'T',True,0,4,'T']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4,'R']
fieldresult = ['S001.0001','M', 4,'R',True,0,4,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4.3,'N']
fieldresult = ['S001.0001','M', 4,'N',True,3,4,'N']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M', 4.3,'I']
fieldresult = ['S001.0001','M', 4,'I',True,3,4,'I']
gramfield(field,'')
self.assertEqual(field,fieldresult)
field = ['S001.0001','M',4.3,'R']
fieldresult = ['S001.0001','M', 4,'R',True,3,4,'R']
gramfield(field,'')
self.assertEqual(field,fieldresult)
self.assertRaises(botslib.GrammarError,gramfield,['S001.0001','M',4,'B'],'')
if __name__ == '__main__':
botsinit.generalinit('config')
#~ botslib.initbotscharsets()
botsinit.initenginelogging()
unittest.main()
| Python |
#!/usr/bin/env python
from bots import engine
if __name__ == '__main__':
engine.start()
| Python |
import sys
import os
import tarfile
import glob
import shutil
import subprocess
import traceback
import bots.botsglobal as botsglobal
def join(path,*paths):
return os.path.normpath(os.path.join(path,*paths))
#******************************************************************************
#*** start *********************************************
#******************************************************************************
def start():
print 'Installation of bots open source edi translator.'
#python version dependencies
version = str(sys.version_info[0]) + str(sys.version_info[1])
if version == '25':
pass
elif version == '26':
pass
elif version == '27':
pass
else:
raise Exception('Wrong python version, use python 2.5.*, 2.6.* or 2.7.*')
botsdir = os.path.dirname(botsglobal.__file__)
print ' Installed bots in "%s".'%(botsdir)
#******************************************************************************
#*** shortcuts *******************************************************
#******************************************************************************
scriptpath = join(sys.prefix,'Scripts')
shortcutdir = join(get_special_folder_path('CSIDL_COMMON_PROGRAMS'),'Bots2.1')
try:
os.mkdir(shortcutdir)
except:
pass
else:
directory_created(shortcutdir)
try:
#~ create_shortcut(join(scriptpath,'botswebserver'),'Bots open source EDI translator',join(shortcutdir,'Bots-webserver.lnk'))
create_shortcut(join(sys.prefix,'python'),'bots open source edi translator',join(shortcutdir,'bots-webserver.lnk'),join(scriptpath,'bots-webserver.py'))
file_created(join(shortcutdir,'bots-webserver.lnk'))
except:
print ' Failed to install shortcut/link for bots in your menu.'
else:
print ' Installed shortcut in "Program Files".'
#******************************************************************************
#*** install libraries, dependencies ***************************************
#******************************************************************************
for library in glob.glob(join(botsdir,'installwin','*.gz')):
tar = tarfile.open(library)
tar.extractall(path=os.path.dirname(library))
tar.close()
untar_dir = library[:-len('.tar.gz')]
subprocess.call([join(sys.prefix,'pythonw'), 'setup.py','install'],cwd=untar_dir,stdin=open(os.devnull,'r'),stdout=open(os.devnull,'w'),stderr=open(os.devnull,'w'))
shutil.rmtree(untar_dir, ignore_errors=True)
print ' Installed needed libraries.'
#******************************************************************************
#*** install configuration files **************************************
#******************************************************************************
if os.path.exists(join(botsdir,'config','settings.py')): #use this to see if this is an existing installation
print ' Found existing configuration files'
print ' Configuration files bots.ini and settings.py not overwritten.'
print ' Manual action is needed.'
print ' See bots web site-documentation-migrate for more info.'
else:
shutil.copy(join(botsdir,'install','bots.ini'),join(botsdir,'config','bots.ini'))
shutil.copy(join(botsdir,'install','settings.py'),join(botsdir,'config','settings.py'))
print ' Installed configuration files'
#******************************************************************************
#*** install database; upgrade existing db *********************************
#******************************************************************************
sqlitedir = join(botsdir,'botssys','sqlitedb')
if os.path.exists(join(sqlitedir,'botsdb')): #use this to see if this is an existing installation
print ' Found existing database file botssys/sqlitedb/botsdb'
print ' Manual action is needed - there is a tool/program to update the database.'
print ' See bots web site-documentation-migrate for more info.'
else:
if not os.path.exists(sqlitedir): #use this to see if this is an existing installation
os.makedirs(sqlitedir)
shutil.copy(join(botsdir,'install','botsdb'),join(sqlitedir,'botsdb'))
print ' Installed SQLite database'
#******************************************************************************
#******************************************************************************
if __name__=='__main__':
if len(sys.argv)>1 and sys.argv[1]=='-install':
try:
start()
except:
print traceback.format_exc(0)
print
print 'Bots installation failed.'
else:
print
print 'Bots installation succeeded.'
| Python |
import os
import sys
from distutils.core import setup
def fullsplit(path, result=None):
"""
Split a pathname into components (the opposite of os.path.join) in a
platform-neutral way.
"""
if result is None:
result = []
head, tail = os.path.split(path)
if head == '':
return [tail] + result
if head == path:
return result
return fullsplit(head, [tail] + result)
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir != '':
os.chdir(root_dir)
for dirpath, dirnames, filenames in os.walk('bots'):
# Ignore dirnames that start with '.'
#~ for i, dirname in enumerate(dirnames):
#~ if dirname.startswith('.'): del dirnames[i]
if '__init__.py' in filenames:
packages.append('.'.join(fullsplit(dirpath)))
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc')]])
elif filenames:
data_files.append([dirpath, [os.path.join(dirpath, f) for f in filenames if not f.endswith('.pyc')]])
#~ # Small hack for working with bdist_wininst.
#~ # See http://mail.python.org/pipermail/distutils-sig/2004-August/004134.html
#~ if len(sys.argv) > 1 and 'bdist_wininst' in sys.argv[1:]:
if len(sys.argv) > 1 and 'bdist_wininst' in sys.argv[1:]:
for file_info in data_files:
file_info[0] = '\\PURELIB\\%s' % file_info[0]
setup(
name="bots",
version="2.1.0",
author = "hjebbers",
author_email = "hjebbers@gmail.com",
url = "http://bots.sourceforge.net/",
description="Bots open source edi translator",
long_description = "Bots is complete software for edi (Electronic Data Interchange): translate and communicate. All major edi data formats are supported: edifact, x12, tradacoms, xml",
platforms="OS Independent (Written in an interpreted language)",
license="GNU General Public License (GPL)",
classifiers = [
'Development Status :: 5 - Production/Stable',
'Operating System :: OS Independent',
'Programming Language :: Python',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Topic :: Office/Business',
'Topic :: Office/Business :: Financial',
'Topic :: Other/Nonlisted Topic',
'Topic :: Communications',
'Environment :: Console',
'Environment :: Web Environment',
],
scripts = [ 'bots-webserver.py',
'bots-engine.py',
'postinstallation.py',
'bots-grammarcheck.py',
'bots-xml2botsgrammar.py',
#~ 'bots/bots-updatedb.py',
],
packages = packages,
data_files = data_files,
)
| Python |
'''
Module which prompts the user for translations and saves them.
TODO: implement
@author: Rodrigo Damazio
'''
class Translator(object):
'''
classdocs
'''
def __init__(self, language):
'''
Constructor
'''
self._language = language
def Translate(self, string_names):
print string_names | Python |
'''
Module which brings history information about files from Mercurial.
@author: Rodrigo Damazio
'''
import re
import subprocess
REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*')
def _GetOutputLines(args):
'''
Runs an external process and returns its output as a list of lines.
@param args: the arguments to run
'''
process = subprocess.Popen(args,
stdout=subprocess.PIPE,
universal_newlines = True,
shell = False)
output = process.communicate()[0]
return output.splitlines()
def FillMercurialRevisions(filename, parsed_file):
'''
Fills the revs attribute of all strings in the given parsed file with
a list of revisions that touched the lines corresponding to that string.
@param filename: the name of the file to get history for
@param parsed_file: the parsed file to modify
'''
# Take output of hg annotate to get revision of each line
output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename])
# Create a map of line -> revision (key is list index, line 0 doesn't exist)
line_revs = ['dummy']
for line in output_lines:
rev_match = REVISION_REGEX.match(line)
if not rev_match:
raise 'Unexpected line of output from hg: %s' % line
rev_hash = rev_match.group('hash')
line_revs.append(rev_hash)
for str in parsed_file.itervalues():
# Get the lines that correspond to each string
start_line = str['startLine']
end_line = str['endLine']
# Get the revisions that touched those lines
revs = []
for line_number in range(start_line, end_line + 1):
revs.append(line_revs[line_number])
# Merge with any revisions that were already there
# (for explict revision specification)
if 'revs' in str:
revs += str['revs']
# Assign the revisions to the string
str['revs'] = frozenset(revs)
def DoesRevisionSuperceed(filename, rev1, rev2):
'''
Tells whether a revision superceeds another.
This essentially means that the older revision is an ancestor of the newer
one.
This also returns True if the two revisions are the same.
@param rev1: the revision that may be superceeding the other
@param rev2: the revision that may be superceeded
@return: True if rev1 superceeds rev2 or they're the same
'''
if rev1 == rev2:
return True
# TODO: Add filename
args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename]
output_lines = _GetOutputLines(args)
return rev2 in output_lines
def NewestRevision(filename, rev1, rev2):
'''
Returns which of two revisions is closest to the head of the repository.
If none of them is the ancestor of the other, then we return either one.
@param rev1: the first revision
@param rev2: the second revision
'''
if DoesRevisionSuperceed(filename, rev1, rev2):
return rev1
return rev2 | Python |
'''
Module which parses a string XML file.
@author: Rodrigo Damazio
'''
from xml.parsers.expat import ParserCreate
import re
#import xml.etree.ElementTree as ET
class StringsParser(object):
'''
Parser for string XML files.
This object is not thread-safe and should be used for parsing a single file at
a time, only.
'''
def Parse(self, file):
'''
Parses the given file and returns a dictionary mapping keys to an object
with attributes for that key, such as the value, start/end line and explicit
revisions.
In addition to the standard XML format of the strings file, this parser
supports an annotation inside comments, in one of these formats:
<!-- KEEP_PARENT name="bla" -->
<!-- KEEP_PARENT name="bla" rev="123456789012" -->
Such an annotation indicates that we're explicitly inheriting form the
master file (and the optional revision says that this decision is compatible
with the master file up to that revision).
@param file: the name of the file to parse
'''
self._Reset()
# Unfortunately expat is the only parser that will give us line numbers
self._xml_parser = ParserCreate()
self._xml_parser.StartElementHandler = self._StartElementHandler
self._xml_parser.EndElementHandler = self._EndElementHandler
self._xml_parser.CharacterDataHandler = self._CharacterDataHandler
self._xml_parser.CommentHandler = self._CommentHandler
file_obj = open(file)
self._xml_parser.ParseFile(file_obj)
file_obj.close()
return self._all_strings
def _Reset(self):
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
self._all_strings = {}
def _StartElementHandler(self, name, attrs):
if name != 'string':
return
if 'name' not in attrs:
return
assert not self._currentString
assert not self._currentStringName
self._currentString = {
'startLine' : self._xml_parser.CurrentLineNumber,
}
if 'rev' in attrs:
self._currentString['revs'] = [attrs['rev']]
self._currentStringName = attrs['name']
self._currentStringValue = ''
def _EndElementHandler(self, name):
if name != 'string':
return
assert self._currentString
assert self._currentStringName
self._currentString['value'] = self._currentStringValue
self._currentString['endLine'] = self._xml_parser.CurrentLineNumber
self._all_strings[self._currentStringName] = self._currentString
self._currentString = None
self._currentStringName = None
self._currentStringValue = None
def _CharacterDataHandler(self, data):
if not self._currentString:
return
self._currentStringValue += data
_KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+'
r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?'
r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*',
re.MULTILINE | re.DOTALL)
def _CommentHandler(self, data):
keep_parent_match = self._KEEP_PARENT_REGEX.match(data)
if not keep_parent_match:
return
name = keep_parent_match.group('name')
self._all_strings[name] = {
'keepParent' : True,
'startLine' : self._xml_parser.CurrentLineNumber,
'endLine' : self._xml_parser.CurrentLineNumber
}
rev = keep_parent_match.group('rev')
if rev:
self._all_strings[name]['revs'] = [rev] | Python |
#!/usr/bin/python
'''
Entry point for My Tracks i18n tool.
@author: Rodrigo Damazio
'''
import mytracks.files
import mytracks.translate
import mytracks.validate
import sys
def Usage():
print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0]
print 'Commands are:'
print ' cleanup'
print ' translate'
print ' validate'
sys.exit(1)
def Translate(languages):
'''
Asks the user to interactively translate any missing or oudated strings from
the files for the given languages.
@param languages: the languages to translate
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
missing = validator.missing_in_lang()
outdated = validator.outdated_in_lang()
for lang in languages:
untranslated = missing[lang] + outdated[lang]
if len(untranslated) == 0:
continue
translator = mytracks.translate.Translator(lang)
translator.Translate(untranslated)
def Validate(languages):
'''
Computes and displays errors in the string files for the given languages.
@param languages: the languages to compute for
'''
validator = mytracks.validate.Validator(languages)
validator.Validate()
error_count = 0
if (validator.valid()):
print 'All files OK'
else:
for lang, missing in validator.missing_in_master().iteritems():
print 'Missing in master, present in %s: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, missing in validator.missing_in_lang().iteritems():
print 'Missing in %s, present in master: %s:' % (lang, str(missing))
error_count = error_count + len(missing)
for lang, outdated in validator.outdated_in_lang().iteritems():
print 'Outdated in %s: %s:' % (lang, str(outdated))
error_count = error_count + len(outdated)
return error_count
if __name__ == '__main__':
argv = sys.argv
argc = len(argv)
if argc < 2:
Usage()
languages = mytracks.files.GetAllLanguageFiles()
if argc == 3:
langs = set(argv[2:])
if not langs.issubset(languages):
raise 'Language(s) not found'
# Filter just to the languages specified
languages = dict((lang, lang_file)
for lang, lang_file in languages.iteritems()
if lang in langs or lang == 'en' )
cmd = argv[1]
if cmd == 'translate':
Translate(languages)
elif cmd == 'validate':
error_count = Validate(languages)
else:
Usage()
error_count = 0
print '%d errors found.' % error_count
| Python |
'''
Module which compares languague files to the master file and detects
issues.
@author: Rodrigo Damazio
'''
import os
from mytracks.parser import StringsParser
import mytracks.history
class Validator(object):
def __init__(self, languages):
'''
Builds a strings file validator.
Params:
@param languages: a dictionary mapping each language to its corresponding directory
'''
self._langs = {}
self._master = None
self._language_paths = languages
parser = StringsParser()
for lang, lang_dir in languages.iteritems():
filename = os.path.join(lang_dir, 'strings.xml')
parsed_file = parser.Parse(filename)
mytracks.history.FillMercurialRevisions(filename, parsed_file)
if lang == 'en':
self._master = parsed_file
else:
self._langs[lang] = parsed_file
self._Reset()
def Validate(self):
'''
Computes whether all the data in the files for the given languages is valid.
'''
self._Reset()
self._ValidateMissingKeys()
self._ValidateOutdatedKeys()
def valid(self):
return (len(self._missing_in_master) == 0 and
len(self._missing_in_lang) == 0 and
len(self._outdated_in_lang) == 0)
def missing_in_master(self):
return self._missing_in_master
def missing_in_lang(self):
return self._missing_in_lang
def outdated_in_lang(self):
return self._outdated_in_lang
def _Reset(self):
# These are maps from language to string name list
self._missing_in_master = {}
self._missing_in_lang = {}
self._outdated_in_lang = {}
def _ValidateMissingKeys(self):
'''
Computes whether there are missing keys on either side.
'''
master_keys = frozenset(self._master.iterkeys())
for lang, file in self._langs.iteritems():
keys = frozenset(file.iterkeys())
missing_in_master = keys - master_keys
missing_in_lang = master_keys - keys
if len(missing_in_master) > 0:
self._missing_in_master[lang] = missing_in_master
if len(missing_in_lang) > 0:
self._missing_in_lang[lang] = missing_in_lang
def _ValidateOutdatedKeys(self):
'''
Computers whether any of the language keys are outdated with relation to the
master keys.
'''
for lang, file in self._langs.iteritems():
outdated = []
for key, str in file.iteritems():
# Get all revisions that touched master and language files for this
# string.
master_str = self._master[key]
master_revs = master_str['revs']
lang_revs = str['revs']
if not master_revs or not lang_revs:
print 'WARNING: No revision for %s in %s' % (key, lang)
continue
master_file = os.path.join(self._language_paths['en'], 'strings.xml')
lang_file = os.path.join(self._language_paths[lang], 'strings.xml')
# Assume that the repository has a single head (TODO: check that),
# and as such there is always one revision which superceeds all others.
master_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2),
master_revs)
lang_rev = reduce(
lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2),
lang_revs)
# If the master version is newer than the lang version
if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev):
outdated.append(key)
if len(outdated) > 0:
self._outdated_in_lang[lang] = outdated
| Python |
'''
Module for dealing with resource files (but not their contents).
@author: Rodrigo Damazio
'''
import os.path
from glob import glob
import re
MYTRACKS_RES_DIR = 'MyTracks/res'
ANDROID_MASTER_VALUES = 'values'
ANDROID_VALUES_MASK = 'values-*'
def GetMyTracksDir():
'''
Returns the directory in which the MyTracks directory is located.
'''
path = os.getcwd()
while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)):
if path == '/':
raise 'Not in My Tracks project'
# Go up one level
path = os.path.split(path)[0]
return path
def GetAllLanguageFiles():
'''
Returns a mapping from all found languages to their respective directories.
'''
mytracks_path = GetMyTracksDir()
res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK)
language_dirs = glob(res_dir)
master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES)
if len(language_dirs) == 0:
raise 'No languages found!'
if not os.path.isdir(master_dir):
raise 'Couldn\'t find master file'
language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs]
language_tuples.append(('en', master_dir))
return dict(language_tuples)
| Python |
import re
from SCons.Script import * # the usual scons stuff you get in a SConscript
def generate(env):
"""
Add builders and construction variables for the
SubstInFile tool.
Adds SubstInFile builder, which substitutes the keys->values of SUBST_DICT
from the source to the target.
The values of SUBST_DICT first have any construction variables expanded
(its keys are not expanded).
If a value of SUBST_DICT is a python callable function, it is called and
the result is expanded as the value.
If there's more than one source and more than one target, each target gets
substituted from the corresponding source.
"""
def do_subst_in_file(targetfile, sourcefile, dict):
"""Replace all instances of the keys of dict with their values.
For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'},
then all instances of %VERSION% in the file will be replaced with 1.2345 etc.
"""
try:
f = open(sourcefile, 'rb')
contents = f.read()
f.close()
except:
raise SCons.Errors.UserError, "Can't read source file %s"%sourcefile
for (k,v) in dict.items():
contents = re.sub(k, v, contents)
try:
f = open(targetfile, 'wb')
f.write(contents)
f.close()
except:
raise SCons.Errors.UserError, "Can't write target file %s"%targetfile
return 0 # success
def subst_in_file(target, source, env):
if not env.has_key('SUBST_DICT'):
raise SCons.Errors.UserError, "SubstInFile requires SUBST_DICT to be set."
d = dict(env['SUBST_DICT']) # copy it
for (k,v) in d.items():
if callable(v):
d[k] = env.subst(v()).replace('\\','\\\\')
elif SCons.Util.is_String(v):
d[k] = env.subst(v).replace('\\','\\\\')
else:
raise SCons.Errors.UserError, "SubstInFile: key %s: %s must be a string or callable"%(k, repr(v))
for (t,s) in zip(target, source):
return do_subst_in_file(str(t), str(s), d)
def subst_in_file_string(target, source, env):
"""This is what gets printed on the console."""
return '\n'.join(['Substituting vars from %s into %s'%(str(s), str(t))
for (t,s) in zip(target, source)])
def subst_emitter(target, source, env):
"""Add dependency from substituted SUBST_DICT to target.
Returns original target, source tuple unchanged.
"""
d = env['SUBST_DICT'].copy() # copy it
for (k,v) in d.items():
if callable(v):
d[k] = env.subst(v())
elif SCons.Util.is_String(v):
d[k]=env.subst(v)
Depends(target, SCons.Node.Python.Value(d))
return target, source
## env.Append(TOOLS = 'substinfile') # this should be automaticaly done by Scons ?!?
subst_action = SCons.Action.Action( subst_in_file, subst_in_file_string )
env['BUILDERS']['SubstInFile'] = Builder(action=subst_action, emitter=subst_emitter)
def exists(env):
"""
Make sure tool exists.
"""
return True
| Python |
import fnmatch
import os
def generate( env ):
def Glob( env, includes = None, excludes = None, dir = '.' ):
"""Adds Glob( includes = Split( '*' ), excludes = None, dir = '.')
helper function to environment.
Glob both the file-system files.
includes: list of file name pattern included in the return list when matched.
excludes: list of file name pattern exluced from the return list.
Example:
sources = env.Glob( ("*.cpp", '*.h'), "~*.cpp", "#src" )
"""
def filterFilename(path):
abs_path = os.path.join( dir, path )
if not os.path.isfile(abs_path):
return 0
fn = os.path.basename(path)
match = 0
for include in includes:
if fnmatch.fnmatchcase( fn, include ):
match = 1
break
if match == 1 and not excludes is None:
for exclude in excludes:
if fnmatch.fnmatchcase( fn, exclude ):
match = 0
break
return match
if includes is None:
includes = ('*',)
elif type(includes) in ( type(''), type(u'') ):
includes = (includes,)
if type(excludes) in ( type(''), type(u'') ):
excludes = (excludes,)
dir = env.Dir(dir).abspath
paths = os.listdir( dir )
def makeAbsFileNode( path ):
return env.File( os.path.join( dir, path ) )
nodes = filter( filterFilename, paths )
return map( makeAbsFileNode, nodes )
from SCons.Script import Environment
Environment.Glob = Glob
def exists(env):
"""
Tool always exists.
"""
return True
| Python |
"""tarball
Tool-specific initialization for tarball.
"""
## Commands to tackle a command based implementation:
##to unpack on the fly...
##gunzip < FILE.tar.gz | tar xvf -
##to pack on the fly...
##tar cvf - FILE-LIST | gzip -c > FILE.tar.gz
import os.path
import SCons.Builder
import SCons.Node.FS
import SCons.Util
try:
import gzip
import tarfile
internal_targz = 1
except ImportError:
internal_targz = 0
TARGZ_DEFAULT_COMPRESSION_LEVEL = 9
if internal_targz:
def targz(target, source, env):
def archive_name( path ):
path = os.path.normpath( os.path.abspath( path ) )
common_path = os.path.commonprefix( (base_dir, path) )
archive_name = path[len(common_path):]
return archive_name
def visit(tar, dirname, names):
for name in names:
path = os.path.join(dirname, name)
if os.path.isfile(path):
tar.add(path, archive_name(path) )
compression = env.get('TARGZ_COMPRESSION_LEVEL',TARGZ_DEFAULT_COMPRESSION_LEVEL)
base_dir = os.path.normpath( env.get('TARGZ_BASEDIR', env.Dir('.')).abspath )
target_path = str(target[0])
fileobj = gzip.GzipFile( target_path, 'wb', compression )
tar = tarfile.TarFile(os.path.splitext(target_path)[0], 'w', fileobj)
for source in source:
source_path = str(source)
if source.isdir():
os.path.walk(source_path, visit, tar)
else:
tar.add(source_path, archive_name(source_path) ) # filename, arcname
tar.close()
targzAction = SCons.Action.Action(targz, varlist=['TARGZ_COMPRESSION_LEVEL','TARGZ_BASEDIR'])
def makeBuilder( emitter = None ):
return SCons.Builder.Builder(action = SCons.Action.Action('$TARGZ_COM', '$TARGZ_COMSTR'),
source_factory = SCons.Node.FS.Entry,
source_scanner = SCons.Defaults.DirScanner,
suffix = '$TARGZ_SUFFIX',
multi = 1)
TarGzBuilder = makeBuilder()
def generate(env):
"""Add Builders and construction variables for zip to an Environment.
The following environnement variables may be set:
TARGZ_COMPRESSION_LEVEL: integer, [0-9]. 0: no compression, 9: best compression (same as gzip compression level).
TARGZ_BASEDIR: base-directory used to determine archive name (this allow archive name to be relative
to something other than top-dir).
"""
env['BUILDERS']['TarGz'] = TarGzBuilder
env['TARGZ_COM'] = targzAction
env['TARGZ_COMPRESSION_LEVEL'] = TARGZ_DEFAULT_COMPRESSION_LEVEL # range 0-9
env['TARGZ_SUFFIX'] = '.tar.gz'
env['TARGZ_BASEDIR'] = env.Dir('.') # Sources archive name are made relative to that directory.
else:
def generate(env):
pass
def exists(env):
return internal_targz
| Python |
import os
import os.path
from fnmatch import fnmatch
import targz
##def DoxyfileParse(file_contents):
## """
## Parse a Doxygen source file and return a dictionary of all the values.
## Values will be strings and lists of strings.
## """
## data = {}
##
## import shlex
## lex = shlex.shlex(instream = file_contents, posix = True)
## lex.wordchars += "*+./-:"
## lex.whitespace = lex.whitespace.replace("\n", "")
## lex.escape = ""
##
## lineno = lex.lineno
## last_backslash_lineno = lineno
## token = lex.get_token()
## key = token # the first token should be a key
## last_token = ""
## key_token = False
## next_key = False
## new_data = True
##
## def append_data(data, key, new_data, token):
## if new_data or len(data[key]) == 0:
## data[key].append(token)
## else:
## data[key][-1] += token
##
## while token:
## if token in ['\n']:
## if last_token not in ['\\']:
## key_token = True
## elif token in ['\\']:
## pass
## elif key_token:
## key = token
## key_token = False
## else:
## if token == "+=":
## if not data.has_key(key):
## data[key] = list()
## elif token == "=":
## data[key] = list()
## else:
## append_data( data, key, new_data, token )
## new_data = True
##
## last_token = token
## token = lex.get_token()
##
## if last_token == '\\' and token != '\n':
## new_data = False
## append_data( data, key, new_data, '\\' )
##
## # compress lists of len 1 into single strings
## for (k, v) in data.items():
## if len(v) == 0:
## data.pop(k)
##
## # items in the following list will be kept as lists and not converted to strings
## if k in ["INPUT", "FILE_PATTERNS", "EXCLUDE_PATTERNS"]:
## continue
##
## if len(v) == 1:
## data[k] = v[0]
##
## return data
##
##def DoxySourceScan(node, env, path):
## """
## Doxygen Doxyfile source scanner. This should scan the Doxygen file and add
## any files used to generate docs to the list of source files.
## """
## default_file_patterns = [
## '*.c', '*.cc', '*.cxx', '*.cpp', '*.c++', '*.java', '*.ii', '*.ixx',
## '*.ipp', '*.i++', '*.inl', '*.h', '*.hh ', '*.hxx', '*.hpp', '*.h++',
## '*.idl', '*.odl', '*.cs', '*.php', '*.php3', '*.inc', '*.m', '*.mm',
## '*.py',
## ]
##
## default_exclude_patterns = [
## '*~',
## ]
##
## sources = []
##
## data = DoxyfileParse(node.get_contents())
##
## if data.get("RECURSIVE", "NO") == "YES":
## recursive = True
## else:
## recursive = False
##
## file_patterns = data.get("FILE_PATTERNS", default_file_patterns)
## exclude_patterns = data.get("EXCLUDE_PATTERNS", default_exclude_patterns)
##
## for node in data.get("INPUT", []):
## if os.path.isfile(node):
## sources.add(node)
## elif os.path.isdir(node):
## if recursive:
## for root, dirs, files in os.walk(node):
## for f in files:
## filename = os.path.join(root, f)
##
## pattern_check = reduce(lambda x, y: x or bool(fnmatch(filename, y)), file_patterns, False)
## exclude_check = reduce(lambda x, y: x and fnmatch(filename, y), exclude_patterns, True)
##
## if pattern_check and not exclude_check:
## sources.append(filename)
## else:
## for pattern in file_patterns:
## sources.extend(glob.glob("/".join([node, pattern])))
## sources = map( lambda path: env.File(path), sources )
## return sources
##
##
##def DoxySourceScanCheck(node, env):
## """Check if we should scan this file"""
## return os.path.isfile(node.path)
def srcDistEmitter(source, target, env):
## """Doxygen Doxyfile emitter"""
## # possible output formats and their default values and output locations
## output_formats = {
## "HTML": ("YES", "html"),
## "LATEX": ("YES", "latex"),
## "RTF": ("NO", "rtf"),
## "MAN": ("YES", "man"),
## "XML": ("NO", "xml"),
## }
##
## data = DoxyfileParse(source[0].get_contents())
##
## targets = []
## out_dir = data.get("OUTPUT_DIRECTORY", ".")
##
## # add our output locations
## for (k, v) in output_formats.items():
## if data.get("GENERATE_" + k, v[0]) == "YES":
## targets.append(env.Dir( os.path.join(out_dir, data.get(k + "_OUTPUT", v[1]))) )
##
## # don't clobber targets
## for node in targets:
## env.Precious(node)
##
## # set up cleaning stuff
## for node in targets:
## env.Clean(node, node)
##
## return (targets, source)
return (target,source)
def generate(env):
"""
Add builders and construction variables for the
SrcDist tool.
"""
## doxyfile_scanner = env.Scanner(
## DoxySourceScan,
## "DoxySourceScan",
## scan_check = DoxySourceScanCheck,
## )
if targz.exists(env):
srcdist_builder = targz.makeBuilder( srcDistEmitter )
env['BUILDERS']['SrcDist'] = srcdist_builder
def exists(env):
"""
Make sure srcdist exists.
"""
return targz.exists(env)
| Python |
#! /usr/bin/env python
#
# SCons - a Software Constructor
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/script/sconsign.py 4720 2010/03/24 03:14:11 jars"
__version__ = "1.3.0"
__build__ = "r4720"
__buildsys__ = "jars-desktop"
__date__ = "2010/03/24 03:14:11"
__developer__ = "jars"
import os
import os.path
import sys
import time
##############################################################################
# BEGIN STANDARD SCons SCRIPT HEADER
#
# This is the cut-and-paste logic so that a self-contained script can
# interoperate correctly with different SCons versions and installation
# locations for the engine. If you modify anything in this section, you
# should also change other scripts that use this same header.
##############################################################################
# Strip the script directory from sys.path() so on case-insensitive
# (WIN32) systems Python doesn't think that the "scons" script is the
# "SCons" package. Replace it with our own library directories
# (version-specific first, in case they installed by hand there,
# followed by generic) so we pick up the right version of the build
# engine modules if they're in either directory.
script_dir = sys.path[0]
if script_dir in sys.path:
sys.path.remove(script_dir)
libs = []
if os.environ.has_key("SCONS_LIB_DIR"):
libs.append(os.environ["SCONS_LIB_DIR"])
local_version = 'scons-local-' + __version__
local = 'scons-local'
if script_dir:
local_version = os.path.join(script_dir, local_version)
local = os.path.join(script_dir, local)
libs.append(os.path.abspath(local_version))
libs.append(os.path.abspath(local))
scons_version = 'scons-%s' % __version__
prefs = []
if sys.platform == 'win32':
# sys.prefix is (likely) C:\Python*;
# check only C:\Python*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, 'Lib', 'site-packages'))
else:
# On other (POSIX) platforms, things are more complicated due to
# the variety of path names and library locations. Try to be smart
# about it.
if script_dir == 'bin':
# script_dir is `pwd`/bin;
# check `pwd`/lib/scons*.
prefs.append(os.getcwd())
else:
if script_dir == '.' or script_dir == '':
script_dir = os.getcwd()
head, tail = os.path.split(script_dir)
if tail == "bin":
# script_dir is /foo/bin;
# check /foo/lib/scons*.
prefs.append(head)
head, tail = os.path.split(sys.prefix)
if tail == "usr":
# sys.prefix is /foo/usr;
# check /foo/usr/lib/scons* first,
# then /foo/usr/local/lib/scons*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, "local"))
elif tail == "local":
h, t = os.path.split(head)
if t == "usr":
# sys.prefix is /foo/usr/local;
# check /foo/usr/local/lib/scons* first,
# then /foo/usr/lib/scons*.
prefs.append(sys.prefix)
prefs.append(head)
else:
# sys.prefix is /foo/local;
# check only /foo/local/lib/scons*.
prefs.append(sys.prefix)
else:
# sys.prefix is /foo (ends in neither /usr or /local);
# check only /foo/lib/scons*.
prefs.append(sys.prefix)
temp = map(lambda x: os.path.join(x, 'lib'), prefs)
temp.extend(map(lambda x: os.path.join(x,
'lib',
'python' + sys.version[:3],
'site-packages'),
prefs))
prefs = temp
# Add the parent directory of the current python's library to the
# preferences. On SuSE-91/AMD64, for example, this is /usr/lib64,
# not /usr/lib.
try:
libpath = os.__file__
except AttributeError:
pass
else:
# Split /usr/libfoo/python*/os.py to /usr/libfoo/python*.
libpath, tail = os.path.split(libpath)
# Split /usr/libfoo/python* to /usr/libfoo
libpath, tail = os.path.split(libpath)
# Check /usr/libfoo/scons*.
prefs.append(libpath)
try:
import pkg_resources
except ImportError:
pass
else:
# when running from an egg add the egg's directory
try:
d = pkg_resources.get_distribution('scons')
except pkg_resources.DistributionNotFound:
pass
else:
prefs.append(d.location)
# Look first for 'scons-__version__' in all of our preference libs,
# then for 'scons'.
libs.extend(map(lambda x: os.path.join(x, scons_version), prefs))
libs.extend(map(lambda x: os.path.join(x, 'scons'), prefs))
sys.path = libs + sys.path
##############################################################################
# END STANDARD SCons SCRIPT HEADER
##############################################################################
import cPickle
import imp
import string
import whichdb
import SCons.SConsign
def my_whichdb(filename):
if filename[-7:] == ".dblite":
return "SCons.dblite"
try:
f = open(filename + ".dblite", "rb")
f.close()
return "SCons.dblite"
except IOError:
pass
return _orig_whichdb(filename)
_orig_whichdb = whichdb.whichdb
whichdb.whichdb = my_whichdb
def my_import(mname):
if '.' in mname:
i = string.rfind(mname, '.')
parent = my_import(mname[:i])
fp, pathname, description = imp.find_module(mname[i+1:],
parent.__path__)
else:
fp, pathname, description = imp.find_module(mname)
return imp.load_module(mname, fp, pathname, description)
class Flagger:
default_value = 1
def __setitem__(self, item, value):
self.__dict__[item] = value
self.default_value = 0
def __getitem__(self, item):
return self.__dict__.get(item, self.default_value)
Do_Call = None
Print_Directories = []
Print_Entries = []
Print_Flags = Flagger()
Verbose = 0
Readable = 0
def default_mapper(entry, name):
try:
val = eval("entry."+name)
except:
val = None
return str(val)
def map_action(entry, name):
try:
bact = entry.bact
bactsig = entry.bactsig
except AttributeError:
return None
return '%s [%s]' % (bactsig, bact)
def map_timestamp(entry, name):
try:
timestamp = entry.timestamp
except AttributeError:
timestamp = None
if Readable and timestamp:
return "'" + time.ctime(timestamp) + "'"
else:
return str(timestamp)
def map_bkids(entry, name):
try:
bkids = entry.bsources + entry.bdepends + entry.bimplicit
bkidsigs = entry.bsourcesigs + entry.bdependsigs + entry.bimplicitsigs
except AttributeError:
return None
result = []
for i in xrange(len(bkids)):
result.append(nodeinfo_string(bkids[i], bkidsigs[i], " "))
if result == []:
return None
return string.join(result, "\n ")
map_field = {
'action' : map_action,
'timestamp' : map_timestamp,
'bkids' : map_bkids,
}
map_name = {
'implicit' : 'bkids',
}
def field(name, entry, verbose=Verbose):
if not Print_Flags[name]:
return None
fieldname = map_name.get(name, name)
mapper = map_field.get(fieldname, default_mapper)
val = mapper(entry, name)
if verbose:
val = name + ": " + val
return val
def nodeinfo_raw(name, ninfo, prefix=""):
# This just formats the dictionary, which we would normally use str()
# to do, except that we want the keys sorted for deterministic output.
d = ninfo.__dict__
try:
keys = ninfo.field_list + ['_version_id']
except AttributeError:
keys = d.keys()
keys.sort()
l = []
for k in keys:
l.append('%s: %s' % (repr(k), repr(d.get(k))))
if '\n' in name:
name = repr(name)
return name + ': {' + string.join(l, ', ') + '}'
def nodeinfo_cooked(name, ninfo, prefix=""):
try:
field_list = ninfo.field_list
except AttributeError:
field_list = []
f = lambda x, ni=ninfo, v=Verbose: field(x, ni, v)
if '\n' in name:
name = repr(name)
outlist = [name+':'] + filter(None, map(f, field_list))
if Verbose:
sep = '\n ' + prefix
else:
sep = ' '
return string.join(outlist, sep)
nodeinfo_string = nodeinfo_cooked
def printfield(name, entry, prefix=""):
outlist = field("implicit", entry, 0)
if outlist:
if Verbose:
print " implicit:"
print " " + outlist
outact = field("action", entry, 0)
if outact:
if Verbose:
print " action: " + outact
else:
print " " + outact
def printentries(entries, location):
if Print_Entries:
for name in Print_Entries:
try:
entry = entries[name]
except KeyError:
sys.stderr.write("sconsign: no entry `%s' in `%s'\n" % (name, location))
else:
try:
ninfo = entry.ninfo
except AttributeError:
print name + ":"
else:
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
else:
names = entries.keys()
names.sort()
for name in names:
entry = entries[name]
try:
ninfo = entry.ninfo
except AttributeError:
print name + ":"
else:
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
class Do_SConsignDB:
def __init__(self, dbm_name, dbm):
self.dbm_name = dbm_name
self.dbm = dbm
def __call__(self, fname):
# The *dbm modules stick their own file suffixes on the names
# that are passed in. This is causes us to jump through some
# hoops here to be able to allow the user
try:
# Try opening the specified file name. Example:
# SPECIFIED OPENED BY self.dbm.open()
# --------- -------------------------
# .sconsign => .sconsign.dblite
# .sconsign.dblite => .sconsign.dblite.dblite
db = self.dbm.open(fname, "r")
except (IOError, OSError), e:
print_e = e
try:
# That didn't work, so try opening the base name,
# so that if the actually passed in 'sconsign.dblite'
# (for example), the dbm module will put the suffix back
# on for us and open it anyway.
db = self.dbm.open(os.path.splitext(fname)[0], "r")
except (IOError, OSError):
# That didn't work either. See if the file name
# they specified just exists (independent of the dbm
# suffix-mangling).
try:
open(fname, "r")
except (IOError, OSError), e:
# Nope, that file doesn't even exist, so report that
# fact back.
print_e = e
sys.stderr.write("sconsign: %s\n" % (print_e))
return
except KeyboardInterrupt:
raise
except cPickle.UnpicklingError:
sys.stderr.write("sconsign: ignoring invalid `%s' file `%s'\n" % (self.dbm_name, fname))
return
except Exception, e:
sys.stderr.write("sconsign: ignoring invalid `%s' file `%s': %s\n" % (self.dbm_name, fname, e))
return
if Print_Directories:
for dir in Print_Directories:
try:
val = db[dir]
except KeyError:
sys.stderr.write("sconsign: no dir `%s' in `%s'\n" % (dir, args[0]))
else:
self.printentries(dir, val)
else:
keys = db.keys()
keys.sort()
for dir in keys:
self.printentries(dir, db[dir])
def printentries(self, dir, val):
print '=== ' + dir + ':'
printentries(cPickle.loads(val), dir)
def Do_SConsignDir(name):
try:
fp = open(name, 'rb')
except (IOError, OSError), e:
sys.stderr.write("sconsign: %s\n" % (e))
return
try:
sconsign = SCons.SConsign.Dir(fp)
except KeyboardInterrupt:
raise
except cPickle.UnpicklingError:
sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s'\n" % (name))
return
except Exception, e:
sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s': %s\n" % (name, e))
return
printentries(sconsign.entries, args[0])
##############################################################################
import getopt
helpstr = """\
Usage: sconsign [OPTIONS] FILE [...]
Options:
-a, --act, --action Print build action information.
-c, --csig Print content signature information.
-d DIR, --dir=DIR Print only info about DIR.
-e ENTRY, --entry=ENTRY Print only info about ENTRY.
-f FORMAT, --format=FORMAT FILE is in the specified FORMAT.
-h, --help Print this message and exit.
-i, --implicit Print implicit dependency information.
-r, --readable Print timestamps in human-readable form.
--raw Print raw Python object representations.
-s, --size Print file sizes.
-t, --timestamp Print timestamp information.
-v, --verbose Verbose, describe each field.
"""
opts, args = getopt.getopt(sys.argv[1:], "acd:e:f:hirstv",
['act', 'action',
'csig', 'dir=', 'entry=',
'format=', 'help', 'implicit',
'raw', 'readable',
'size', 'timestamp', 'verbose'])
for o, a in opts:
if o in ('-a', '--act', '--action'):
Print_Flags['action'] = 1
elif o in ('-c', '--csig'):
Print_Flags['csig'] = 1
elif o in ('-d', '--dir'):
Print_Directories.append(a)
elif o in ('-e', '--entry'):
Print_Entries.append(a)
elif o in ('-f', '--format'):
Module_Map = {'dblite' : 'SCons.dblite',
'sconsign' : None}
dbm_name = Module_Map.get(a, a)
if dbm_name:
try:
dbm = my_import(dbm_name)
except:
sys.stderr.write("sconsign: illegal file format `%s'\n" % a)
print helpstr
sys.exit(2)
Do_Call = Do_SConsignDB(a, dbm)
else:
Do_Call = Do_SConsignDir
elif o in ('-h', '--help'):
print helpstr
sys.exit(0)
elif o in ('-i', '--implicit'):
Print_Flags['implicit'] = 1
elif o in ('--raw',):
nodeinfo_string = nodeinfo_raw
elif o in ('-r', '--readable'):
Readable = 1
elif o in ('-s', '--size'):
Print_Flags['size'] = 1
elif o in ('-t', '--timestamp'):
Print_Flags['timestamp'] = 1
elif o in ('-v', '--verbose'):
Verbose = 1
if Do_Call:
for a in args:
Do_Call(a)
else:
for a in args:
dbm_name = whichdb.whichdb(a)
if dbm_name:
Map_Module = {'SCons.dblite' : 'dblite'}
dbm = my_import(dbm_name)
Do_SConsignDB(Map_Module.get(dbm_name, dbm_name), dbm)(a)
else:
Do_SConsignDir(a)
sys.exit(0)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#!/usr/bin/env python
#
# scons-time - run SCons timings and collect statistics
#
# A script for running a configuration through SCons with a standard
# set of invocations to collect timing and memory statistics and to
# capture the results in a consistent set of output files for display
# and analysis.
#
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from __future__ import nested_scopes
__revision__ = "src/script/scons-time.py 4720 2010/03/24 03:14:11 jars"
import getopt
import glob
import os
import os.path
import re
import shutil
import string
import sys
import tempfile
import time
try:
False
except NameError:
# Pre-2.2 Python has no False keyword.
import __builtin__
__builtin__.False = not 1
try:
True
except NameError:
# Pre-2.2 Python has no True keyword.
import __builtin__
__builtin__.True = not 0
def make_temp_file(**kw):
try:
result = tempfile.mktemp(**kw)
try:
result = os.path.realpath(result)
except AttributeError:
# Python 2.1 has no os.path.realpath() method.
pass
except TypeError:
try:
save_template = tempfile.template
prefix = kw['prefix']
del kw['prefix']
tempfile.template = prefix
result = tempfile.mktemp(**kw)
finally:
tempfile.template = save_template
return result
def HACK_for_exec(cmd, *args):
'''
For some reason, Python won't allow an exec() within a function
that also declares an internal function (including lambda functions).
This function is a hack that calls exec() in a function with no
internal functions.
'''
if not args: exec(cmd)
elif len(args) == 1: exec cmd in args[0]
else: exec cmd in args[0], args[1]
class Plotter:
def increment_size(self, largest):
"""
Return the size of each horizontal increment line for a specified
maximum value. This returns a value that will provide somewhere
between 5 and 9 horizontal lines on the graph, on some set of
boundaries that are multiples of 10/100/1000/etc.
"""
i = largest / 5
if not i:
return largest
multiplier = 1
while i >= 10:
i = i / 10
multiplier = multiplier * 10
return i * multiplier
def max_graph_value(self, largest):
# Round up to next integer.
largest = int(largest) + 1
increment = self.increment_size(largest)
return ((largest + increment - 1) / increment) * increment
class Line:
def __init__(self, points, type, title, label, comment, fmt="%s %s"):
self.points = points
self.type = type
self.title = title
self.label = label
self.comment = comment
self.fmt = fmt
def print_label(self, inx, x, y):
if self.label:
print 'set label %s "%s" at %s,%s right' % (inx, self.label, x, y)
def plot_string(self):
if self.title:
title_string = 'title "%s"' % self.title
else:
title_string = 'notitle'
return "'-' %s with lines lt %s" % (title_string, self.type)
def print_points(self, fmt=None):
if fmt is None:
fmt = self.fmt
if self.comment:
print '# %s' % self.comment
for x, y in self.points:
# If y is None, it usually represents some kind of break
# in the line's index number. We might want to represent
# this some way rather than just drawing the line straight
# between the two points on either side.
if not y is None:
print fmt % (x, y)
print 'e'
def get_x_values(self):
return [ p[0] for p in self.points ]
def get_y_values(self):
return [ p[1] for p in self.points ]
class Gnuplotter(Plotter):
def __init__(self, title, key_location):
self.lines = []
self.title = title
self.key_location = key_location
def line(self, points, type, title=None, label=None, comment=None, fmt='%s %s'):
if points:
line = Line(points, type, title, label, comment, fmt)
self.lines.append(line)
def plot_string(self, line):
return line.plot_string()
def vertical_bar(self, x, type, label, comment):
if self.get_min_x() <= x and x <= self.get_max_x():
points = [(x, 0), (x, self.max_graph_value(self.get_max_y()))]
self.line(points, type, label, comment)
def get_all_x_values(self):
result = []
for line in self.lines:
result.extend(line.get_x_values())
return filter(lambda r: not r is None, result)
def get_all_y_values(self):
result = []
for line in self.lines:
result.extend(line.get_y_values())
return filter(lambda r: not r is None, result)
def get_min_x(self):
try:
return self.min_x
except AttributeError:
try:
self.min_x = min(self.get_all_x_values())
except ValueError:
self.min_x = 0
return self.min_x
def get_max_x(self):
try:
return self.max_x
except AttributeError:
try:
self.max_x = max(self.get_all_x_values())
except ValueError:
self.max_x = 0
return self.max_x
def get_min_y(self):
try:
return self.min_y
except AttributeError:
try:
self.min_y = min(self.get_all_y_values())
except ValueError:
self.min_y = 0
return self.min_y
def get_max_y(self):
try:
return self.max_y
except AttributeError:
try:
self.max_y = max(self.get_all_y_values())
except ValueError:
self.max_y = 0
return self.max_y
def draw(self):
if not self.lines:
return
if self.title:
print 'set title "%s"' % self.title
print 'set key %s' % self.key_location
min_y = self.get_min_y()
max_y = self.max_graph_value(self.get_max_y())
range = max_y - min_y
incr = range / 10.0
start = min_y + (max_y / 2.0) + (2.0 * incr)
position = [ start - (i * incr) for i in xrange(5) ]
inx = 1
for line in self.lines:
line.print_label(inx, line.points[0][0]-1,
position[(inx-1) % len(position)])
inx += 1
plot_strings = [ self.plot_string(l) for l in self.lines ]
print 'plot ' + ', \\\n '.join(plot_strings)
for line in self.lines:
line.print_points()
def untar(fname):
import tarfile
tar = tarfile.open(name=fname, mode='r')
for tarinfo in tar:
tar.extract(tarinfo)
tar.close()
def unzip(fname):
import zipfile
zf = zipfile.ZipFile(fname, 'r')
for name in zf.namelist():
dir = os.path.dirname(name)
try:
os.makedirs(dir)
except:
pass
open(name, 'w').write(zf.read(name))
def read_tree(dir):
def read_files(arg, dirname, fnames):
for fn in fnames:
fn = os.path.join(dirname, fn)
if os.path.isfile(fn):
open(fn, 'rb').read()
os.path.walk('.', read_files, None)
def redirect_to_file(command, log):
return '%s > %s 2>&1' % (command, log)
def tee_to_file(command, log):
return '%s 2>&1 | tee %s' % (command, log)
class SConsTimer:
"""
Usage: scons-time SUBCOMMAND [ARGUMENTS]
Type "scons-time help SUBCOMMAND" for help on a specific subcommand.
Available subcommands:
func Extract test-run data for a function
help Provides help
mem Extract --debug=memory data from test runs
obj Extract --debug=count data from test runs
time Extract --debug=time data from test runs
run Runs a test configuration
"""
name = 'scons-time'
name_spaces = ' '*len(name)
def makedict(**kw):
return kw
default_settings = makedict(
aegis = 'aegis',
aegis_project = None,
chdir = None,
config_file = None,
initial_commands = [],
key_location = 'bottom left',
orig_cwd = os.getcwd(),
outdir = None,
prefix = '',
python = '"%s"' % sys.executable,
redirect = redirect_to_file,
scons = None,
scons_flags = '--debug=count --debug=memory --debug=time --debug=memoizer',
scons_lib_dir = None,
scons_wrapper = None,
startup_targets = '--help',
subdir = None,
subversion_url = None,
svn = 'svn',
svn_co_flag = '-q',
tar = 'tar',
targets = '',
targets0 = None,
targets1 = None,
targets2 = None,
title = None,
unzip = 'unzip',
verbose = False,
vertical_bars = [],
unpack_map = {
'.tar.gz' : (untar, '%(tar)s xzf %%s'),
'.tgz' : (untar, '%(tar)s xzf %%s'),
'.tar' : (untar, '%(tar)s xf %%s'),
'.zip' : (unzip, '%(unzip)s %%s'),
},
)
run_titles = [
'Startup',
'Full build',
'Up-to-date build',
]
run_commands = [
'%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof0)s %(targets0)s',
'%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof1)s %(targets1)s',
'%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof2)s %(targets2)s',
]
stages = [
'pre-read',
'post-read',
'pre-build',
'post-build',
]
stage_strings = {
'pre-read' : 'Memory before reading SConscript files:',
'post-read' : 'Memory after reading SConscript files:',
'pre-build' : 'Memory before building targets:',
'post-build' : 'Memory after building targets:',
}
memory_string_all = 'Memory '
default_stage = stages[-1]
time_strings = {
'total' : 'Total build time',
'SConscripts' : 'Total SConscript file execution time',
'SCons' : 'Total SCons execution time',
'commands' : 'Total command execution time',
}
time_string_all = 'Total .* time'
#
def __init__(self):
self.__dict__.update(self.default_settings)
# Functions for displaying and executing commands.
def subst(self, x, dictionary):
try:
return x % dictionary
except TypeError:
# x isn't a string (it's probably a Python function),
# so just return it.
return x
def subst_variables(self, command, dictionary):
"""
Substitutes (via the format operator) the values in the specified
dictionary into the specified command.
The command can be an (action, string) tuple. In all cases, we
perform substitution on strings and don't worry if something isn't
a string. (It's probably a Python function to be executed.)
"""
try:
command + ''
except TypeError:
action = command[0]
string = command[1]
args = command[2:]
else:
action = command
string = action
args = (())
action = self.subst(action, dictionary)
string = self.subst(string, dictionary)
return (action, string, args)
def _do_not_display(self, msg, *args):
pass
def display(self, msg, *args):
"""
Displays the specified message.
Each message is prepended with a standard prefix of our name
plus the time.
"""
if callable(msg):
msg = msg(*args)
else:
msg = msg % args
if msg is None:
return
fmt = '%s[%s]: %s\n'
sys.stdout.write(fmt % (self.name, time.strftime('%H:%M:%S'), msg))
def _do_not_execute(self, action, *args):
pass
def execute(self, action, *args):
"""
Executes the specified action.
The action is called if it's a callable Python function, and
otherwise passed to os.system().
"""
if callable(action):
action(*args)
else:
os.system(action % args)
def run_command_list(self, commands, dict):
"""
Executes a list of commands, substituting values from the
specified dictionary.
"""
commands = [ self.subst_variables(c, dict) for c in commands ]
for action, string, args in commands:
self.display(string, *args)
sys.stdout.flush()
status = self.execute(action, *args)
if status:
sys.exit(status)
def log_display(self, command, log):
command = self.subst(command, self.__dict__)
if log:
command = self.redirect(command, log)
return command
def log_execute(self, command, log):
command = self.subst(command, self.__dict__)
output = os.popen(command).read()
if self.verbose:
sys.stdout.write(output)
open(log, 'wb').write(output)
#
def archive_splitext(self, path):
"""
Splits an archive name into a filename base and extension.
This is like os.path.splitext() (which it calls) except that it
also looks for '.tar.gz' and treats it as an atomic extensions.
"""
if path.endswith('.tar.gz'):
return path[:-7], path[-7:]
else:
return os.path.splitext(path)
def args_to_files(self, args, tail=None):
"""
Takes a list of arguments, expands any glob patterns, and
returns the last "tail" files from the list.
"""
files = []
for a in args:
g = glob.glob(a)
g.sort()
files.extend(g)
if tail:
files = files[-tail:]
return files
def ascii_table(self, files, columns,
line_function, file_function=lambda x: x,
*args, **kw):
header_fmt = ' '.join(['%12s'] * len(columns))
line_fmt = header_fmt + ' %s'
print header_fmt % columns
for file in files:
t = line_function(file, *args, **kw)
if t is None:
t = []
diff = len(columns) - len(t)
if diff > 0:
t += [''] * diff
t.append(file_function(file))
print line_fmt % tuple(t)
def collect_results(self, files, function, *args, **kw):
results = {}
for file in files:
base = os.path.splitext(file)[0]
run, index = string.split(base, '-')[-2:]
run = int(run)
index = int(index)
value = function(file, *args, **kw)
try:
r = results[index]
except KeyError:
r = []
results[index] = r
r.append((run, value))
return results
def doc_to_help(self, obj):
"""
Translates an object's __doc__ string into help text.
This strips a consistent number of spaces from each line in the
help text, essentially "outdenting" the text to the left-most
column.
"""
doc = obj.__doc__
if doc is None:
return ''
return self.outdent(doc)
def find_next_run_number(self, dir, prefix):
"""
Returns the next run number in a directory for the specified prefix.
Examines the contents the specified directory for files with the
specified prefix, extracts the run numbers from each file name,
and returns the next run number after the largest it finds.
"""
x = re.compile(re.escape(prefix) + '-([0-9]+).*')
matches = map(lambda e, x=x: x.match(e), os.listdir(dir))
matches = filter(None, matches)
if not matches:
return 0
run_numbers = map(lambda m: int(m.group(1)), matches)
return int(max(run_numbers)) + 1
def gnuplot_results(self, results, fmt='%s %.3f'):
"""
Prints out a set of results in Gnuplot format.
"""
gp = Gnuplotter(self.title, self.key_location)
indices = results.keys()
indices.sort()
for i in indices:
try:
t = self.run_titles[i]
except IndexError:
t = '??? %s ???' % i
results[i].sort()
gp.line(results[i], i+1, t, None, t, fmt=fmt)
for bar_tuple in self.vertical_bars:
try:
x, type, label, comment = bar_tuple
except ValueError:
x, type, label = bar_tuple
comment = label
gp.vertical_bar(x, type, label, comment)
gp.draw()
def logfile_name(self, invocation):
"""
Returns the absolute path of a log file for the specificed
invocation number.
"""
name = self.prefix_run + '-%d.log' % invocation
return os.path.join(self.outdir, name)
def outdent(self, s):
"""
Strip as many spaces from each line as are found at the beginning
of the first line in the list.
"""
lines = s.split('\n')
if lines[0] == '':
lines = lines[1:]
spaces = re.match(' *', lines[0]).group(0)
def strip_initial_spaces(l, s=spaces):
if l.startswith(spaces):
l = l[len(spaces):]
return l
return '\n'.join([ strip_initial_spaces(l) for l in lines ]) + '\n'
def profile_name(self, invocation):
"""
Returns the absolute path of a profile file for the specified
invocation number.
"""
name = self.prefix_run + '-%d.prof' % invocation
return os.path.join(self.outdir, name)
def set_env(self, key, value):
os.environ[key] = value
#
def get_debug_times(self, file, time_string=None):
"""
Fetch times from the --debug=time strings in the specified file.
"""
if time_string is None:
search_string = self.time_string_all
else:
search_string = time_string
contents = open(file).read()
if not contents:
sys.stderr.write('file %s has no contents!\n' % repr(file))
return None
result = re.findall(r'%s: ([\d\.]*)' % search_string, contents)[-4:]
result = [ float(r) for r in result ]
if not time_string is None:
try:
result = result[0]
except IndexError:
sys.stderr.write('file %s has no results!\n' % repr(file))
return None
return result
def get_function_profile(self, file, function):
"""
Returns the file, line number, function name, and cumulative time.
"""
try:
import pstats
except ImportError, e:
sys.stderr.write('%s: func: %s\n' % (self.name, e))
sys.stderr.write('%s This version of Python is missing the profiler.\n' % self.name_spaces)
sys.stderr.write('%s Cannot use the "func" subcommand.\n' % self.name_spaces)
sys.exit(1)
statistics = pstats.Stats(file).stats
matches = [ e for e in statistics.items() if e[0][2] == function ]
r = matches[0]
return r[0][0], r[0][1], r[0][2], r[1][3]
def get_function_time(self, file, function):
"""
Returns just the cumulative time for the specified function.
"""
return self.get_function_profile(file, function)[3]
def get_memory(self, file, memory_string=None):
"""
Returns a list of integers of the amount of memory used. The
default behavior is to return all the stages.
"""
if memory_string is None:
search_string = self.memory_string_all
else:
search_string = memory_string
lines = open(file).readlines()
lines = [ l for l in lines if l.startswith(search_string) ][-4:]
result = [ int(l.split()[-1]) for l in lines[-4:] ]
if len(result) == 1:
result = result[0]
return result
def get_object_counts(self, file, object_name, index=None):
"""
Returns the counts of the specified object_name.
"""
object_string = ' ' + object_name + '\n'
lines = open(file).readlines()
line = [ l for l in lines if l.endswith(object_string) ][0]
result = [ int(field) for field in line.split()[:4] ]
if index is not None:
result = result[index]
return result
#
command_alias = {}
def execute_subcommand(self, argv):
"""
Executes the do_*() function for the specified subcommand (argv[0]).
"""
if not argv:
return
cmdName = self.command_alias.get(argv[0], argv[0])
try:
func = getattr(self, 'do_' + cmdName)
except AttributeError:
return self.default(argv)
try:
return func(argv)
except TypeError, e:
sys.stderr.write("%s %s: %s\n" % (self.name, cmdName, e))
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.write("Try '%s help %s'\n" % (self.name, cmdName))
def default(self, argv):
"""
The default behavior for an unknown subcommand. Prints an
error message and exits.
"""
sys.stderr.write('%s: Unknown subcommand "%s".\n' % (self.name, argv[0]))
sys.stderr.write('Type "%s help" for usage.\n' % self.name)
sys.exit(1)
#
def do_help(self, argv):
"""
"""
if argv[1:]:
for arg in argv[1:]:
try:
func = getattr(self, 'do_' + arg)
except AttributeError:
sys.stderr.write('%s: No help for "%s"\n' % (self.name, arg))
else:
try:
help = getattr(self, 'help_' + arg)
except AttributeError:
sys.stdout.write(self.doc_to_help(func))
sys.stdout.flush()
else:
help()
else:
doc = self.doc_to_help(self.__class__)
if doc:
sys.stdout.write(doc)
sys.stdout.flush()
return None
#
def help_func(self):
help = """\
Usage: scons-time func [OPTIONS] FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
--func=NAME, --function=NAME Report time for function NAME
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--title=TITLE Specify the output plot TITLE
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_func(self, argv):
"""
"""
format = 'ascii'
function_name = '_main'
tail = None
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'func=',
'function=',
'help',
'prefix=',
'tail=',
'title=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('--func', '--function'):
function_name = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'func'])
sys.exit(0)
elif o in ('--max',):
max_time = int(a)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
if self.config_file:
exec open(self.config_file, 'rU').read() in self.__dict__
if self.chdir:
os.chdir(self.chdir)
if not args:
pattern = '%s*.prof' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: func: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.prof files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help func" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
for file in args:
try:
f, line, func, time = \
self.get_function_profile(file, function_name)
except ValueError, e:
sys.stderr.write("%s: func: %s: %s\n" %
(self.name, file, e))
else:
if f.startswith(cwd_):
f = f[len(cwd_):]
print "%.3f %s:%d(%s)" % (time, f, line, func)
elif format == 'gnuplot':
results = self.collect_results(args, self.get_function_time,
function_name)
self.gnuplot_results(results)
else:
sys.stderr.write('%s: func: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
#
def help_mem(self):
help = """\
Usage: scons-time mem [OPTIONS] FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
--stage=STAGE Plot memory at the specified stage:
pre-read, post-read, pre-build,
post-build (default: post-build)
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--title=TITLE Specify the output plot TITLE
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_mem(self, argv):
format = 'ascii'
logfile_path = lambda x: x
stage = self.default_stage
tail = None
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'help',
'prefix=',
'stage=',
'tail=',
'title=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'mem'])
sys.exit(0)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('--stage',):
if not a in self.stages:
sys.stderr.write('%s: mem: Unrecognized stage "%s".\n' % (self.name, a))
sys.exit(1)
stage = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
if self.config_file:
HACK_for_exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
logfile_path = lambda x, c=self.chdir: os.path.join(c, x)
if not args:
pattern = '%s*.log' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: mem: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help mem" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
self.ascii_table(args, tuple(self.stages), self.get_memory, logfile_path)
elif format == 'gnuplot':
results = self.collect_results(args, self.get_memory,
self.stage_strings[stage])
self.gnuplot_results(results)
else:
sys.stderr.write('%s: mem: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
return 0
#
def help_obj(self):
help = """\
Usage: scons-time obj [OPTIONS] OBJECT FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
--stage=STAGE Plot memory at the specified stage:
pre-read, post-read, pre-build,
post-build (default: post-build)
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--title=TITLE Specify the output plot TITLE
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_obj(self, argv):
format = 'ascii'
logfile_path = lambda x: x
stage = self.default_stage
tail = None
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'help',
'prefix=',
'stage=',
'tail=',
'title=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'obj'])
sys.exit(0)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('--stage',):
if not a in self.stages:
sys.stderr.write('%s: obj: Unrecognized stage "%s".\n' % (self.name, a))
sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
stage = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
if not args:
sys.stderr.write('%s: obj: Must specify an object name.\n' % self.name)
sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
object_name = args.pop(0)
if self.config_file:
HACK_for_exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
logfile_path = lambda x, c=self.chdir: os.path.join(c, x)
if not args:
pattern = '%s*.log' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: obj: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
self.ascii_table(args, tuple(self.stages), self.get_object_counts, logfile_path, object_name)
elif format == 'gnuplot':
stage_index = 0
for s in self.stages:
if stage == s:
break
stage_index = stage_index + 1
results = self.collect_results(args, self.get_object_counts,
object_name, stage_index)
self.gnuplot_results(results)
else:
sys.stderr.write('%s: obj: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
return 0
#
def help_run(self):
help = """\
Usage: scons-time run [OPTIONS] [FILE ...]
--aegis=PROJECT Use SCons from the Aegis PROJECT
--chdir=DIR Name of unpacked directory for chdir
-f FILE, --file=FILE Read configuration from specified FILE
-h, --help Print this help and exit
-n, --no-exec No execute, just print command lines
--number=NUMBER Put output in files for run NUMBER
--outdir=OUTDIR Put output files in OUTDIR
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
--python=PYTHON Time using the specified PYTHON
-q, --quiet Don't print command lines
--scons=SCONS Time using the specified SCONS
--svn=URL, --subversion=URL Use SCons from Subversion URL
-v, --verbose Display output of commands
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_run(self, argv):
"""
"""
run_number_list = [None]
short_opts = '?f:hnp:qs:v'
long_opts = [
'aegis=',
'file=',
'help',
'no-exec',
'number=',
'outdir=',
'prefix=',
'python=',
'quiet',
'scons=',
'svn=',
'subdir=',
'subversion=',
'verbose',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('--aegis',):
self.aegis_project = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'run'])
sys.exit(0)
elif o in ('-n', '--no-exec'):
self.execute = self._do_not_execute
elif o in ('--number',):
run_number_list = self.split_run_numbers(a)
elif o in ('--outdir',):
self.outdir = a
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('--python',):
self.python = a
elif o in ('-q', '--quiet'):
self.display = self._do_not_display
elif o in ('-s', '--subdir'):
self.subdir = a
elif o in ('--scons',):
self.scons = a
elif o in ('--svn', '--subversion'):
self.subversion_url = a
elif o in ('-v', '--verbose'):
self.redirect = tee_to_file
self.verbose = True
self.svn_co_flag = ''
if not args and not self.config_file:
sys.stderr.write('%s: run: No arguments or -f config file specified.\n' % self.name)
sys.stderr.write('%s Type "%s help run" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
if self.config_file:
exec open(self.config_file, 'rU').read() in self.__dict__
if args:
self.archive_list = args
archive_file_name = os.path.split(self.archive_list[0])[1]
if not self.subdir:
self.subdir = self.archive_splitext(archive_file_name)[0]
if not self.prefix:
self.prefix = self.archive_splitext(archive_file_name)[0]
prepare = None
if self.subversion_url:
prepare = self.prep_subversion_run
elif self.aegis_project:
prepare = self.prep_aegis_run
for run_number in run_number_list:
self.individual_run(run_number, self.archive_list, prepare)
def split_run_numbers(self, s):
result = []
for n in s.split(','):
try:
x, y = n.split('-')
except ValueError:
result.append(int(n))
else:
result.extend(range(int(x), int(y)+1))
return result
def scons_path(self, dir):
return os.path.join(dir, 'src', 'script', 'scons.py')
def scons_lib_dir_path(self, dir):
return os.path.join(dir, 'src', 'engine')
def prep_aegis_run(self, commands, removals):
self.aegis_tmpdir = make_temp_file(prefix = self.name + '-aegis-')
removals.append((shutil.rmtree, 'rm -rf %%s', self.aegis_tmpdir))
self.aegis_parent_project = os.path.splitext(self.aegis_project)[0]
self.scons = self.scons_path(self.aegis_tmpdir)
self.scons_lib_dir = self.scons_lib_dir_path(self.aegis_tmpdir)
commands.extend([
'mkdir %(aegis_tmpdir)s',
(lambda: os.chdir(self.aegis_tmpdir), 'cd %(aegis_tmpdir)s'),
'%(aegis)s -cp -ind -p %(aegis_parent_project)s .',
'%(aegis)s -cp -ind -p %(aegis_project)s -delta %(run_number)s .',
])
def prep_subversion_run(self, commands, removals):
self.svn_tmpdir = make_temp_file(prefix = self.name + '-svn-')
removals.append((shutil.rmtree, 'rm -rf %%s', self.svn_tmpdir))
self.scons = self.scons_path(self.svn_tmpdir)
self.scons_lib_dir = self.scons_lib_dir_path(self.svn_tmpdir)
commands.extend([
'mkdir %(svn_tmpdir)s',
'%(svn)s co %(svn_co_flag)s -r %(run_number)s %(subversion_url)s %(svn_tmpdir)s',
])
def individual_run(self, run_number, archive_list, prepare=None):
"""
Performs an individual run of the default SCons invocations.
"""
commands = []
removals = []
if prepare:
prepare(commands, removals)
save_scons = self.scons
save_scons_wrapper = self.scons_wrapper
save_scons_lib_dir = self.scons_lib_dir
if self.outdir is None:
self.outdir = self.orig_cwd
elif not os.path.isabs(self.outdir):
self.outdir = os.path.join(self.orig_cwd, self.outdir)
if self.scons is None:
self.scons = self.scons_path(self.orig_cwd)
if self.scons_lib_dir is None:
self.scons_lib_dir = self.scons_lib_dir_path(self.orig_cwd)
if self.scons_wrapper is None:
self.scons_wrapper = self.scons
if not run_number:
run_number = self.find_next_run_number(self.outdir, self.prefix)
self.run_number = str(run_number)
self.prefix_run = self.prefix + '-%03d' % run_number
if self.targets0 is None:
self.targets0 = self.startup_targets
if self.targets1 is None:
self.targets1 = self.targets
if self.targets2 is None:
self.targets2 = self.targets
self.tmpdir = make_temp_file(prefix = self.name + '-')
commands.extend([
'mkdir %(tmpdir)s',
(os.chdir, 'cd %%s', self.tmpdir),
])
for archive in archive_list:
if not os.path.isabs(archive):
archive = os.path.join(self.orig_cwd, archive)
if os.path.isdir(archive):
dest = os.path.split(archive)[1]
commands.append((shutil.copytree, 'cp -r %%s %%s', archive, dest))
else:
suffix = self.archive_splitext(archive)[1]
unpack_command = self.unpack_map.get(suffix)
if not unpack_command:
dest = os.path.split(archive)[1]
commands.append((shutil.copyfile, 'cp %%s %%s', archive, dest))
else:
commands.append(unpack_command + (archive,))
commands.extend([
(os.chdir, 'cd %%s', self.subdir),
])
commands.extend(self.initial_commands)
commands.extend([
(lambda: read_tree('.'),
'find * -type f | xargs cat > /dev/null'),
(self.set_env, 'export %%s=%%s',
'SCONS_LIB_DIR', self.scons_lib_dir),
'%(python)s %(scons_wrapper)s --version',
])
index = 0
for run_command in self.run_commands:
setattr(self, 'prof%d' % index, self.profile_name(index))
c = (
self.log_execute,
self.log_display,
run_command,
self.logfile_name(index),
)
commands.append(c)
index = index + 1
commands.extend([
(os.chdir, 'cd %%s', self.orig_cwd),
])
if not os.environ.get('PRESERVE'):
commands.extend(removals)
commands.append((shutil.rmtree, 'rm -rf %%s', self.tmpdir))
self.run_command_list(commands, self.__dict__)
self.scons = save_scons
self.scons_lib_dir = save_scons_lib_dir
self.scons_wrapper = save_scons_wrapper
#
def help_time(self):
help = """\
Usage: scons-time time [OPTIONS] FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--which=TIMER Plot timings for TIMER: total,
SConscripts, SCons, commands.
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_time(self, argv):
format = 'ascii'
logfile_path = lambda x: x
tail = None
which = 'total'
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'help',
'prefix=',
'tail=',
'title=',
'which=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'time'])
sys.exit(0)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
elif o in ('--which',):
if not a in self.time_strings.keys():
sys.stderr.write('%s: time: Unrecognized timer "%s".\n' % (self.name, a))
sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
which = a
if self.config_file:
HACK_for_exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
logfile_path = lambda x, c=self.chdir: os.path.join(c, x)
if not args:
pattern = '%s*.log' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: time: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
columns = ("Total", "SConscripts", "SCons", "commands")
self.ascii_table(args, columns, self.get_debug_times, logfile_path)
elif format == 'gnuplot':
results = self.collect_results(args, self.get_debug_times,
self.time_strings[which])
self.gnuplot_results(results, fmt='%s %.6f')
else:
sys.stderr.write('%s: time: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], 'h?V', ['help', 'version'])
ST = SConsTimer()
for o, a in opts:
if o in ('-?', '-h', '--help'):
ST.do_help(['help'])
sys.exit(0)
elif o in ('-V', '--version'):
sys.stdout.write('scons-time version\n')
sys.exit(0)
if not args:
sys.stderr.write('Type "%s help" for usage.\n' % ST.name)
sys.exit(1)
ST.execute_subcommand(args)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""
Notes:
- shared library support is buggy: it assumes that a static and dynamic library can be build from the same object files. This is not true on many platforms. For this reason it is only enabled on linux-gcc at the current time.
To add a platform:
- add its name in options allowed_values below
- add tool initialization for this platform. Search for "if platform == 'suncc'" as an example.
"""
import os
import os.path
import sys
JSONCPP_VERSION = open(File('#version').abspath,'rt').read().strip()
DIST_DIR = '#dist'
options = Variables()
options.Add( EnumVariable('platform',
'Platform (compiler/stl) used to build the project',
'msvc71',
allowed_values='suncc vacpp mingw msvc6 msvc7 msvc71 msvc80 linux-gcc'.split(),
ignorecase=2) )
try:
platform = ARGUMENTS['platform']
if platform == 'linux-gcc':
CXX = 'g++' # not quite right, but env is not yet available.
import commands
version = commands.getoutput('%s -dumpversion' %CXX)
platform = 'linux-gcc-%s' %version
print "Using platform '%s'" %platform
LD_LIBRARY_PATH = os.environ.get('LD_LIBRARY_PATH', '')
LD_LIBRARY_PATH = "%s:libs/%s" %(LD_LIBRARY_PATH, platform)
os.environ['LD_LIBRARY_PATH'] = LD_LIBRARY_PATH
print "LD_LIBRARY_PATH =", LD_LIBRARY_PATH
except KeyError:
print 'You must specify a "platform"'
sys.exit(2)
print "Building using PLATFORM =", platform
rootbuild_dir = Dir('#buildscons')
build_dir = os.path.join( '#buildscons', platform )
bin_dir = os.path.join( '#bin', platform )
lib_dir = os.path.join( '#libs', platform )
sconsign_dir_path = Dir(build_dir).abspath
sconsign_path = os.path.join( sconsign_dir_path, '.sconsign.dbm' )
# Ensure build directory exist (SConsignFile fail otherwise!)
if not os.path.exists( sconsign_dir_path ):
os.makedirs( sconsign_dir_path )
# Store all dependencies signature in a database
SConsignFile( sconsign_path )
def make_environ_vars():
"""Returns a dictionnary with environment variable to use when compiling."""
# PATH is required to find the compiler
# TEMP is required for at least mingw
vars = {}
for name in ('PATH', 'TEMP', 'TMP'):
if name in os.environ:
vars[name] = os.environ[name]
return vars
env = Environment( ENV = make_environ_vars(),
toolpath = ['scons-tools'],
tools=[] ) #, tools=['default'] )
if platform == 'suncc':
env.Tool( 'sunc++' )
env.Tool( 'sunlink' )
env.Tool( 'sunar' )
env.Append( CCFLAGS = ['-mt'] )
elif platform == 'vacpp':
env.Tool( 'default' )
env.Tool( 'aixcc' )
env['CXX'] = 'xlC_r' #scons does not pick-up the correct one !
# using xlC_r ensure multi-threading is enabled:
# http://publib.boulder.ibm.com/infocenter/pseries/index.jsp?topic=/com.ibm.vacpp7a.doc/compiler/ref/cuselect.htm
env.Append( CCFLAGS = '-qrtti=all',
LINKFLAGS='-bh:5' ) # -bh:5 remove duplicate symbol warning
elif platform == 'msvc6':
env['MSVS_VERSION']='6.0'
for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']:
env.Tool( tool )
env['CXXFLAGS']='-GR -GX /nologo /MT'
elif platform == 'msvc70':
env['MSVS_VERSION']='7.0'
for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']:
env.Tool( tool )
env['CXXFLAGS']='-GR -GX /nologo /MT'
elif platform == 'msvc71':
env['MSVS_VERSION']='7.1'
for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']:
env.Tool( tool )
env['CXXFLAGS']='-GR -GX /nologo /MT'
elif platform == 'msvc80':
env['MSVS_VERSION']='8.0'
for tool in ['msvc', 'msvs', 'mslink', 'masm', 'mslib']:
env.Tool( tool )
env['CXXFLAGS']='-GR -EHsc /nologo /MT'
elif platform == 'mingw':
env.Tool( 'mingw' )
env.Append( CPPDEFINES=[ "WIN32", "NDEBUG", "_MT" ] )
elif platform.startswith('linux-gcc'):
env.Tool( 'default' )
env.Append( LIBS = ['pthread'], CCFLAGS = "-Wall" )
env['SHARED_LIB_ENABLED'] = True
else:
print "UNSUPPORTED PLATFORM."
env.Exit(1)
env.Tool('targz')
env.Tool('srcdist')
env.Tool('globtool')
env.Append( CPPPATH = ['#include'],
LIBPATH = lib_dir )
short_platform = platform
if short_platform.startswith('msvc'):
short_platform = short_platform[2:]
# Notes: on Windows you need to rebuild the source for each variant
# Build script does not support that yet so we only build static libraries.
# This also fails on AIX because both dynamic and static library ends with
# extension .a.
env['SHARED_LIB_ENABLED'] = env.get('SHARED_LIB_ENABLED', False)
env['LIB_PLATFORM'] = short_platform
env['LIB_LINK_TYPE'] = 'lib' # static
env['LIB_CRUNTIME'] = 'mt'
env['LIB_NAME_SUFFIX'] = '${LIB_PLATFORM}_${LIB_LINK_TYPE}${LIB_CRUNTIME}' # must match autolink naming convention
env['JSONCPP_VERSION'] = JSONCPP_VERSION
env['BUILD_DIR'] = env.Dir(build_dir)
env['ROOTBUILD_DIR'] = env.Dir(rootbuild_dir)
env['DIST_DIR'] = DIST_DIR
if 'TarGz' in env['BUILDERS']:
class SrcDistAdder:
def __init__( self, env ):
self.env = env
def __call__( self, *args, **kw ):
apply( self.env.SrcDist, (self.env['SRCDIST_TARGET'],) + args, kw )
env['SRCDIST_BUILDER'] = env.TarGz
else: # If tarfile module is missing
class SrcDistAdder:
def __init__( self, env ):
pass
def __call__( self, *args, **kw ):
pass
env['SRCDIST_ADD'] = SrcDistAdder( env )
env['SRCDIST_TARGET'] = os.path.join( DIST_DIR, 'jsoncpp-src-%s.tar.gz' % env['JSONCPP_VERSION'] )
env_testing = env.Clone( )
env_testing.Append( LIBS = ['json_${LIB_NAME_SUFFIX}'] )
def buildJSONExample( env, target_sources, target_name ):
env = env.Clone()
env.Append( CPPPATH = ['#'] )
exe = env.Program( target=target_name,
source=target_sources )
env['SRCDIST_ADD']( source=[target_sources] )
global bin_dir
return env.Install( bin_dir, exe )
def buildJSONTests( env, target_sources, target_name ):
jsontests_node = buildJSONExample( env, target_sources, target_name )
check_alias_target = env.Alias( 'check', jsontests_node, RunJSONTests( jsontests_node, jsontests_node ) )
env.AlwaysBuild( check_alias_target )
def buildUnitTests( env, target_sources, target_name ):
jsontests_node = buildJSONExample( env, target_sources, target_name )
check_alias_target = env.Alias( 'check', jsontests_node,
RunUnitTests( jsontests_node, jsontests_node ) )
env.AlwaysBuild( check_alias_target )
def buildLibrary( env, target_sources, target_name ):
static_lib = env.StaticLibrary( target=target_name + '_${LIB_NAME_SUFFIX}',
source=target_sources )
global lib_dir
env.Install( lib_dir, static_lib )
if env['SHARED_LIB_ENABLED']:
shared_lib = env.SharedLibrary( target=target_name + '_${LIB_NAME_SUFFIX}',
source=target_sources )
env.Install( lib_dir, shared_lib )
env['SRCDIST_ADD']( source=[target_sources] )
Export( 'env env_testing buildJSONExample buildLibrary buildJSONTests buildUnitTests' )
def buildProjectInDirectory( target_directory ):
global build_dir
target_build_dir = os.path.join( build_dir, target_directory )
target = os.path.join( target_directory, 'sconscript' )
SConscript( target, build_dir=target_build_dir, duplicate=0 )
env['SRCDIST_ADD']( source=[target] )
def runJSONTests_action( target, source = None, env = None ):
# Add test scripts to python path
jsontest_path = Dir( '#test' ).abspath
sys.path.insert( 0, jsontest_path )
data_path = os.path.join( jsontest_path, 'data' )
import runjsontests
return runjsontests.runAllTests( os.path.abspath(source[0].path), data_path )
def runJSONTests_string( target, source = None, env = None ):
return 'RunJSONTests("%s")' % source[0]
import SCons.Action
ActionFactory = SCons.Action.ActionFactory
RunJSONTests = ActionFactory(runJSONTests_action, runJSONTests_string )
def runUnitTests_action( target, source = None, env = None ):
# Add test scripts to python path
jsontest_path = Dir( '#test' ).abspath
sys.path.insert( 0, jsontest_path )
import rununittests
return rununittests.runAllTests( os.path.abspath(source[0].path) )
def runUnitTests_string( target, source = None, env = None ):
return 'RunUnitTests("%s")' % source[0]
RunUnitTests = ActionFactory(runUnitTests_action, runUnitTests_string )
env.Alias( 'check' )
srcdist_cmd = env['SRCDIST_ADD']( source = """
AUTHORS README.txt SConstruct
""".split() )
env.Alias( 'src-dist', srcdist_cmd )
buildProjectInDirectory( 'src/jsontestrunner' )
buildProjectInDirectory( 'src/lib_json' )
buildProjectInDirectory( 'src/test_lib_json' )
#print env.Dump()
| Python |
#! /usr/bin/env python
#
# SCons - a Software Constructor
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/script/scons.py 4720 2010/03/24 03:14:11 jars"
__version__ = "1.3.0"
__build__ = "r4720"
__buildsys__ = "jars-desktop"
__date__ = "2010/03/24 03:14:11"
__developer__ = "jars"
import os
import os.path
import sys
##############################################################################
# BEGIN STANDARD SCons SCRIPT HEADER
#
# This is the cut-and-paste logic so that a self-contained script can
# interoperate correctly with different SCons versions and installation
# locations for the engine. If you modify anything in this section, you
# should also change other scripts that use this same header.
##############################################################################
# Strip the script directory from sys.path() so on case-insensitive
# (WIN32) systems Python doesn't think that the "scons" script is the
# "SCons" package. Replace it with our own library directories
# (version-specific first, in case they installed by hand there,
# followed by generic) so we pick up the right version of the build
# engine modules if they're in either directory.
# Check to see if the python version is > 3.0 which is currently unsupported
# If so exit with error message
try:
if sys.version_info >= (3,0,0):
msg = "scons: *** SCons version %s does not run under Python version %s.\n"
sys.stderr.write(msg % (__version__, sys.version.split()[0]))
sys.exit(1)
except AttributeError:
# Pre-1.6 Python has no sys.version_info
# No need to check version as we then know the version is < 3.0.0 and supported
pass
script_dir = sys.path[0]
if script_dir in sys.path:
sys.path.remove(script_dir)
libs = []
if os.environ.has_key("SCONS_LIB_DIR"):
libs.append(os.environ["SCONS_LIB_DIR"])
local_version = 'scons-local-' + __version__
local = 'scons-local'
if script_dir:
local_version = os.path.join(script_dir, local_version)
local = os.path.join(script_dir, local)
libs.append(os.path.abspath(local_version))
libs.append(os.path.abspath(local))
scons_version = 'scons-%s' % __version__
prefs = []
if sys.platform == 'win32':
# sys.prefix is (likely) C:\Python*;
# check only C:\Python*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, 'Lib', 'site-packages'))
else:
# On other (POSIX) platforms, things are more complicated due to
# the variety of path names and library locations. Try to be smart
# about it.
if script_dir == 'bin':
# script_dir is `pwd`/bin;
# check `pwd`/lib/scons*.
prefs.append(os.getcwd())
else:
if script_dir == '.' or script_dir == '':
script_dir = os.getcwd()
head, tail = os.path.split(script_dir)
if tail == "bin":
# script_dir is /foo/bin;
# check /foo/lib/scons*.
prefs.append(head)
head, tail = os.path.split(sys.prefix)
if tail == "usr":
# sys.prefix is /foo/usr;
# check /foo/usr/lib/scons* first,
# then /foo/usr/local/lib/scons*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, "local"))
elif tail == "local":
h, t = os.path.split(head)
if t == "usr":
# sys.prefix is /foo/usr/local;
# check /foo/usr/local/lib/scons* first,
# then /foo/usr/lib/scons*.
prefs.append(sys.prefix)
prefs.append(head)
else:
# sys.prefix is /foo/local;
# check only /foo/local/lib/scons*.
prefs.append(sys.prefix)
else:
# sys.prefix is /foo (ends in neither /usr or /local);
# check only /foo/lib/scons*.
prefs.append(sys.prefix)
temp = map(lambda x: os.path.join(x, 'lib'), prefs)
temp.extend(map(lambda x: os.path.join(x,
'lib',
'python' + sys.version[:3],
'site-packages'),
prefs))
prefs = temp
# Add the parent directory of the current python's library to the
# preferences. On SuSE-91/AMD64, for example, this is /usr/lib64,
# not /usr/lib.
try:
libpath = os.__file__
except AttributeError:
pass
else:
# Split /usr/libfoo/python*/os.py to /usr/libfoo/python*.
libpath, tail = os.path.split(libpath)
# Split /usr/libfoo/python* to /usr/libfoo
libpath, tail = os.path.split(libpath)
# Check /usr/libfoo/scons*.
prefs.append(libpath)
try:
import pkg_resources
except ImportError:
pass
else:
# when running from an egg add the egg's directory
try:
d = pkg_resources.get_distribution('scons')
except pkg_resources.DistributionNotFound:
pass
else:
prefs.append(d.location)
# Look first for 'scons-__version__' in all of our preference libs,
# then for 'scons'.
libs.extend(map(lambda x: os.path.join(x, scons_version), prefs))
libs.extend(map(lambda x: os.path.join(x, 'scons'), prefs))
sys.path = libs + sys.path
##############################################################################
# END STANDARD SCons SCRIPT HEADER
##############################################################################
if __name__ == "__main__":
import SCons.Script
# this does all the work, and calls sys.exit
# with the proper exit status when done.
SCons.Script.main()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#! /usr/bin/env python
#
# SCons - a Software Constructor
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/script/sconsign.py 4720 2010/03/24 03:14:11 jars"
__version__ = "1.3.0"
__build__ = "r4720"
__buildsys__ = "jars-desktop"
__date__ = "2010/03/24 03:14:11"
__developer__ = "jars"
import os
import os.path
import sys
import time
##############################################################################
# BEGIN STANDARD SCons SCRIPT HEADER
#
# This is the cut-and-paste logic so that a self-contained script can
# interoperate correctly with different SCons versions and installation
# locations for the engine. If you modify anything in this section, you
# should also change other scripts that use this same header.
##############################################################################
# Strip the script directory from sys.path() so on case-insensitive
# (WIN32) systems Python doesn't think that the "scons" script is the
# "SCons" package. Replace it with our own library directories
# (version-specific first, in case they installed by hand there,
# followed by generic) so we pick up the right version of the build
# engine modules if they're in either directory.
script_dir = sys.path[0]
if script_dir in sys.path:
sys.path.remove(script_dir)
libs = []
if os.environ.has_key("SCONS_LIB_DIR"):
libs.append(os.environ["SCONS_LIB_DIR"])
local_version = 'scons-local-' + __version__
local = 'scons-local'
if script_dir:
local_version = os.path.join(script_dir, local_version)
local = os.path.join(script_dir, local)
libs.append(os.path.abspath(local_version))
libs.append(os.path.abspath(local))
scons_version = 'scons-%s' % __version__
prefs = []
if sys.platform == 'win32':
# sys.prefix is (likely) C:\Python*;
# check only C:\Python*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, 'Lib', 'site-packages'))
else:
# On other (POSIX) platforms, things are more complicated due to
# the variety of path names and library locations. Try to be smart
# about it.
if script_dir == 'bin':
# script_dir is `pwd`/bin;
# check `pwd`/lib/scons*.
prefs.append(os.getcwd())
else:
if script_dir == '.' or script_dir == '':
script_dir = os.getcwd()
head, tail = os.path.split(script_dir)
if tail == "bin":
# script_dir is /foo/bin;
# check /foo/lib/scons*.
prefs.append(head)
head, tail = os.path.split(sys.prefix)
if tail == "usr":
# sys.prefix is /foo/usr;
# check /foo/usr/lib/scons* first,
# then /foo/usr/local/lib/scons*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, "local"))
elif tail == "local":
h, t = os.path.split(head)
if t == "usr":
# sys.prefix is /foo/usr/local;
# check /foo/usr/local/lib/scons* first,
# then /foo/usr/lib/scons*.
prefs.append(sys.prefix)
prefs.append(head)
else:
# sys.prefix is /foo/local;
# check only /foo/local/lib/scons*.
prefs.append(sys.prefix)
else:
# sys.prefix is /foo (ends in neither /usr or /local);
# check only /foo/lib/scons*.
prefs.append(sys.prefix)
temp = map(lambda x: os.path.join(x, 'lib'), prefs)
temp.extend(map(lambda x: os.path.join(x,
'lib',
'python' + sys.version[:3],
'site-packages'),
prefs))
prefs = temp
# Add the parent directory of the current python's library to the
# preferences. On SuSE-91/AMD64, for example, this is /usr/lib64,
# not /usr/lib.
try:
libpath = os.__file__
except AttributeError:
pass
else:
# Split /usr/libfoo/python*/os.py to /usr/libfoo/python*.
libpath, tail = os.path.split(libpath)
# Split /usr/libfoo/python* to /usr/libfoo
libpath, tail = os.path.split(libpath)
# Check /usr/libfoo/scons*.
prefs.append(libpath)
try:
import pkg_resources
except ImportError:
pass
else:
# when running from an egg add the egg's directory
try:
d = pkg_resources.get_distribution('scons')
except pkg_resources.DistributionNotFound:
pass
else:
prefs.append(d.location)
# Look first for 'scons-__version__' in all of our preference libs,
# then for 'scons'.
libs.extend(map(lambda x: os.path.join(x, scons_version), prefs))
libs.extend(map(lambda x: os.path.join(x, 'scons'), prefs))
sys.path = libs + sys.path
##############################################################################
# END STANDARD SCons SCRIPT HEADER
##############################################################################
import cPickle
import imp
import string
import whichdb
import SCons.SConsign
def my_whichdb(filename):
if filename[-7:] == ".dblite":
return "SCons.dblite"
try:
f = open(filename + ".dblite", "rb")
f.close()
return "SCons.dblite"
except IOError:
pass
return _orig_whichdb(filename)
_orig_whichdb = whichdb.whichdb
whichdb.whichdb = my_whichdb
def my_import(mname):
if '.' in mname:
i = string.rfind(mname, '.')
parent = my_import(mname[:i])
fp, pathname, description = imp.find_module(mname[i+1:],
parent.__path__)
else:
fp, pathname, description = imp.find_module(mname)
return imp.load_module(mname, fp, pathname, description)
class Flagger:
default_value = 1
def __setitem__(self, item, value):
self.__dict__[item] = value
self.default_value = 0
def __getitem__(self, item):
return self.__dict__.get(item, self.default_value)
Do_Call = None
Print_Directories = []
Print_Entries = []
Print_Flags = Flagger()
Verbose = 0
Readable = 0
def default_mapper(entry, name):
try:
val = eval("entry."+name)
except:
val = None
return str(val)
def map_action(entry, name):
try:
bact = entry.bact
bactsig = entry.bactsig
except AttributeError:
return None
return '%s [%s]' % (bactsig, bact)
def map_timestamp(entry, name):
try:
timestamp = entry.timestamp
except AttributeError:
timestamp = None
if Readable and timestamp:
return "'" + time.ctime(timestamp) + "'"
else:
return str(timestamp)
def map_bkids(entry, name):
try:
bkids = entry.bsources + entry.bdepends + entry.bimplicit
bkidsigs = entry.bsourcesigs + entry.bdependsigs + entry.bimplicitsigs
except AttributeError:
return None
result = []
for i in xrange(len(bkids)):
result.append(nodeinfo_string(bkids[i], bkidsigs[i], " "))
if result == []:
return None
return string.join(result, "\n ")
map_field = {
'action' : map_action,
'timestamp' : map_timestamp,
'bkids' : map_bkids,
}
map_name = {
'implicit' : 'bkids',
}
def field(name, entry, verbose=Verbose):
if not Print_Flags[name]:
return None
fieldname = map_name.get(name, name)
mapper = map_field.get(fieldname, default_mapper)
val = mapper(entry, name)
if verbose:
val = name + ": " + val
return val
def nodeinfo_raw(name, ninfo, prefix=""):
# This just formats the dictionary, which we would normally use str()
# to do, except that we want the keys sorted for deterministic output.
d = ninfo.__dict__
try:
keys = ninfo.field_list + ['_version_id']
except AttributeError:
keys = d.keys()
keys.sort()
l = []
for k in keys:
l.append('%s: %s' % (repr(k), repr(d.get(k))))
if '\n' in name:
name = repr(name)
return name + ': {' + string.join(l, ', ') + '}'
def nodeinfo_cooked(name, ninfo, prefix=""):
try:
field_list = ninfo.field_list
except AttributeError:
field_list = []
f = lambda x, ni=ninfo, v=Verbose: field(x, ni, v)
if '\n' in name:
name = repr(name)
outlist = [name+':'] + filter(None, map(f, field_list))
if Verbose:
sep = '\n ' + prefix
else:
sep = ' '
return string.join(outlist, sep)
nodeinfo_string = nodeinfo_cooked
def printfield(name, entry, prefix=""):
outlist = field("implicit", entry, 0)
if outlist:
if Verbose:
print " implicit:"
print " " + outlist
outact = field("action", entry, 0)
if outact:
if Verbose:
print " action: " + outact
else:
print " " + outact
def printentries(entries, location):
if Print_Entries:
for name in Print_Entries:
try:
entry = entries[name]
except KeyError:
sys.stderr.write("sconsign: no entry `%s' in `%s'\n" % (name, location))
else:
try:
ninfo = entry.ninfo
except AttributeError:
print name + ":"
else:
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
else:
names = entries.keys()
names.sort()
for name in names:
entry = entries[name]
try:
ninfo = entry.ninfo
except AttributeError:
print name + ":"
else:
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
class Do_SConsignDB:
def __init__(self, dbm_name, dbm):
self.dbm_name = dbm_name
self.dbm = dbm
def __call__(self, fname):
# The *dbm modules stick their own file suffixes on the names
# that are passed in. This is causes us to jump through some
# hoops here to be able to allow the user
try:
# Try opening the specified file name. Example:
# SPECIFIED OPENED BY self.dbm.open()
# --------- -------------------------
# .sconsign => .sconsign.dblite
# .sconsign.dblite => .sconsign.dblite.dblite
db = self.dbm.open(fname, "r")
except (IOError, OSError), e:
print_e = e
try:
# That didn't work, so try opening the base name,
# so that if the actually passed in 'sconsign.dblite'
# (for example), the dbm module will put the suffix back
# on for us and open it anyway.
db = self.dbm.open(os.path.splitext(fname)[0], "r")
except (IOError, OSError):
# That didn't work either. See if the file name
# they specified just exists (independent of the dbm
# suffix-mangling).
try:
open(fname, "r")
except (IOError, OSError), e:
# Nope, that file doesn't even exist, so report that
# fact back.
print_e = e
sys.stderr.write("sconsign: %s\n" % (print_e))
return
except KeyboardInterrupt:
raise
except cPickle.UnpicklingError:
sys.stderr.write("sconsign: ignoring invalid `%s' file `%s'\n" % (self.dbm_name, fname))
return
except Exception, e:
sys.stderr.write("sconsign: ignoring invalid `%s' file `%s': %s\n" % (self.dbm_name, fname, e))
return
if Print_Directories:
for dir in Print_Directories:
try:
val = db[dir]
except KeyError:
sys.stderr.write("sconsign: no dir `%s' in `%s'\n" % (dir, args[0]))
else:
self.printentries(dir, val)
else:
keys = db.keys()
keys.sort()
for dir in keys:
self.printentries(dir, db[dir])
def printentries(self, dir, val):
print '=== ' + dir + ':'
printentries(cPickle.loads(val), dir)
def Do_SConsignDir(name):
try:
fp = open(name, 'rb')
except (IOError, OSError), e:
sys.stderr.write("sconsign: %s\n" % (e))
return
try:
sconsign = SCons.SConsign.Dir(fp)
except KeyboardInterrupt:
raise
except cPickle.UnpicklingError:
sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s'\n" % (name))
return
except Exception, e:
sys.stderr.write("sconsign: ignoring invalid .sconsign file `%s': %s\n" % (name, e))
return
printentries(sconsign.entries, args[0])
##############################################################################
import getopt
helpstr = """\
Usage: sconsign [OPTIONS] FILE [...]
Options:
-a, --act, --action Print build action information.
-c, --csig Print content signature information.
-d DIR, --dir=DIR Print only info about DIR.
-e ENTRY, --entry=ENTRY Print only info about ENTRY.
-f FORMAT, --format=FORMAT FILE is in the specified FORMAT.
-h, --help Print this message and exit.
-i, --implicit Print implicit dependency information.
-r, --readable Print timestamps in human-readable form.
--raw Print raw Python object representations.
-s, --size Print file sizes.
-t, --timestamp Print timestamp information.
-v, --verbose Verbose, describe each field.
"""
opts, args = getopt.getopt(sys.argv[1:], "acd:e:f:hirstv",
['act', 'action',
'csig', 'dir=', 'entry=',
'format=', 'help', 'implicit',
'raw', 'readable',
'size', 'timestamp', 'verbose'])
for o, a in opts:
if o in ('-a', '--act', '--action'):
Print_Flags['action'] = 1
elif o in ('-c', '--csig'):
Print_Flags['csig'] = 1
elif o in ('-d', '--dir'):
Print_Directories.append(a)
elif o in ('-e', '--entry'):
Print_Entries.append(a)
elif o in ('-f', '--format'):
Module_Map = {'dblite' : 'SCons.dblite',
'sconsign' : None}
dbm_name = Module_Map.get(a, a)
if dbm_name:
try:
dbm = my_import(dbm_name)
except:
sys.stderr.write("sconsign: illegal file format `%s'\n" % a)
print helpstr
sys.exit(2)
Do_Call = Do_SConsignDB(a, dbm)
else:
Do_Call = Do_SConsignDir
elif o in ('-h', '--help'):
print helpstr
sys.exit(0)
elif o in ('-i', '--implicit'):
Print_Flags['implicit'] = 1
elif o in ('--raw',):
nodeinfo_string = nodeinfo_raw
elif o in ('-r', '--readable'):
Readable = 1
elif o in ('-s', '--size'):
Print_Flags['size'] = 1
elif o in ('-t', '--timestamp'):
Print_Flags['timestamp'] = 1
elif o in ('-v', '--verbose'):
Verbose = 1
if Do_Call:
for a in args:
Do_Call(a)
else:
for a in args:
dbm_name = whichdb.whichdb(a)
if dbm_name:
Map_Module = {'SCons.dblite' : 'dblite'}
dbm = my_import(dbm_name)
Do_SConsignDB(Map_Module.get(dbm_name, dbm_name), dbm)(a)
else:
Do_SConsignDir(a)
sys.exit(0)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#!/usr/bin/env python
#
# scons-time - run SCons timings and collect statistics
#
# A script for running a configuration through SCons with a standard
# set of invocations to collect timing and memory statistics and to
# capture the results in a consistent set of output files for display
# and analysis.
#
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
from __future__ import nested_scopes
__revision__ = "src/script/scons-time.py 4720 2010/03/24 03:14:11 jars"
import getopt
import glob
import os
import os.path
import re
import shutil
import string
import sys
import tempfile
import time
try:
False
except NameError:
# Pre-2.2 Python has no False keyword.
import __builtin__
__builtin__.False = not 1
try:
True
except NameError:
# Pre-2.2 Python has no True keyword.
import __builtin__
__builtin__.True = not 0
def make_temp_file(**kw):
try:
result = tempfile.mktemp(**kw)
try:
result = os.path.realpath(result)
except AttributeError:
# Python 2.1 has no os.path.realpath() method.
pass
except TypeError:
try:
save_template = tempfile.template
prefix = kw['prefix']
del kw['prefix']
tempfile.template = prefix
result = tempfile.mktemp(**kw)
finally:
tempfile.template = save_template
return result
def HACK_for_exec(cmd, *args):
'''
For some reason, Python won't allow an exec() within a function
that also declares an internal function (including lambda functions).
This function is a hack that calls exec() in a function with no
internal functions.
'''
if not args: exec(cmd)
elif len(args) == 1: exec cmd in args[0]
else: exec cmd in args[0], args[1]
class Plotter:
def increment_size(self, largest):
"""
Return the size of each horizontal increment line for a specified
maximum value. This returns a value that will provide somewhere
between 5 and 9 horizontal lines on the graph, on some set of
boundaries that are multiples of 10/100/1000/etc.
"""
i = largest / 5
if not i:
return largest
multiplier = 1
while i >= 10:
i = i / 10
multiplier = multiplier * 10
return i * multiplier
def max_graph_value(self, largest):
# Round up to next integer.
largest = int(largest) + 1
increment = self.increment_size(largest)
return ((largest + increment - 1) / increment) * increment
class Line:
def __init__(self, points, type, title, label, comment, fmt="%s %s"):
self.points = points
self.type = type
self.title = title
self.label = label
self.comment = comment
self.fmt = fmt
def print_label(self, inx, x, y):
if self.label:
print 'set label %s "%s" at %s,%s right' % (inx, self.label, x, y)
def plot_string(self):
if self.title:
title_string = 'title "%s"' % self.title
else:
title_string = 'notitle'
return "'-' %s with lines lt %s" % (title_string, self.type)
def print_points(self, fmt=None):
if fmt is None:
fmt = self.fmt
if self.comment:
print '# %s' % self.comment
for x, y in self.points:
# If y is None, it usually represents some kind of break
# in the line's index number. We might want to represent
# this some way rather than just drawing the line straight
# between the two points on either side.
if not y is None:
print fmt % (x, y)
print 'e'
def get_x_values(self):
return [ p[0] for p in self.points ]
def get_y_values(self):
return [ p[1] for p in self.points ]
class Gnuplotter(Plotter):
def __init__(self, title, key_location):
self.lines = []
self.title = title
self.key_location = key_location
def line(self, points, type, title=None, label=None, comment=None, fmt='%s %s'):
if points:
line = Line(points, type, title, label, comment, fmt)
self.lines.append(line)
def plot_string(self, line):
return line.plot_string()
def vertical_bar(self, x, type, label, comment):
if self.get_min_x() <= x and x <= self.get_max_x():
points = [(x, 0), (x, self.max_graph_value(self.get_max_y()))]
self.line(points, type, label, comment)
def get_all_x_values(self):
result = []
for line in self.lines:
result.extend(line.get_x_values())
return filter(lambda r: not r is None, result)
def get_all_y_values(self):
result = []
for line in self.lines:
result.extend(line.get_y_values())
return filter(lambda r: not r is None, result)
def get_min_x(self):
try:
return self.min_x
except AttributeError:
try:
self.min_x = min(self.get_all_x_values())
except ValueError:
self.min_x = 0
return self.min_x
def get_max_x(self):
try:
return self.max_x
except AttributeError:
try:
self.max_x = max(self.get_all_x_values())
except ValueError:
self.max_x = 0
return self.max_x
def get_min_y(self):
try:
return self.min_y
except AttributeError:
try:
self.min_y = min(self.get_all_y_values())
except ValueError:
self.min_y = 0
return self.min_y
def get_max_y(self):
try:
return self.max_y
except AttributeError:
try:
self.max_y = max(self.get_all_y_values())
except ValueError:
self.max_y = 0
return self.max_y
def draw(self):
if not self.lines:
return
if self.title:
print 'set title "%s"' % self.title
print 'set key %s' % self.key_location
min_y = self.get_min_y()
max_y = self.max_graph_value(self.get_max_y())
range = max_y - min_y
incr = range / 10.0
start = min_y + (max_y / 2.0) + (2.0 * incr)
position = [ start - (i * incr) for i in xrange(5) ]
inx = 1
for line in self.lines:
line.print_label(inx, line.points[0][0]-1,
position[(inx-1) % len(position)])
inx += 1
plot_strings = [ self.plot_string(l) for l in self.lines ]
print 'plot ' + ', \\\n '.join(plot_strings)
for line in self.lines:
line.print_points()
def untar(fname):
import tarfile
tar = tarfile.open(name=fname, mode='r')
for tarinfo in tar:
tar.extract(tarinfo)
tar.close()
def unzip(fname):
import zipfile
zf = zipfile.ZipFile(fname, 'r')
for name in zf.namelist():
dir = os.path.dirname(name)
try:
os.makedirs(dir)
except:
pass
open(name, 'w').write(zf.read(name))
def read_tree(dir):
def read_files(arg, dirname, fnames):
for fn in fnames:
fn = os.path.join(dirname, fn)
if os.path.isfile(fn):
open(fn, 'rb').read()
os.path.walk('.', read_files, None)
def redirect_to_file(command, log):
return '%s > %s 2>&1' % (command, log)
def tee_to_file(command, log):
return '%s 2>&1 | tee %s' % (command, log)
class SConsTimer:
"""
Usage: scons-time SUBCOMMAND [ARGUMENTS]
Type "scons-time help SUBCOMMAND" for help on a specific subcommand.
Available subcommands:
func Extract test-run data for a function
help Provides help
mem Extract --debug=memory data from test runs
obj Extract --debug=count data from test runs
time Extract --debug=time data from test runs
run Runs a test configuration
"""
name = 'scons-time'
name_spaces = ' '*len(name)
def makedict(**kw):
return kw
default_settings = makedict(
aegis = 'aegis',
aegis_project = None,
chdir = None,
config_file = None,
initial_commands = [],
key_location = 'bottom left',
orig_cwd = os.getcwd(),
outdir = None,
prefix = '',
python = '"%s"' % sys.executable,
redirect = redirect_to_file,
scons = None,
scons_flags = '--debug=count --debug=memory --debug=time --debug=memoizer',
scons_lib_dir = None,
scons_wrapper = None,
startup_targets = '--help',
subdir = None,
subversion_url = None,
svn = 'svn',
svn_co_flag = '-q',
tar = 'tar',
targets = '',
targets0 = None,
targets1 = None,
targets2 = None,
title = None,
unzip = 'unzip',
verbose = False,
vertical_bars = [],
unpack_map = {
'.tar.gz' : (untar, '%(tar)s xzf %%s'),
'.tgz' : (untar, '%(tar)s xzf %%s'),
'.tar' : (untar, '%(tar)s xf %%s'),
'.zip' : (unzip, '%(unzip)s %%s'),
},
)
run_titles = [
'Startup',
'Full build',
'Up-to-date build',
]
run_commands = [
'%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof0)s %(targets0)s',
'%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof1)s %(targets1)s',
'%(python)s %(scons_wrapper)s %(scons_flags)s --profile=%(prof2)s %(targets2)s',
]
stages = [
'pre-read',
'post-read',
'pre-build',
'post-build',
]
stage_strings = {
'pre-read' : 'Memory before reading SConscript files:',
'post-read' : 'Memory after reading SConscript files:',
'pre-build' : 'Memory before building targets:',
'post-build' : 'Memory after building targets:',
}
memory_string_all = 'Memory '
default_stage = stages[-1]
time_strings = {
'total' : 'Total build time',
'SConscripts' : 'Total SConscript file execution time',
'SCons' : 'Total SCons execution time',
'commands' : 'Total command execution time',
}
time_string_all = 'Total .* time'
#
def __init__(self):
self.__dict__.update(self.default_settings)
# Functions for displaying and executing commands.
def subst(self, x, dictionary):
try:
return x % dictionary
except TypeError:
# x isn't a string (it's probably a Python function),
# so just return it.
return x
def subst_variables(self, command, dictionary):
"""
Substitutes (via the format operator) the values in the specified
dictionary into the specified command.
The command can be an (action, string) tuple. In all cases, we
perform substitution on strings and don't worry if something isn't
a string. (It's probably a Python function to be executed.)
"""
try:
command + ''
except TypeError:
action = command[0]
string = command[1]
args = command[2:]
else:
action = command
string = action
args = (())
action = self.subst(action, dictionary)
string = self.subst(string, dictionary)
return (action, string, args)
def _do_not_display(self, msg, *args):
pass
def display(self, msg, *args):
"""
Displays the specified message.
Each message is prepended with a standard prefix of our name
plus the time.
"""
if callable(msg):
msg = msg(*args)
else:
msg = msg % args
if msg is None:
return
fmt = '%s[%s]: %s\n'
sys.stdout.write(fmt % (self.name, time.strftime('%H:%M:%S'), msg))
def _do_not_execute(self, action, *args):
pass
def execute(self, action, *args):
"""
Executes the specified action.
The action is called if it's a callable Python function, and
otherwise passed to os.system().
"""
if callable(action):
action(*args)
else:
os.system(action % args)
def run_command_list(self, commands, dict):
"""
Executes a list of commands, substituting values from the
specified dictionary.
"""
commands = [ self.subst_variables(c, dict) for c in commands ]
for action, string, args in commands:
self.display(string, *args)
sys.stdout.flush()
status = self.execute(action, *args)
if status:
sys.exit(status)
def log_display(self, command, log):
command = self.subst(command, self.__dict__)
if log:
command = self.redirect(command, log)
return command
def log_execute(self, command, log):
command = self.subst(command, self.__dict__)
output = os.popen(command).read()
if self.verbose:
sys.stdout.write(output)
open(log, 'wb').write(output)
#
def archive_splitext(self, path):
"""
Splits an archive name into a filename base and extension.
This is like os.path.splitext() (which it calls) except that it
also looks for '.tar.gz' and treats it as an atomic extensions.
"""
if path.endswith('.tar.gz'):
return path[:-7], path[-7:]
else:
return os.path.splitext(path)
def args_to_files(self, args, tail=None):
"""
Takes a list of arguments, expands any glob patterns, and
returns the last "tail" files from the list.
"""
files = []
for a in args:
g = glob.glob(a)
g.sort()
files.extend(g)
if tail:
files = files[-tail:]
return files
def ascii_table(self, files, columns,
line_function, file_function=lambda x: x,
*args, **kw):
header_fmt = ' '.join(['%12s'] * len(columns))
line_fmt = header_fmt + ' %s'
print header_fmt % columns
for file in files:
t = line_function(file, *args, **kw)
if t is None:
t = []
diff = len(columns) - len(t)
if diff > 0:
t += [''] * diff
t.append(file_function(file))
print line_fmt % tuple(t)
def collect_results(self, files, function, *args, **kw):
results = {}
for file in files:
base = os.path.splitext(file)[0]
run, index = string.split(base, '-')[-2:]
run = int(run)
index = int(index)
value = function(file, *args, **kw)
try:
r = results[index]
except KeyError:
r = []
results[index] = r
r.append((run, value))
return results
def doc_to_help(self, obj):
"""
Translates an object's __doc__ string into help text.
This strips a consistent number of spaces from each line in the
help text, essentially "outdenting" the text to the left-most
column.
"""
doc = obj.__doc__
if doc is None:
return ''
return self.outdent(doc)
def find_next_run_number(self, dir, prefix):
"""
Returns the next run number in a directory for the specified prefix.
Examines the contents the specified directory for files with the
specified prefix, extracts the run numbers from each file name,
and returns the next run number after the largest it finds.
"""
x = re.compile(re.escape(prefix) + '-([0-9]+).*')
matches = map(lambda e, x=x: x.match(e), os.listdir(dir))
matches = filter(None, matches)
if not matches:
return 0
run_numbers = map(lambda m: int(m.group(1)), matches)
return int(max(run_numbers)) + 1
def gnuplot_results(self, results, fmt='%s %.3f'):
"""
Prints out a set of results in Gnuplot format.
"""
gp = Gnuplotter(self.title, self.key_location)
indices = results.keys()
indices.sort()
for i in indices:
try:
t = self.run_titles[i]
except IndexError:
t = '??? %s ???' % i
results[i].sort()
gp.line(results[i], i+1, t, None, t, fmt=fmt)
for bar_tuple in self.vertical_bars:
try:
x, type, label, comment = bar_tuple
except ValueError:
x, type, label = bar_tuple
comment = label
gp.vertical_bar(x, type, label, comment)
gp.draw()
def logfile_name(self, invocation):
"""
Returns the absolute path of a log file for the specificed
invocation number.
"""
name = self.prefix_run + '-%d.log' % invocation
return os.path.join(self.outdir, name)
def outdent(self, s):
"""
Strip as many spaces from each line as are found at the beginning
of the first line in the list.
"""
lines = s.split('\n')
if lines[0] == '':
lines = lines[1:]
spaces = re.match(' *', lines[0]).group(0)
def strip_initial_spaces(l, s=spaces):
if l.startswith(spaces):
l = l[len(spaces):]
return l
return '\n'.join([ strip_initial_spaces(l) for l in lines ]) + '\n'
def profile_name(self, invocation):
"""
Returns the absolute path of a profile file for the specified
invocation number.
"""
name = self.prefix_run + '-%d.prof' % invocation
return os.path.join(self.outdir, name)
def set_env(self, key, value):
os.environ[key] = value
#
def get_debug_times(self, file, time_string=None):
"""
Fetch times from the --debug=time strings in the specified file.
"""
if time_string is None:
search_string = self.time_string_all
else:
search_string = time_string
contents = open(file).read()
if not contents:
sys.stderr.write('file %s has no contents!\n' % repr(file))
return None
result = re.findall(r'%s: ([\d\.]*)' % search_string, contents)[-4:]
result = [ float(r) for r in result ]
if not time_string is None:
try:
result = result[0]
except IndexError:
sys.stderr.write('file %s has no results!\n' % repr(file))
return None
return result
def get_function_profile(self, file, function):
"""
Returns the file, line number, function name, and cumulative time.
"""
try:
import pstats
except ImportError, e:
sys.stderr.write('%s: func: %s\n' % (self.name, e))
sys.stderr.write('%s This version of Python is missing the profiler.\n' % self.name_spaces)
sys.stderr.write('%s Cannot use the "func" subcommand.\n' % self.name_spaces)
sys.exit(1)
statistics = pstats.Stats(file).stats
matches = [ e for e in statistics.items() if e[0][2] == function ]
r = matches[0]
return r[0][0], r[0][1], r[0][2], r[1][3]
def get_function_time(self, file, function):
"""
Returns just the cumulative time for the specified function.
"""
return self.get_function_profile(file, function)[3]
def get_memory(self, file, memory_string=None):
"""
Returns a list of integers of the amount of memory used. The
default behavior is to return all the stages.
"""
if memory_string is None:
search_string = self.memory_string_all
else:
search_string = memory_string
lines = open(file).readlines()
lines = [ l for l in lines if l.startswith(search_string) ][-4:]
result = [ int(l.split()[-1]) for l in lines[-4:] ]
if len(result) == 1:
result = result[0]
return result
def get_object_counts(self, file, object_name, index=None):
"""
Returns the counts of the specified object_name.
"""
object_string = ' ' + object_name + '\n'
lines = open(file).readlines()
line = [ l for l in lines if l.endswith(object_string) ][0]
result = [ int(field) for field in line.split()[:4] ]
if index is not None:
result = result[index]
return result
#
command_alias = {}
def execute_subcommand(self, argv):
"""
Executes the do_*() function for the specified subcommand (argv[0]).
"""
if not argv:
return
cmdName = self.command_alias.get(argv[0], argv[0])
try:
func = getattr(self, 'do_' + cmdName)
except AttributeError:
return self.default(argv)
try:
return func(argv)
except TypeError, e:
sys.stderr.write("%s %s: %s\n" % (self.name, cmdName, e))
import traceback
traceback.print_exc(file=sys.stderr)
sys.stderr.write("Try '%s help %s'\n" % (self.name, cmdName))
def default(self, argv):
"""
The default behavior for an unknown subcommand. Prints an
error message and exits.
"""
sys.stderr.write('%s: Unknown subcommand "%s".\n' % (self.name, argv[0]))
sys.stderr.write('Type "%s help" for usage.\n' % self.name)
sys.exit(1)
#
def do_help(self, argv):
"""
"""
if argv[1:]:
for arg in argv[1:]:
try:
func = getattr(self, 'do_' + arg)
except AttributeError:
sys.stderr.write('%s: No help for "%s"\n' % (self.name, arg))
else:
try:
help = getattr(self, 'help_' + arg)
except AttributeError:
sys.stdout.write(self.doc_to_help(func))
sys.stdout.flush()
else:
help()
else:
doc = self.doc_to_help(self.__class__)
if doc:
sys.stdout.write(doc)
sys.stdout.flush()
return None
#
def help_func(self):
help = """\
Usage: scons-time func [OPTIONS] FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
--func=NAME, --function=NAME Report time for function NAME
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--title=TITLE Specify the output plot TITLE
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_func(self, argv):
"""
"""
format = 'ascii'
function_name = '_main'
tail = None
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'func=',
'function=',
'help',
'prefix=',
'tail=',
'title=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('--func', '--function'):
function_name = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'func'])
sys.exit(0)
elif o in ('--max',):
max_time = int(a)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
if self.config_file:
exec open(self.config_file, 'rU').read() in self.__dict__
if self.chdir:
os.chdir(self.chdir)
if not args:
pattern = '%s*.prof' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: func: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.prof files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help func" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
for file in args:
try:
f, line, func, time = \
self.get_function_profile(file, function_name)
except ValueError, e:
sys.stderr.write("%s: func: %s: %s\n" %
(self.name, file, e))
else:
if f.startswith(cwd_):
f = f[len(cwd_):]
print "%.3f %s:%d(%s)" % (time, f, line, func)
elif format == 'gnuplot':
results = self.collect_results(args, self.get_function_time,
function_name)
self.gnuplot_results(results)
else:
sys.stderr.write('%s: func: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
#
def help_mem(self):
help = """\
Usage: scons-time mem [OPTIONS] FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
--stage=STAGE Plot memory at the specified stage:
pre-read, post-read, pre-build,
post-build (default: post-build)
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--title=TITLE Specify the output plot TITLE
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_mem(self, argv):
format = 'ascii'
logfile_path = lambda x: x
stage = self.default_stage
tail = None
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'help',
'prefix=',
'stage=',
'tail=',
'title=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'mem'])
sys.exit(0)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('--stage',):
if not a in self.stages:
sys.stderr.write('%s: mem: Unrecognized stage "%s".\n' % (self.name, a))
sys.exit(1)
stage = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
if self.config_file:
HACK_for_exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
logfile_path = lambda x, c=self.chdir: os.path.join(c, x)
if not args:
pattern = '%s*.log' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: mem: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help mem" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
self.ascii_table(args, tuple(self.stages), self.get_memory, logfile_path)
elif format == 'gnuplot':
results = self.collect_results(args, self.get_memory,
self.stage_strings[stage])
self.gnuplot_results(results)
else:
sys.stderr.write('%s: mem: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
return 0
#
def help_obj(self):
help = """\
Usage: scons-time obj [OPTIONS] OBJECT FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
--stage=STAGE Plot memory at the specified stage:
pre-read, post-read, pre-build,
post-build (default: post-build)
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--title=TITLE Specify the output plot TITLE
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_obj(self, argv):
format = 'ascii'
logfile_path = lambda x: x
stage = self.default_stage
tail = None
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'help',
'prefix=',
'stage=',
'tail=',
'title=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'obj'])
sys.exit(0)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('--stage',):
if not a in self.stages:
sys.stderr.write('%s: obj: Unrecognized stage "%s".\n' % (self.name, a))
sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
stage = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
if not args:
sys.stderr.write('%s: obj: Must specify an object name.\n' % self.name)
sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
object_name = args.pop(0)
if self.config_file:
HACK_for_exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
logfile_path = lambda x, c=self.chdir: os.path.join(c, x)
if not args:
pattern = '%s*.log' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: obj: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help obj" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
self.ascii_table(args, tuple(self.stages), self.get_object_counts, logfile_path, object_name)
elif format == 'gnuplot':
stage_index = 0
for s in self.stages:
if stage == s:
break
stage_index = stage_index + 1
results = self.collect_results(args, self.get_object_counts,
object_name, stage_index)
self.gnuplot_results(results)
else:
sys.stderr.write('%s: obj: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
return 0
#
def help_run(self):
help = """\
Usage: scons-time run [OPTIONS] [FILE ...]
--aegis=PROJECT Use SCons from the Aegis PROJECT
--chdir=DIR Name of unpacked directory for chdir
-f FILE, --file=FILE Read configuration from specified FILE
-h, --help Print this help and exit
-n, --no-exec No execute, just print command lines
--number=NUMBER Put output in files for run NUMBER
--outdir=OUTDIR Put output files in OUTDIR
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
--python=PYTHON Time using the specified PYTHON
-q, --quiet Don't print command lines
--scons=SCONS Time using the specified SCONS
--svn=URL, --subversion=URL Use SCons from Subversion URL
-v, --verbose Display output of commands
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_run(self, argv):
"""
"""
run_number_list = [None]
short_opts = '?f:hnp:qs:v'
long_opts = [
'aegis=',
'file=',
'help',
'no-exec',
'number=',
'outdir=',
'prefix=',
'python=',
'quiet',
'scons=',
'svn=',
'subdir=',
'subversion=',
'verbose',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('--aegis',):
self.aegis_project = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'run'])
sys.exit(0)
elif o in ('-n', '--no-exec'):
self.execute = self._do_not_execute
elif o in ('--number',):
run_number_list = self.split_run_numbers(a)
elif o in ('--outdir',):
self.outdir = a
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('--python',):
self.python = a
elif o in ('-q', '--quiet'):
self.display = self._do_not_display
elif o in ('-s', '--subdir'):
self.subdir = a
elif o in ('--scons',):
self.scons = a
elif o in ('--svn', '--subversion'):
self.subversion_url = a
elif o in ('-v', '--verbose'):
self.redirect = tee_to_file
self.verbose = True
self.svn_co_flag = ''
if not args and not self.config_file:
sys.stderr.write('%s: run: No arguments or -f config file specified.\n' % self.name)
sys.stderr.write('%s Type "%s help run" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
if self.config_file:
exec open(self.config_file, 'rU').read() in self.__dict__
if args:
self.archive_list = args
archive_file_name = os.path.split(self.archive_list[0])[1]
if not self.subdir:
self.subdir = self.archive_splitext(archive_file_name)[0]
if not self.prefix:
self.prefix = self.archive_splitext(archive_file_name)[0]
prepare = None
if self.subversion_url:
prepare = self.prep_subversion_run
elif self.aegis_project:
prepare = self.prep_aegis_run
for run_number in run_number_list:
self.individual_run(run_number, self.archive_list, prepare)
def split_run_numbers(self, s):
result = []
for n in s.split(','):
try:
x, y = n.split('-')
except ValueError:
result.append(int(n))
else:
result.extend(range(int(x), int(y)+1))
return result
def scons_path(self, dir):
return os.path.join(dir, 'src', 'script', 'scons.py')
def scons_lib_dir_path(self, dir):
return os.path.join(dir, 'src', 'engine')
def prep_aegis_run(self, commands, removals):
self.aegis_tmpdir = make_temp_file(prefix = self.name + '-aegis-')
removals.append((shutil.rmtree, 'rm -rf %%s', self.aegis_tmpdir))
self.aegis_parent_project = os.path.splitext(self.aegis_project)[0]
self.scons = self.scons_path(self.aegis_tmpdir)
self.scons_lib_dir = self.scons_lib_dir_path(self.aegis_tmpdir)
commands.extend([
'mkdir %(aegis_tmpdir)s',
(lambda: os.chdir(self.aegis_tmpdir), 'cd %(aegis_tmpdir)s'),
'%(aegis)s -cp -ind -p %(aegis_parent_project)s .',
'%(aegis)s -cp -ind -p %(aegis_project)s -delta %(run_number)s .',
])
def prep_subversion_run(self, commands, removals):
self.svn_tmpdir = make_temp_file(prefix = self.name + '-svn-')
removals.append((shutil.rmtree, 'rm -rf %%s', self.svn_tmpdir))
self.scons = self.scons_path(self.svn_tmpdir)
self.scons_lib_dir = self.scons_lib_dir_path(self.svn_tmpdir)
commands.extend([
'mkdir %(svn_tmpdir)s',
'%(svn)s co %(svn_co_flag)s -r %(run_number)s %(subversion_url)s %(svn_tmpdir)s',
])
def individual_run(self, run_number, archive_list, prepare=None):
"""
Performs an individual run of the default SCons invocations.
"""
commands = []
removals = []
if prepare:
prepare(commands, removals)
save_scons = self.scons
save_scons_wrapper = self.scons_wrapper
save_scons_lib_dir = self.scons_lib_dir
if self.outdir is None:
self.outdir = self.orig_cwd
elif not os.path.isabs(self.outdir):
self.outdir = os.path.join(self.orig_cwd, self.outdir)
if self.scons is None:
self.scons = self.scons_path(self.orig_cwd)
if self.scons_lib_dir is None:
self.scons_lib_dir = self.scons_lib_dir_path(self.orig_cwd)
if self.scons_wrapper is None:
self.scons_wrapper = self.scons
if not run_number:
run_number = self.find_next_run_number(self.outdir, self.prefix)
self.run_number = str(run_number)
self.prefix_run = self.prefix + '-%03d' % run_number
if self.targets0 is None:
self.targets0 = self.startup_targets
if self.targets1 is None:
self.targets1 = self.targets
if self.targets2 is None:
self.targets2 = self.targets
self.tmpdir = make_temp_file(prefix = self.name + '-')
commands.extend([
'mkdir %(tmpdir)s',
(os.chdir, 'cd %%s', self.tmpdir),
])
for archive in archive_list:
if not os.path.isabs(archive):
archive = os.path.join(self.orig_cwd, archive)
if os.path.isdir(archive):
dest = os.path.split(archive)[1]
commands.append((shutil.copytree, 'cp -r %%s %%s', archive, dest))
else:
suffix = self.archive_splitext(archive)[1]
unpack_command = self.unpack_map.get(suffix)
if not unpack_command:
dest = os.path.split(archive)[1]
commands.append((shutil.copyfile, 'cp %%s %%s', archive, dest))
else:
commands.append(unpack_command + (archive,))
commands.extend([
(os.chdir, 'cd %%s', self.subdir),
])
commands.extend(self.initial_commands)
commands.extend([
(lambda: read_tree('.'),
'find * -type f | xargs cat > /dev/null'),
(self.set_env, 'export %%s=%%s',
'SCONS_LIB_DIR', self.scons_lib_dir),
'%(python)s %(scons_wrapper)s --version',
])
index = 0
for run_command in self.run_commands:
setattr(self, 'prof%d' % index, self.profile_name(index))
c = (
self.log_execute,
self.log_display,
run_command,
self.logfile_name(index),
)
commands.append(c)
index = index + 1
commands.extend([
(os.chdir, 'cd %%s', self.orig_cwd),
])
if not os.environ.get('PRESERVE'):
commands.extend(removals)
commands.append((shutil.rmtree, 'rm -rf %%s', self.tmpdir))
self.run_command_list(commands, self.__dict__)
self.scons = save_scons
self.scons_lib_dir = save_scons_lib_dir
self.scons_wrapper = save_scons_wrapper
#
def help_time(self):
help = """\
Usage: scons-time time [OPTIONS] FILE [...]
-C DIR, --chdir=DIR Change to DIR before looking for files
-f FILE, --file=FILE Read configuration from specified FILE
--fmt=FORMAT, --format=FORMAT Print data in specified FORMAT
-h, --help Print this help and exit
-p STRING, --prefix=STRING Use STRING as log file/profile prefix
-t NUMBER, --tail=NUMBER Only report the last NUMBER files
--which=TIMER Plot timings for TIMER: total,
SConscripts, SCons, commands.
"""
sys.stdout.write(self.outdent(help))
sys.stdout.flush()
def do_time(self, argv):
format = 'ascii'
logfile_path = lambda x: x
tail = None
which = 'total'
short_opts = '?C:f:hp:t:'
long_opts = [
'chdir=',
'file=',
'fmt=',
'format=',
'help',
'prefix=',
'tail=',
'title=',
'which=',
]
opts, args = getopt.getopt(argv[1:], short_opts, long_opts)
for o, a in opts:
if o in ('-C', '--chdir'):
self.chdir = a
elif o in ('-f', '--file'):
self.config_file = a
elif o in ('--fmt', '--format'):
format = a
elif o in ('-?', '-h', '--help'):
self.do_help(['help', 'time'])
sys.exit(0)
elif o in ('-p', '--prefix'):
self.prefix = a
elif o in ('-t', '--tail'):
tail = int(a)
elif o in ('--title',):
self.title = a
elif o in ('--which',):
if not a in self.time_strings.keys():
sys.stderr.write('%s: time: Unrecognized timer "%s".\n' % (self.name, a))
sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
which = a
if self.config_file:
HACK_for_exec(open(self.config_file, 'rU').read(), self.__dict__)
if self.chdir:
os.chdir(self.chdir)
logfile_path = lambda x, c=self.chdir: os.path.join(c, x)
if not args:
pattern = '%s*.log' % self.prefix
args = self.args_to_files([pattern], tail)
if not args:
if self.chdir:
directory = self.chdir
else:
directory = os.getcwd()
sys.stderr.write('%s: time: No arguments specified.\n' % self.name)
sys.stderr.write('%s No %s*.log files found in "%s".\n' % (self.name_spaces, self.prefix, directory))
sys.stderr.write('%s Type "%s help time" for help.\n' % (self.name_spaces, self.name))
sys.exit(1)
else:
args = self.args_to_files(args, tail)
cwd_ = os.getcwd() + os.sep
if format == 'ascii':
columns = ("Total", "SConscripts", "SCons", "commands")
self.ascii_table(args, columns, self.get_debug_times, logfile_path)
elif format == 'gnuplot':
results = self.collect_results(args, self.get_debug_times,
self.time_strings[which])
self.gnuplot_results(results, fmt='%s %.6f')
else:
sys.stderr.write('%s: time: Unknown format "%s".\n' % (self.name, format))
sys.exit(1)
if __name__ == '__main__':
opts, args = getopt.getopt(sys.argv[1:], 'h?V', ['help', 'version'])
ST = SConsTimer()
for o, a in opts:
if o in ('-?', '-h', '--help'):
ST.do_help(['help'])
sys.exit(0)
elif o in ('-V', '--version'):
sys.stdout.write('scons-time version\n')
sys.exit(0)
if not args:
sys.stderr.write('Type "%s help" for usage.\n' % ST.name)
sys.exit(1)
ST.execute_subcommand(args)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
import os.path
def fix_source_eol( path, is_dry_run = True, verbose = True, eol = '\n' ):
"""Makes sure that all sources have the specified eol sequence (default: unix)."""
if not os.path.isfile( path ):
raise ValueError( 'Path "%s" is not a file' % path )
try:
f = open(path, 'rb')
except IOError, msg:
print >> sys.stderr, "%s: I/O Error: %s" % (file, str(msg))
return False
try:
raw_lines = f.readlines()
finally:
f.close()
fixed_lines = [line.rstrip('\r\n') + eol for line in raw_lines]
if raw_lines != fixed_lines:
print '%s =>' % path,
if not is_dry_run:
f = open(path, "wb")
try:
f.writelines(fixed_lines)
finally:
f.close()
if verbose:
print is_dry_run and ' NEED FIX' or ' FIXED'
return True
##
##
##
##def _do_fix( is_dry_run = True ):
## from waftools import antglob
## python_sources = antglob.glob( '.',
## includes = '**/*.py **/wscript **/wscript_build',
## excludes = antglob.default_excludes + './waf.py',
## prune_dirs = antglob.prune_dirs + 'waf-* ./build' )
## for path in python_sources:
## _fix_python_source( path, is_dry_run )
##
## cpp_sources = antglob.glob( '.',
## includes = '**/*.cpp **/*.h **/*.inl',
## prune_dirs = antglob.prune_dirs + 'waf-* ./build' )
## for path in cpp_sources:
## _fix_source_eol( path, is_dry_run )
##
##
##def dry_fix(context):
## _do_fix( is_dry_run = True )
##
##def fix(context):
## _do_fix( is_dry_run = False )
##
##def shutdown():
## pass
##
##def check(context):
## # Unit tests are run when "check" target is used
## ut = UnitTest.unit_test()
## ut.change_to_testfile_dir = True
## ut.want_to_see_test_output = True
## ut.want_to_see_test_error = True
## ut.run()
## ut.print_results()
| Python |
#!/usr/bin/env python
# encoding: utf-8
# Baptiste Lepilleur, 2009
from dircache import listdir
import re
import fnmatch
import os.path
# These fnmatch expressions are used by default to prune the directory tree
# while doing the recursive traversal in the glob_impl method of glob function.
prune_dirs = '.git .bzr .hg .svn _MTN _darcs CVS SCCS '
# These fnmatch expressions are used by default to exclude files and dirs
# while doing the recursive traversal in the glob_impl method of glob function.
##exclude_pats = prune_pats + '*~ #*# .#* %*% ._* .gitignore .cvsignore vssver.scc .DS_Store'.split()
# These ant_glob expressions are used by default to exclude files and dirs and also prune the directory tree
# while doing the recursive traversal in the glob_impl method of glob function.
default_excludes = '''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.svn
**/.svn/**
**/.git
**/.git/**
**/.gitignore
**/.bzr
**/.bzr/**
**/.hg
**/.hg/**
**/_MTN
**/_MTN/**
**/_darcs
**/_darcs/**
**/.DS_Store '''
DIR = 1
FILE = 2
DIR_LINK = 4
FILE_LINK = 8
LINKS = DIR_LINK | FILE_LINK
ALL_NO_LINK = DIR | FILE
ALL = DIR | FILE | LINKS
_ANT_RE = re.compile( r'(/\*\*/)|(\*\*/)|(/\*\*)|(\*)|(/)|([^\*/]*)' )
def ant_pattern_to_re( ant_pattern ):
"""Generates a regular expression from the ant pattern.
Matching convention:
**/a: match 'a', 'dir/a', 'dir1/dir2/a'
a/**/b: match 'a/b', 'a/c/b', 'a/d/c/b'
*.py: match 'script.py' but not 'a/script.py'
"""
rex = ['^']
next_pos = 0
sep_rex = r'(?:/|%s)' % re.escape( os.path.sep )
## print 'Converting', ant_pattern
for match in _ANT_RE.finditer( ant_pattern ):
## print 'Matched', match.group()
## print match.start(0), next_pos
if match.start(0) != next_pos:
raise ValueError( "Invalid ant pattern" )
if match.group(1): # /**/
rex.append( sep_rex + '(?:.*%s)?' % sep_rex )
elif match.group(2): # **/
rex.append( '(?:.*%s)?' % sep_rex )
elif match.group(3): # /**
rex.append( sep_rex + '.*' )
elif match.group(4): # *
rex.append( '[^/%s]*' % re.escape(os.path.sep) )
elif match.group(5): # /
rex.append( sep_rex )
else: # somepath
rex.append( re.escape(match.group(6)) )
next_pos = match.end()
rex.append('$')
return re.compile( ''.join( rex ) )
def _as_list( l ):
if isinstance(l, basestring):
return l.split()
return l
def glob(dir_path,
includes = '**/*',
excludes = default_excludes,
entry_type = FILE,
prune_dirs = prune_dirs,
max_depth = 25):
include_filter = [ant_pattern_to_re(p) for p in _as_list(includes)]
exclude_filter = [ant_pattern_to_re(p) for p in _as_list(excludes)]
prune_dirs = [p.replace('/',os.path.sep) for p in _as_list(prune_dirs)]
dir_path = dir_path.replace('/',os.path.sep)
entry_type_filter = entry_type
def is_pruned_dir( dir_name ):
for pattern in prune_dirs:
if fnmatch.fnmatch( dir_name, pattern ):
return True
return False
def apply_filter( full_path, filter_rexs ):
"""Return True if at least one of the filter regular expression match full_path."""
for rex in filter_rexs:
if rex.match( full_path ):
return True
return False
def glob_impl( root_dir_path ):
child_dirs = [root_dir_path]
while child_dirs:
dir_path = child_dirs.pop()
for entry in listdir( dir_path ):
full_path = os.path.join( dir_path, entry )
## print 'Testing:', full_path,
is_dir = os.path.isdir( full_path )
if is_dir and not is_pruned_dir( entry ): # explore child directory ?
## print '===> marked for recursion',
child_dirs.append( full_path )
included = apply_filter( full_path, include_filter )
rejected = apply_filter( full_path, exclude_filter )
if not included or rejected: # do not include entry ?
## print '=> not included or rejected'
continue
link = os.path.islink( full_path )
is_file = os.path.isfile( full_path )
if not is_file and not is_dir:
## print '=> unknown entry type'
continue
if link:
entry_type = is_file and FILE_LINK or DIR_LINK
else:
entry_type = is_file and FILE or DIR
## print '=> type: %d' % entry_type,
if (entry_type & entry_type_filter) != 0:
## print ' => KEEP'
yield os.path.join( dir_path, entry )
## else:
## print ' => TYPE REJECTED'
return list( glob_impl( dir_path ) )
if __name__ == "__main__":
import unittest
class AntPatternToRETest(unittest.TestCase):
## def test_conversion( self ):
## self.assertEqual( '^somepath$', ant_pattern_to_re( 'somepath' ).pattern )
def test_matching( self ):
test_cases = [ ( 'path',
['path'],
['somepath', 'pathsuffix', '/path', '/path'] ),
( '*.py',
['source.py', 'source.ext.py', '.py'],
['path/source.py', '/.py', 'dir.py/z', 'z.pyc', 'z.c'] ),
( '**/path',
['path', '/path', '/a/path', 'c:/a/path', '/a/b/path', '//a/path', '/a/path/b/path'],
['path/', 'a/path/b', 'dir.py/z', 'somepath', 'pathsuffix', 'a/somepath'] ),
( 'path/**',
['path/a', 'path/path/a', 'path//'],
['path', 'somepath/a', 'a/path', 'a/path/a', 'pathsuffix/a'] ),
( '/**/path',
['/path', '/a/path', '/a/b/path/path', '/path/path'],
['path', 'path/', 'a/path', '/pathsuffix', '/somepath'] ),
( 'a/b',
['a/b'],
['somea/b', 'a/bsuffix', 'a/b/c'] ),
( '**/*.py',
['script.py', 'src/script.py', 'a/b/script.py', '/a/b/script.py'],
['script.pyc', 'script.pyo', 'a.py/b'] ),
( 'src/**/*.py',
['src/a.py', 'src/dir/a.py'],
['a/src/a.py', '/src/a.py'] ),
]
for ant_pattern, accepted_matches, rejected_matches in list(test_cases):
def local_path( paths ):
return [ p.replace('/',os.path.sep) for p in paths ]
test_cases.append( (ant_pattern, local_path(accepted_matches), local_path( rejected_matches )) )
for ant_pattern, accepted_matches, rejected_matches in test_cases:
rex = ant_pattern_to_re( ant_pattern )
print 'ant_pattern:', ant_pattern, ' => ', rex.pattern
for accepted_match in accepted_matches:
print 'Accepted?:', accepted_match
self.assert_( rex.match( accepted_match ) is not None )
for rejected_match in rejected_matches:
print 'Rejected?:', rejected_match
self.assert_( rex.match( rejected_match ) is None )
unittest.main()
| Python |
#!/usr/bin/env python
# encoding: utf-8
# Baptiste Lepilleur, 2009
from dircache import listdir
import re
import fnmatch
import os.path
# These fnmatch expressions are used by default to prune the directory tree
# while doing the recursive traversal in the glob_impl method of glob function.
prune_dirs = '.git .bzr .hg .svn _MTN _darcs CVS SCCS '
# These fnmatch expressions are used by default to exclude files and dirs
# while doing the recursive traversal in the glob_impl method of glob function.
##exclude_pats = prune_pats + '*~ #*# .#* %*% ._* .gitignore .cvsignore vssver.scc .DS_Store'.split()
# These ant_glob expressions are used by default to exclude files and dirs and also prune the directory tree
# while doing the recursive traversal in the glob_impl method of glob function.
default_excludes = '''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.svn
**/.svn/**
**/.git
**/.git/**
**/.gitignore
**/.bzr
**/.bzr/**
**/.hg
**/.hg/**
**/_MTN
**/_MTN/**
**/_darcs
**/_darcs/**
**/.DS_Store '''
DIR = 1
FILE = 2
DIR_LINK = 4
FILE_LINK = 8
LINKS = DIR_LINK | FILE_LINK
ALL_NO_LINK = DIR | FILE
ALL = DIR | FILE | LINKS
_ANT_RE = re.compile( r'(/\*\*/)|(\*\*/)|(/\*\*)|(\*)|(/)|([^\*/]*)' )
def ant_pattern_to_re( ant_pattern ):
"""Generates a regular expression from the ant pattern.
Matching convention:
**/a: match 'a', 'dir/a', 'dir1/dir2/a'
a/**/b: match 'a/b', 'a/c/b', 'a/d/c/b'
*.py: match 'script.py' but not 'a/script.py'
"""
rex = ['^']
next_pos = 0
sep_rex = r'(?:/|%s)' % re.escape( os.path.sep )
## print 'Converting', ant_pattern
for match in _ANT_RE.finditer( ant_pattern ):
## print 'Matched', match.group()
## print match.start(0), next_pos
if match.start(0) != next_pos:
raise ValueError( "Invalid ant pattern" )
if match.group(1): # /**/
rex.append( sep_rex + '(?:.*%s)?' % sep_rex )
elif match.group(2): # **/
rex.append( '(?:.*%s)?' % sep_rex )
elif match.group(3): # /**
rex.append( sep_rex + '.*' )
elif match.group(4): # *
rex.append( '[^/%s]*' % re.escape(os.path.sep) )
elif match.group(5): # /
rex.append( sep_rex )
else: # somepath
rex.append( re.escape(match.group(6)) )
next_pos = match.end()
rex.append('$')
return re.compile( ''.join( rex ) )
def _as_list( l ):
if isinstance(l, basestring):
return l.split()
return l
def glob(dir_path,
includes = '**/*',
excludes = default_excludes,
entry_type = FILE,
prune_dirs = prune_dirs,
max_depth = 25):
include_filter = [ant_pattern_to_re(p) for p in _as_list(includes)]
exclude_filter = [ant_pattern_to_re(p) for p in _as_list(excludes)]
prune_dirs = [p.replace('/',os.path.sep) for p in _as_list(prune_dirs)]
dir_path = dir_path.replace('/',os.path.sep)
entry_type_filter = entry_type
def is_pruned_dir( dir_name ):
for pattern in prune_dirs:
if fnmatch.fnmatch( dir_name, pattern ):
return True
return False
def apply_filter( full_path, filter_rexs ):
"""Return True if at least one of the filter regular expression match full_path."""
for rex in filter_rexs:
if rex.match( full_path ):
return True
return False
def glob_impl( root_dir_path ):
child_dirs = [root_dir_path]
while child_dirs:
dir_path = child_dirs.pop()
for entry in listdir( dir_path ):
full_path = os.path.join( dir_path, entry )
## print 'Testing:', full_path,
is_dir = os.path.isdir( full_path )
if is_dir and not is_pruned_dir( entry ): # explore child directory ?
## print '===> marked for recursion',
child_dirs.append( full_path )
included = apply_filter( full_path, include_filter )
rejected = apply_filter( full_path, exclude_filter )
if not included or rejected: # do not include entry ?
## print '=> not included or rejected'
continue
link = os.path.islink( full_path )
is_file = os.path.isfile( full_path )
if not is_file and not is_dir:
## print '=> unknown entry type'
continue
if link:
entry_type = is_file and FILE_LINK or DIR_LINK
else:
entry_type = is_file and FILE or DIR
## print '=> type: %d' % entry_type,
if (entry_type & entry_type_filter) != 0:
## print ' => KEEP'
yield os.path.join( dir_path, entry )
## else:
## print ' => TYPE REJECTED'
return list( glob_impl( dir_path ) )
if __name__ == "__main__":
import unittest
class AntPatternToRETest(unittest.TestCase):
## def test_conversion( self ):
## self.assertEqual( '^somepath$', ant_pattern_to_re( 'somepath' ).pattern )
def test_matching( self ):
test_cases = [ ( 'path',
['path'],
['somepath', 'pathsuffix', '/path', '/path'] ),
( '*.py',
['source.py', 'source.ext.py', '.py'],
['path/source.py', '/.py', 'dir.py/z', 'z.pyc', 'z.c'] ),
( '**/path',
['path', '/path', '/a/path', 'c:/a/path', '/a/b/path', '//a/path', '/a/path/b/path'],
['path/', 'a/path/b', 'dir.py/z', 'somepath', 'pathsuffix', 'a/somepath'] ),
( 'path/**',
['path/a', 'path/path/a', 'path//'],
['path', 'somepath/a', 'a/path', 'a/path/a', 'pathsuffix/a'] ),
( '/**/path',
['/path', '/a/path', '/a/b/path/path', '/path/path'],
['path', 'path/', 'a/path', '/pathsuffix', '/somepath'] ),
( 'a/b',
['a/b'],
['somea/b', 'a/bsuffix', 'a/b/c'] ),
( '**/*.py',
['script.py', 'src/script.py', 'a/b/script.py', '/a/b/script.py'],
['script.pyc', 'script.pyo', 'a.py/b'] ),
( 'src/**/*.py',
['src/a.py', 'src/dir/a.py'],
['a/src/a.py', '/src/a.py'] ),
]
for ant_pattern, accepted_matches, rejected_matches in list(test_cases):
def local_path( paths ):
return [ p.replace('/',os.path.sep) for p in paths ]
test_cases.append( (ant_pattern, local_path(accepted_matches), local_path( rejected_matches )) )
for ant_pattern, accepted_matches, rejected_matches in test_cases:
rex = ant_pattern_to_re( ant_pattern )
print 'ant_pattern:', ant_pattern, ' => ', rex.pattern
for accepted_match in accepted_matches:
print 'Accepted?:', accepted_match
self.assert_( rex.match( accepted_match ) is not None )
for rejected_match in rejected_matches:
print 'Rejected?:', rejected_match
self.assert_( rex.match( rejected_match ) is None )
unittest.main()
| Python |
# module
| Python |
import os.path
import gzip
import tarfile
TARGZ_DEFAULT_COMPRESSION_LEVEL = 9
def make_tarball(tarball_path, sources, base_dir, prefix_dir=''):
"""Parameters:
tarball_path: output path of the .tar.gz file
sources: list of sources to include in the tarball, relative to the current directory
base_dir: if a source file is in a sub-directory of base_dir, then base_dir is stripped
from path in the tarball.
prefix_dir: all files stored in the tarball be sub-directory of prefix_dir. Set to ''
to make them child of root.
"""
base_dir = os.path.normpath( os.path.abspath( base_dir ) )
def archive_name( path ):
"""Makes path relative to base_dir."""
path = os.path.normpath( os.path.abspath( path ) )
common_path = os.path.commonprefix( (base_dir, path) )
archive_name = path[len(common_path):]
if os.path.isabs( archive_name ):
archive_name = archive_name[1:]
return os.path.join( prefix_dir, archive_name )
def visit(tar, dirname, names):
for name in names:
path = os.path.join(dirname, name)
if os.path.isfile(path):
path_in_tar = archive_name(path)
tar.add(path, path_in_tar )
compression = TARGZ_DEFAULT_COMPRESSION_LEVEL
tar = tarfile.TarFile.gzopen( tarball_path, 'w', compresslevel=compression )
try:
for source in sources:
source_path = source
if os.path.isdir( source ):
os.path.walk(source_path, visit, tar)
else:
path_in_tar = archive_name(source_path)
tar.add(source_path, path_in_tar ) # filename, arcname
finally:
tar.close()
def decompress( tarball_path, base_dir ):
"""Decompress the gzipped tarball into directory base_dir.
"""
# !!! This class method is not documented in the online doc
# nor is bz2open!
tar = tarfile.TarFile.gzopen(tarball_path, mode='r')
try:
tar.extractall( base_dir )
finally:
tar.close()
| Python |
#! /usr/bin/env python
#
# SCons - a Software Constructor
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/script/scons.py 4720 2010/03/24 03:14:11 jars"
__version__ = "1.3.0"
__build__ = "r4720"
__buildsys__ = "jars-desktop"
__date__ = "2010/03/24 03:14:11"
__developer__ = "jars"
import os
import os.path
import sys
##############################################################################
# BEGIN STANDARD SCons SCRIPT HEADER
#
# This is the cut-and-paste logic so that a self-contained script can
# interoperate correctly with different SCons versions and installation
# locations for the engine. If you modify anything in this section, you
# should also change other scripts that use this same header.
##############################################################################
# Strip the script directory from sys.path() so on case-insensitive
# (WIN32) systems Python doesn't think that the "scons" script is the
# "SCons" package. Replace it with our own library directories
# (version-specific first, in case they installed by hand there,
# followed by generic) so we pick up the right version of the build
# engine modules if they're in either directory.
# Check to see if the python version is > 3.0 which is currently unsupported
# If so exit with error message
try:
if sys.version_info >= (3,0,0):
msg = "scons: *** SCons version %s does not run under Python version %s.\n"
sys.stderr.write(msg % (__version__, sys.version.split()[0]))
sys.exit(1)
except AttributeError:
# Pre-1.6 Python has no sys.version_info
# No need to check version as we then know the version is < 3.0.0 and supported
pass
script_dir = sys.path[0]
if script_dir in sys.path:
sys.path.remove(script_dir)
libs = []
if os.environ.has_key("SCONS_LIB_DIR"):
libs.append(os.environ["SCONS_LIB_DIR"])
local_version = 'scons-local-' + __version__
local = 'scons-local'
if script_dir:
local_version = os.path.join(script_dir, local_version)
local = os.path.join(script_dir, local)
libs.append(os.path.abspath(local_version))
libs.append(os.path.abspath(local))
scons_version = 'scons-%s' % __version__
prefs = []
if sys.platform == 'win32':
# sys.prefix is (likely) C:\Python*;
# check only C:\Python*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, 'Lib', 'site-packages'))
else:
# On other (POSIX) platforms, things are more complicated due to
# the variety of path names and library locations. Try to be smart
# about it.
if script_dir == 'bin':
# script_dir is `pwd`/bin;
# check `pwd`/lib/scons*.
prefs.append(os.getcwd())
else:
if script_dir == '.' or script_dir == '':
script_dir = os.getcwd()
head, tail = os.path.split(script_dir)
if tail == "bin":
# script_dir is /foo/bin;
# check /foo/lib/scons*.
prefs.append(head)
head, tail = os.path.split(sys.prefix)
if tail == "usr":
# sys.prefix is /foo/usr;
# check /foo/usr/lib/scons* first,
# then /foo/usr/local/lib/scons*.
prefs.append(sys.prefix)
prefs.append(os.path.join(sys.prefix, "local"))
elif tail == "local":
h, t = os.path.split(head)
if t == "usr":
# sys.prefix is /foo/usr/local;
# check /foo/usr/local/lib/scons* first,
# then /foo/usr/lib/scons*.
prefs.append(sys.prefix)
prefs.append(head)
else:
# sys.prefix is /foo/local;
# check only /foo/local/lib/scons*.
prefs.append(sys.prefix)
else:
# sys.prefix is /foo (ends in neither /usr or /local);
# check only /foo/lib/scons*.
prefs.append(sys.prefix)
temp = map(lambda x: os.path.join(x, 'lib'), prefs)
temp.extend(map(lambda x: os.path.join(x,
'lib',
'python' + sys.version[:3],
'site-packages'),
prefs))
prefs = temp
# Add the parent directory of the current python's library to the
# preferences. On SuSE-91/AMD64, for example, this is /usr/lib64,
# not /usr/lib.
try:
libpath = os.__file__
except AttributeError:
pass
else:
# Split /usr/libfoo/python*/os.py to /usr/libfoo/python*.
libpath, tail = os.path.split(libpath)
# Split /usr/libfoo/python* to /usr/libfoo
libpath, tail = os.path.split(libpath)
# Check /usr/libfoo/scons*.
prefs.append(libpath)
try:
import pkg_resources
except ImportError:
pass
else:
# when running from an egg add the egg's directory
try:
d = pkg_resources.get_distribution('scons')
except pkg_resources.DistributionNotFound:
pass
else:
prefs.append(d.location)
# Look first for 'scons-__version__' in all of our preference libs,
# then for 'scons'.
libs.extend(map(lambda x: os.path.join(x, scons_version), prefs))
libs.extend(map(lambda x: os.path.join(x, 'scons'), prefs))
sys.path = libs + sys.path
##############################################################################
# END STANDARD SCons SCRIPT HEADER
##############################################################################
if __name__ == "__main__":
import SCons.Script
# this does all the work, and calls sys.exit
# with the proper exit status when done.
SCons.Script.main()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Util
Various utility functions go here.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Util.py 4720 2010/03/24 03:14:11 jars"
import copy
import os
import os.path
import re
import string
import sys
import types
from UserDict import UserDict
from UserList import UserList
from UserString import UserString
# Don't "from types import ..." these because we need to get at the
# types module later to look for UnicodeType.
DictType = types.DictType
InstanceType = types.InstanceType
ListType = types.ListType
StringType = types.StringType
TupleType = types.TupleType
def dictify(keys, values, result={}):
for k, v in zip(keys, values):
result[k] = v
return result
_altsep = os.altsep
if _altsep is None and sys.platform == 'win32':
# My ActivePython 2.0.1 doesn't set os.altsep! What gives?
_altsep = '/'
if _altsep:
def rightmost_separator(path, sep, _altsep=_altsep):
rfind = string.rfind
return max(rfind(path, sep), rfind(path, _altsep))
else:
rightmost_separator = string.rfind
# First two from the Python Cookbook, just for completeness.
# (Yeah, yeah, YAGNI...)
def containsAny(str, set):
"""Check whether sequence str contains ANY of the items in set."""
for c in set:
if c in str: return 1
return 0
def containsAll(str, set):
"""Check whether sequence str contains ALL of the items in set."""
for c in set:
if c not in str: return 0
return 1
def containsOnly(str, set):
"""Check whether sequence str contains ONLY items in set."""
for c in str:
if c not in set: return 0
return 1
def splitext(path):
"Same as os.path.splitext() but faster."
sep = rightmost_separator(path, os.sep)
dot = string.rfind(path, '.')
# An ext is only real if it has at least one non-digit char
if dot > sep and not containsOnly(path[dot:], "0123456789."):
return path[:dot],path[dot:]
else:
return path,""
def updrive(path):
"""
Make the drive letter (if any) upper case.
This is useful because Windows is inconsitent on the case
of the drive letter, which can cause inconsistencies when
calculating command signatures.
"""
drive, rest = os.path.splitdrive(path)
if drive:
path = string.upper(drive) + rest
return path
class NodeList(UserList):
"""This class is almost exactly like a regular list of Nodes
(actually it can hold any object), with one important difference.
If you try to get an attribute from this list, it will return that
attribute from every item in the list. For example:
>>> someList = NodeList([ ' foo ', ' bar ' ])
>>> someList.strip()
[ 'foo', 'bar' ]
"""
def __nonzero__(self):
return len(self.data) != 0
def __str__(self):
return string.join(map(str, self.data))
def __iter__(self):
return iter(self.data)
def __call__(self, *args, **kwargs):
result = map(lambda x, args=args, kwargs=kwargs: apply(x,
args,
kwargs),
self.data)
return self.__class__(result)
def __getattr__(self, name):
result = map(lambda x, n=name: getattr(x, n), self.data)
return self.__class__(result)
_get_env_var = re.compile(r'^\$([_a-zA-Z]\w*|{[_a-zA-Z]\w*})$')
def get_environment_var(varstr):
"""Given a string, first determine if it looks like a reference
to a single environment variable, like "$FOO" or "${FOO}".
If so, return that variable with no decorations ("FOO").
If not, return None."""
mo=_get_env_var.match(to_String(varstr))
if mo:
var = mo.group(1)
if var[0] == '{':
return var[1:-1]
else:
return var
else:
return None
class DisplayEngine:
def __init__(self):
self.__call__ = self.print_it
def print_it(self, text, append_newline=1):
if append_newline: text = text + '\n'
try:
sys.stdout.write(text)
except IOError:
# Stdout might be connected to a pipe that has been closed
# by now. The most likely reason for the pipe being closed
# is that the user has press ctrl-c. It this is the case,
# then SCons is currently shutdown. We therefore ignore
# IOError's here so that SCons can continue and shutdown
# properly so that the .sconsign is correctly written
# before SCons exits.
pass
def dont_print(self, text, append_newline=1):
pass
def set_mode(self, mode):
if mode:
self.__call__ = self.print_it
else:
self.__call__ = self.dont_print
def render_tree(root, child_func, prune=0, margin=[0], visited={}):
"""
Render a tree of nodes into an ASCII tree view.
root - the root node of the tree
child_func - the function called to get the children of a node
prune - don't visit the same node twice
margin - the format of the left margin to use for children of root.
1 results in a pipe, and 0 results in no pipe.
visited - a dictionary of visited nodes in the current branch if not prune,
or in the whole tree if prune.
"""
rname = str(root)
children = child_func(root)
retval = ""
for pipe in margin[:-1]:
if pipe:
retval = retval + "| "
else:
retval = retval + " "
if visited.has_key(rname):
return retval + "+-[" + rname + "]\n"
retval = retval + "+-" + rname + "\n"
if not prune:
visited = copy.copy(visited)
visited[rname] = 1
for i in range(len(children)):
margin.append(i<len(children)-1)
retval = retval + render_tree(children[i], child_func, prune, margin, visited
)
margin.pop()
return retval
IDX = lambda N: N and 1 or 0
def print_tree(root, child_func, prune=0, showtags=0, margin=[0], visited={}):
"""
Print a tree of nodes. This is like render_tree, except it prints
lines directly instead of creating a string representation in memory,
so that huge trees can be printed.
root - the root node of the tree
child_func - the function called to get the children of a node
prune - don't visit the same node twice
showtags - print status information to the left of each node line
margin - the format of the left margin to use for children of root.
1 results in a pipe, and 0 results in no pipe.
visited - a dictionary of visited nodes in the current branch if not prune,
or in the whole tree if prune.
"""
rname = str(root)
if showtags:
if showtags == 2:
print ' E = exists'
print ' R = exists in repository only'
print ' b = implicit builder'
print ' B = explicit builder'
print ' S = side effect'
print ' P = precious'
print ' A = always build'
print ' C = current'
print ' N = no clean'
print ' H = no cache'
print ''
tags = ['[']
tags.append(' E'[IDX(root.exists())])
tags.append(' R'[IDX(root.rexists() and not root.exists())])
tags.append(' BbB'[[0,1][IDX(root.has_explicit_builder())] +
[0,2][IDX(root.has_builder())]])
tags.append(' S'[IDX(root.side_effect)])
tags.append(' P'[IDX(root.precious)])
tags.append(' A'[IDX(root.always_build)])
tags.append(' C'[IDX(root.is_up_to_date())])
tags.append(' N'[IDX(root.noclean)])
tags.append(' H'[IDX(root.nocache)])
tags.append(']')
else:
tags = []
def MMM(m):
return [" ","| "][m]
margins = map(MMM, margin[:-1])
children = child_func(root)
if prune and visited.has_key(rname) and children:
print string.join(tags + margins + ['+-[', rname, ']'], '')
return
print string.join(tags + margins + ['+-', rname], '')
visited[rname] = 1
if children:
margin.append(1)
idx = IDX(showtags)
for C in children[:-1]:
print_tree(C, child_func, prune, idx, margin, visited)
margin[-1] = 0
print_tree(children[-1], child_func, prune, idx, margin, visited)
margin.pop()
# Functions for deciding if things are like various types, mainly to
# handle UserDict, UserList and UserString like their underlying types.
#
# Yes, all of this manual testing breaks polymorphism, and the real
# Pythonic way to do all of this would be to just try it and handle the
# exception, but handling the exception when it's not the right type is
# often too slow.
try:
class mystr(str):
pass
except TypeError:
# An older Python version without new-style classes.
#
# The actual implementations here have been selected after timings
# coded up in in bench/is_types.py (from the SCons source tree,
# see the scons-src distribution), mostly against Python 1.5.2.
# Key results from those timings:
#
# -- Storing the type of the object in a variable (t = type(obj))
# slows down the case where it's a native type and the first
# comparison will match, but nicely speeds up the case where
# it's a different native type. Since that's going to be
# common, it's a good tradeoff.
#
# -- The data show that calling isinstance() on an object that's
# a native type (dict, list or string) is expensive enough
# that checking up front for whether the object is of type
# InstanceType is a pretty big win, even though it does slow
# down the case where it really *is* an object instance a
# little bit.
def is_Dict(obj):
t = type(obj)
return t is DictType or \
(t is InstanceType and isinstance(obj, UserDict))
def is_List(obj):
t = type(obj)
return t is ListType \
or (t is InstanceType and isinstance(obj, UserList))
def is_Sequence(obj):
t = type(obj)
return t is ListType \
or t is TupleType \
or (t is InstanceType and isinstance(obj, UserList))
def is_Tuple(obj):
t = type(obj)
return t is TupleType
if hasattr(types, 'UnicodeType'):
def is_String(obj):
t = type(obj)
return t is StringType \
or t is UnicodeType \
or (t is InstanceType and isinstance(obj, UserString))
else:
def is_String(obj):
t = type(obj)
return t is StringType \
or (t is InstanceType and isinstance(obj, UserString))
def is_Scalar(obj):
return is_String(obj) or not is_Sequence(obj)
def flatten(obj, result=None):
"""Flatten a sequence to a non-nested list.
Flatten() converts either a single scalar or a nested sequence
to a non-nested list. Note that flatten() considers strings
to be scalars instead of sequences like Python would.
"""
if is_Scalar(obj):
return [obj]
if result is None:
result = []
for item in obj:
if is_Scalar(item):
result.append(item)
else:
flatten_sequence(item, result)
return result
def flatten_sequence(sequence, result=None):
"""Flatten a sequence to a non-nested list.
Same as flatten(), but it does not handle the single scalar
case. This is slightly more efficient when one knows that
the sequence to flatten can not be a scalar.
"""
if result is None:
result = []
for item in sequence:
if is_Scalar(item):
result.append(item)
else:
flatten_sequence(item, result)
return result
#
# Generic convert-to-string functions that abstract away whether or
# not the Python we're executing has Unicode support. The wrapper
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
if hasattr(types, 'UnicodeType'):
UnicodeType = types.UnicodeType
def to_String(s):
if isinstance(s, UserString):
t = type(s.data)
else:
t = type(s)
if t is UnicodeType:
return unicode(s)
else:
return str(s)
else:
to_String = str
def to_String_for_signature(obj):
try:
f = obj.for_signature
except AttributeError:
return to_String_for_subst(obj)
else:
return f()
def to_String_for_subst(s):
if is_Sequence( s ):
return string.join( map(to_String_for_subst, s) )
return to_String( s )
else:
# A modern Python version with new-style classes, so we can just use
# isinstance().
#
# We are using the following trick to speed-up these
# functions. Default arguments are used to take a snapshot of the
# the global functions and constants used by these functions. This
# transforms accesses to global variable into local variables
# accesses (i.e. LOAD_FAST instead of LOAD_GLOBAL).
DictTypes = (dict, UserDict)
ListTypes = (list, UserList)
SequenceTypes = (list, tuple, UserList)
# Empirically, Python versions with new-style classes all have
# unicode.
#
# Note that profiling data shows a speed-up when comparing
# explicitely with str and unicode instead of simply comparing
# with basestring. (at least on Python 2.5.1)
StringTypes = (str, unicode, UserString)
# Empirically, it is faster to check explicitely for str and
# unicode than for basestring.
BaseStringTypes = (str, unicode)
def is_Dict(obj, isinstance=isinstance, DictTypes=DictTypes):
return isinstance(obj, DictTypes)
def is_List(obj, isinstance=isinstance, ListTypes=ListTypes):
return isinstance(obj, ListTypes)
def is_Sequence(obj, isinstance=isinstance, SequenceTypes=SequenceTypes):
return isinstance(obj, SequenceTypes)
def is_Tuple(obj, isinstance=isinstance, tuple=tuple):
return isinstance(obj, tuple)
def is_String(obj, isinstance=isinstance, StringTypes=StringTypes):
return isinstance(obj, StringTypes)
def is_Scalar(obj, isinstance=isinstance, StringTypes=StringTypes, SequenceTypes=SequenceTypes):
# Profiling shows that there is an impressive speed-up of 2x
# when explicitely checking for strings instead of just not
# sequence when the argument (i.e. obj) is already a string.
# But, if obj is a not string than it is twice as fast to
# check only for 'not sequence'. The following code therefore
# assumes that the obj argument is a string must of the time.
return isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes)
def do_flatten(sequence, result, isinstance=isinstance,
StringTypes=StringTypes, SequenceTypes=SequenceTypes):
for item in sequence:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
result.append(item)
else:
do_flatten(item, result)
def flatten(obj, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
"""Flatten a sequence to a non-nested list.
Flatten() converts either a single scalar or a nested sequence
to a non-nested list. Note that flatten() considers strings
to be scalars instead of sequences like Python would.
"""
if isinstance(obj, StringTypes) or not isinstance(obj, SequenceTypes):
return [obj]
result = []
for item in obj:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
result.append(item)
else:
do_flatten(item, result)
return result
def flatten_sequence(sequence, isinstance=isinstance, StringTypes=StringTypes,
SequenceTypes=SequenceTypes, do_flatten=do_flatten):
"""Flatten a sequence to a non-nested list.
Same as flatten(), but it does not handle the single scalar
case. This is slightly more efficient when one knows that
the sequence to flatten can not be a scalar.
"""
result = []
for item in sequence:
if isinstance(item, StringTypes) or not isinstance(item, SequenceTypes):
result.append(item)
else:
do_flatten(item, result)
return result
#
# Generic convert-to-string functions that abstract away whether or
# not the Python we're executing has Unicode support. The wrapper
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
def to_String(s,
isinstance=isinstance, str=str,
UserString=UserString, BaseStringTypes=BaseStringTypes):
if isinstance(s,BaseStringTypes):
# Early out when already a string!
return s
elif isinstance(s, UserString):
# s.data can only be either a unicode or a regular
# string. Please see the UserString initializer.
return s.data
else:
return str(s)
def to_String_for_subst(s,
isinstance=isinstance, join=string.join, str=str, to_String=to_String,
BaseStringTypes=BaseStringTypes, SequenceTypes=SequenceTypes,
UserString=UserString):
# Note that the test cases are sorted by order of probability.
if isinstance(s, BaseStringTypes):
return s
elif isinstance(s, SequenceTypes):
l = []
for e in s:
l.append(to_String_for_subst(e))
return join( s )
elif isinstance(s, UserString):
# s.data can only be either a unicode or a regular
# string. Please see the UserString initializer.
return s.data
else:
return str(s)
def to_String_for_signature(obj, to_String_for_subst=to_String_for_subst,
AttributeError=AttributeError):
try:
f = obj.for_signature
except AttributeError:
return to_String_for_subst(obj)
else:
return f()
# The SCons "semi-deep" copy.
#
# This makes separate copies of lists (including UserList objects)
# dictionaries (including UserDict objects) and tuples, but just copies
# references to anything else it finds.
#
# A special case is any object that has a __semi_deepcopy__() method,
# which we invoke to create the copy, which is used by the BuilderDict
# class because of its extra initialization argument.
#
# The dispatch table approach used here is a direct rip-off from the
# normal Python copy module.
_semi_deepcopy_dispatch = d = {}
def _semi_deepcopy_dict(x):
copy = {}
for key, val in x.items():
# The regular Python copy.deepcopy() also deepcopies the key,
# as follows:
#
# copy[semi_deepcopy(key)] = semi_deepcopy(val)
#
# Doesn't seem like we need to, but we'll comment it just in case.
copy[key] = semi_deepcopy(val)
return copy
d[types.DictionaryType] = _semi_deepcopy_dict
def _semi_deepcopy_list(x):
return map(semi_deepcopy, x)
d[types.ListType] = _semi_deepcopy_list
def _semi_deepcopy_tuple(x):
return tuple(map(semi_deepcopy, x))
d[types.TupleType] = _semi_deepcopy_tuple
def _semi_deepcopy_inst(x):
if hasattr(x, '__semi_deepcopy__'):
return x.__semi_deepcopy__()
elif isinstance(x, UserDict):
return x.__class__(_semi_deepcopy_dict(x))
elif isinstance(x, UserList):
return x.__class__(_semi_deepcopy_list(x))
else:
return x
d[types.InstanceType] = _semi_deepcopy_inst
def semi_deepcopy(x):
copier = _semi_deepcopy_dispatch.get(type(x))
if copier:
return copier(x)
else:
return x
class Proxy:
"""A simple generic Proxy class, forwarding all calls to
subject. So, for the benefit of the python newbie, what does
this really mean? Well, it means that you can take an object, let's
call it 'objA', and wrap it in this Proxy class, with a statement
like this
proxyObj = Proxy(objA),
Then, if in the future, you do something like this
x = proxyObj.var1,
since Proxy does not have a 'var1' attribute (but presumably objA does),
the request actually is equivalent to saying
x = objA.var1
Inherit from this class to create a Proxy."""
def __init__(self, subject):
"""Wrap an object as a Proxy object"""
self.__subject = subject
def __getattr__(self, name):
"""Retrieve an attribute from the wrapped object. If the named
attribute doesn't exist, AttributeError is raised"""
return getattr(self.__subject, name)
def get(self):
"""Retrieve the entire wrapped object"""
return self.__subject
def __cmp__(self, other):
if issubclass(other.__class__, self.__subject.__class__):
return cmp(self.__subject, other)
return cmp(self.__dict__, other.__dict__)
# attempt to load the windows registry module:
can_read_reg = 0
try:
import _winreg
can_read_reg = 1
hkey_mod = _winreg
RegOpenKeyEx = _winreg.OpenKeyEx
RegEnumKey = _winreg.EnumKey
RegEnumValue = _winreg.EnumValue
RegQueryValueEx = _winreg.QueryValueEx
RegError = _winreg.error
except ImportError:
try:
import win32api
import win32con
can_read_reg = 1
hkey_mod = win32con
RegOpenKeyEx = win32api.RegOpenKeyEx
RegEnumKey = win32api.RegEnumKey
RegEnumValue = win32api.RegEnumValue
RegQueryValueEx = win32api.RegQueryValueEx
RegError = win32api.error
except ImportError:
class _NoError(Exception):
pass
RegError = _NoError
if can_read_reg:
HKEY_CLASSES_ROOT = hkey_mod.HKEY_CLASSES_ROOT
HKEY_LOCAL_MACHINE = hkey_mod.HKEY_LOCAL_MACHINE
HKEY_CURRENT_USER = hkey_mod.HKEY_CURRENT_USER
HKEY_USERS = hkey_mod.HKEY_USERS
def RegGetValue(root, key):
"""This utility function returns a value in the registry
without having to open the key first. Only available on
Windows platforms with a version of Python that can read the
registry. Returns the same thing as
SCons.Util.RegQueryValueEx, except you just specify the entire
path to the value, and don't have to bother opening the key
first. So:
Instead of:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion')
out = SCons.Util.RegQueryValueEx(k,
'ProgramFilesDir')
You can write:
out = SCons.Util.RegGetValue(SCons.Util.HKEY_LOCAL_MACHINE,
r'SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir')
"""
# I would use os.path.split here, but it's not a filesystem
# path...
p = key.rfind('\\') + 1
keyp = key[:p-1] # -1 to omit trailing slash
val = key[p:]
k = RegOpenKeyEx(root, keyp)
return RegQueryValueEx(k,val)
else:
try:
e = WindowsError
except NameError:
# Make sure we have a definition of WindowsError so we can
# run platform-independent tests of Windows functionality on
# platforms other than Windows. (WindowsError is, in fact, an
# OSError subclass on Windows.)
class WindowsError(OSError):
pass
import __builtin__
__builtin__.WindowsError = WindowsError
else:
del e
HKEY_CLASSES_ROOT = None
HKEY_LOCAL_MACHINE = None
HKEY_CURRENT_USER = None
HKEY_USERS = None
def RegGetValue(root, key):
raise WindowsError
def RegOpenKeyEx(root, key):
raise WindowsError
if sys.platform == 'win32':
def WhereIs(file, path=None, pathext=None, reject=[]):
if path is None:
try:
path = os.environ['PATH']
except KeyError:
return None
if is_String(path):
path = string.split(path, os.pathsep)
if pathext is None:
try:
pathext = os.environ['PATHEXT']
except KeyError:
pathext = '.COM;.EXE;.BAT;.CMD'
if is_String(pathext):
pathext = string.split(pathext, os.pathsep)
for ext in pathext:
if string.lower(ext) == string.lower(file[-len(ext):]):
pathext = ['']
break
if not is_List(reject) and not is_Tuple(reject):
reject = [reject]
for dir in path:
f = os.path.join(dir, file)
for ext in pathext:
fext = f + ext
if os.path.isfile(fext):
try:
reject.index(fext)
except ValueError:
return os.path.normpath(fext)
continue
return None
elif os.name == 'os2':
def WhereIs(file, path=None, pathext=None, reject=[]):
if path is None:
try:
path = os.environ['PATH']
except KeyError:
return None
if is_String(path):
path = string.split(path, os.pathsep)
if pathext is None:
pathext = ['.exe', '.cmd']
for ext in pathext:
if string.lower(ext) == string.lower(file[-len(ext):]):
pathext = ['']
break
if not is_List(reject) and not is_Tuple(reject):
reject = [reject]
for dir in path:
f = os.path.join(dir, file)
for ext in pathext:
fext = f + ext
if os.path.isfile(fext):
try:
reject.index(fext)
except ValueError:
return os.path.normpath(fext)
continue
return None
else:
def WhereIs(file, path=None, pathext=None, reject=[]):
import stat
if path is None:
try:
path = os.environ['PATH']
except KeyError:
return None
if is_String(path):
path = string.split(path, os.pathsep)
if not is_List(reject) and not is_Tuple(reject):
reject = [reject]
for d in path:
f = os.path.join(d, file)
if os.path.isfile(f):
try:
st = os.stat(f)
except OSError:
# os.stat() raises OSError, not IOError if the file
# doesn't exist, so in this case we let IOError get
# raised so as to not mask possibly serious disk or
# network issues.
continue
if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
try:
reject.index(f)
except ValueError:
return os.path.normpath(f)
continue
return None
def PrependPath(oldpath, newpath, sep = os.pathsep,
delete_existing=1, canonicalize=None):
"""This prepends newpath elements to the given oldpath. Will only
add any particular path once (leaving the first one it encounters
and ignoring the rest, to preserve path order), and will
os.path.normpath and os.path.normcase all paths to help assure
this. This can also handle the case where the given old path
variable is a list instead of a string, in which case a list will
be returned instead of a string.
Example:
Old Path: "/foo/bar:/foo"
New Path: "/biz/boom:/foo"
Result: "/biz/boom:/foo:/foo/bar"
If delete_existing is 0, then adding a path that exists will
not move it to the beginning; it will stay where it is in the
list.
If canonicalize is not None, it is applied to each element of
newpath before use.
"""
orig = oldpath
is_list = 1
paths = orig
if not is_List(orig) and not is_Tuple(orig):
paths = string.split(paths, sep)
is_list = 0
if is_String(newpath):
newpaths = string.split(newpath, sep)
elif not is_List(newpath) and not is_Tuple(newpath):
newpaths = [ newpath ] # might be a Dir
else:
newpaths = newpath
if canonicalize:
newpaths=map(canonicalize, newpaths)
if not delete_existing:
# First uniquify the old paths, making sure to
# preserve the first instance (in Unix/Linux,
# the first one wins), and remembering them in normpaths.
# Then insert the new paths at the head of the list
# if they're not already in the normpaths list.
result = []
normpaths = []
for path in paths:
if not path:
continue
normpath = os.path.normpath(os.path.normcase(path))
if normpath not in normpaths:
result.append(path)
normpaths.append(normpath)
newpaths.reverse() # since we're inserting at the head
for path in newpaths:
if not path:
continue
normpath = os.path.normpath(os.path.normcase(path))
if normpath not in normpaths:
result.insert(0, path)
normpaths.append(normpath)
paths = result
else:
newpaths = newpaths + paths # prepend new paths
normpaths = []
paths = []
# now we add them only if they are unique
for path in newpaths:
normpath = os.path.normpath(os.path.normcase(path))
if path and not normpath in normpaths:
paths.append(path)
normpaths.append(normpath)
if is_list:
return paths
else:
return string.join(paths, sep)
def AppendPath(oldpath, newpath, sep = os.pathsep,
delete_existing=1, canonicalize=None):
"""This appends new path elements to the given old path. Will
only add any particular path once (leaving the last one it
encounters and ignoring the rest, to preserve path order), and
will os.path.normpath and os.path.normcase all paths to help
assure this. This can also handle the case where the given old
path variable is a list instead of a string, in which case a list
will be returned instead of a string.
Example:
Old Path: "/foo/bar:/foo"
New Path: "/biz/boom:/foo"
Result: "/foo/bar:/biz/boom:/foo"
If delete_existing is 0, then adding a path that exists
will not move it to the end; it will stay where it is in the list.
If canonicalize is not None, it is applied to each element of
newpath before use.
"""
orig = oldpath
is_list = 1
paths = orig
if not is_List(orig) and not is_Tuple(orig):
paths = string.split(paths, sep)
is_list = 0
if is_String(newpath):
newpaths = string.split(newpath, sep)
elif not is_List(newpath) and not is_Tuple(newpath):
newpaths = [ newpath ] # might be a Dir
else:
newpaths = newpath
if canonicalize:
newpaths=map(canonicalize, newpaths)
if not delete_existing:
# add old paths to result, then
# add new paths if not already present
# (I thought about using a dict for normpaths for speed,
# but it's not clear hashing the strings would be faster
# than linear searching these typically short lists.)
result = []
normpaths = []
for path in paths:
if not path:
continue
result.append(path)
normpaths.append(os.path.normpath(os.path.normcase(path)))
for path in newpaths:
if not path:
continue
normpath = os.path.normpath(os.path.normcase(path))
if normpath not in normpaths:
result.append(path)
normpaths.append(normpath)
paths = result
else:
# start w/ new paths, add old ones if not present,
# then reverse.
newpaths = paths + newpaths # append new paths
newpaths.reverse()
normpaths = []
paths = []
# now we add them only if they are unique
for path in newpaths:
normpath = os.path.normpath(os.path.normcase(path))
if path and not normpath in normpaths:
paths.append(path)
normpaths.append(normpath)
paths.reverse()
if is_list:
return paths
else:
return string.join(paths, sep)
if sys.platform == 'cygwin':
def get_native_path(path):
"""Transforms an absolute path into a native path for the system. In
Cygwin, this converts from a Cygwin path to a Windows one."""
return string.replace(os.popen('cygpath -w ' + path).read(), '\n', '')
else:
def get_native_path(path):
"""Transforms an absolute path into a native path for the system.
Non-Cygwin version, just leave the path alone."""
return path
display = DisplayEngine()
def Split(arg):
if is_List(arg) or is_Tuple(arg):
return arg
elif is_String(arg):
return string.split(arg)
else:
return [arg]
class CLVar(UserList):
"""A class for command-line construction variables.
This is a list that uses Split() to split an initial string along
white-space arguments, and similarly to split any strings that get
added. This allows us to Do the Right Thing with Append() and
Prepend() (as well as straight Python foo = env['VAR'] + 'arg1
arg2') regardless of whether a user adds a list or a string to a
command-line construction variable.
"""
def __init__(self, seq = []):
UserList.__init__(self, Split(seq))
def __add__(self, other):
return UserList.__add__(self, CLVar(other))
def __radd__(self, other):
return UserList.__radd__(self, CLVar(other))
def __coerce__(self, other):
return (self, CLVar(other))
def __str__(self):
return string.join(self.data)
# A dictionary that preserves the order in which items are added.
# Submitted by David Benjamin to ActiveState's Python Cookbook web site:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
# Including fixes/enhancements from the follow-on discussions.
class OrderedDict(UserDict):
def __init__(self, dict = None):
self._keys = []
UserDict.__init__(self, dict)
def __delitem__(self, key):
UserDict.__delitem__(self, key)
self._keys.remove(key)
def __setitem__(self, key, item):
UserDict.__setitem__(self, key, item)
if key not in self._keys: self._keys.append(key)
def clear(self):
UserDict.clear(self)
self._keys = []
def copy(self):
dict = OrderedDict()
dict.update(self)
return dict
def items(self):
return zip(self._keys, self.values())
def keys(self):
return self._keys[:]
def popitem(self):
try:
key = self._keys[-1]
except IndexError:
raise KeyError('dictionary is empty')
val = self[key]
del self[key]
return (key, val)
def setdefault(self, key, failobj = None):
UserDict.setdefault(self, key, failobj)
if key not in self._keys: self._keys.append(key)
def update(self, dict):
for (key, val) in dict.items():
self.__setitem__(key, val)
def values(self):
return map(self.get, self._keys)
class Selector(OrderedDict):
"""A callable ordered dictionary that maps file suffixes to
dictionary values. We preserve the order in which items are added
so that get_suffix() calls always return the first suffix added."""
def __call__(self, env, source, ext=None):
if ext is None:
try:
ext = source[0].suffix
except IndexError:
ext = ""
try:
return self[ext]
except KeyError:
# Try to perform Environment substitution on the keys of
# the dictionary before giving up.
s_dict = {}
for (k,v) in self.items():
if k is not None:
s_k = env.subst(k)
if s_dict.has_key(s_k):
# We only raise an error when variables point
# to the same suffix. If one suffix is literal
# and a variable suffix contains this literal,
# the literal wins and we don't raise an error.
raise KeyError, (s_dict[s_k][0], k, s_k)
s_dict[s_k] = (k,v)
try:
return s_dict[ext][1]
except KeyError:
try:
return self[None]
except KeyError:
return None
if sys.platform == 'cygwin':
# On Cygwin, os.path.normcase() lies, so just report back the
# fact that the underlying Windows OS is case-insensitive.
def case_sensitive_suffixes(s1, s2):
return 0
else:
def case_sensitive_suffixes(s1, s2):
return (os.path.normcase(s1) != os.path.normcase(s2))
def adjustixes(fname, pre, suf, ensure_suffix=False):
if pre:
path, fn = os.path.split(os.path.normpath(fname))
if fn[:len(pre)] != pre:
fname = os.path.join(path, pre + fn)
# Only append a suffix if the suffix we're going to add isn't already
# there, and if either we've been asked to ensure the specific suffix
# is present or there's no suffix on it at all.
if suf and fname[-len(suf):] != suf and \
(ensure_suffix or not splitext(fname)[1]):
fname = fname + suf
return fname
# From Tim Peters,
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
# ASPN: Python Cookbook: Remove duplicates from a sequence
# (Also in the printed Python Cookbook.)
def unique(s):
"""Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed, all sequence elements should be hashable. Then
unique() will usually work in linear time.
If not possible, the sequence elements should enjoy a total
ordering, and if list(s).sort() doesn't raise TypeError it's
assumed that they do enjoy a total ordering. Then unique() will
usually work in O(N*log2(N)) time.
If that's not possible either, the sequence elements must support
equality-testing. Then unique() will usually work in quadratic
time.
"""
n = len(s)
if n == 0:
return []
# Try using a dict first, as that's the fastest and will usually
# work. If it doesn't work, it will usually fail quickly, so it
# usually doesn't cost much to *try* it. It requires that all the
# sequence elements be hashable, and support equality comparison.
u = {}
try:
for x in s:
u[x] = 1
except TypeError:
pass # move on to the next method
else:
return u.keys()
del u
# We can't hash all the elements. Second fastest is to sort,
# which brings the equal elements together; then duplicates are
# easy to weed out in a single pass.
# NOTE: Python's list.sort() was designed to be efficient in the
# presence of many duplicate elements. This isn't true of all
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
t = list(s)
t.sort()
except TypeError:
pass # move on to the next method
else:
assert n > 0
last = t[0]
lasti = i = 1
while i < n:
if t[i] != last:
t[lasti] = last = t[i]
lasti = lasti + 1
i = i + 1
return t[:lasti]
del t
# Brute force is all that's left.
u = []
for x in s:
if x not in u:
u.append(x)
return u
# From Alex Martelli,
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
# ASPN: Python Cookbook: Remove duplicates from a sequence
# First comment, dated 2001/10/13.
# (Also in the printed Python Cookbook.)
def uniquer(seq, idfun=None):
if idfun is None:
def idfun(x): return x
seen = {}
result = []
for item in seq:
marker = idfun(item)
# in old Python versions:
# if seen.has_key(marker)
# but in new ones:
if marker in seen: continue
seen[marker] = 1
result.append(item)
return result
# A more efficient implementation of Alex's uniquer(), this avoids the
# idfun() argument and function-call overhead by assuming that all
# items in the sequence are hashable.
def uniquer_hashables(seq):
seen = {}
result = []
for item in seq:
#if not item in seen:
if not seen.has_key(item):
seen[item] = 1
result.append(item)
return result
# Much of the logic here was originally based on recipe 4.9 from the
# Python CookBook, but we had to dumb it way down for Python 1.5.2.
class LogicalLines:
def __init__(self, fileobj):
self.fileobj = fileobj
def readline(self):
result = []
while 1:
line = self.fileobj.readline()
if not line:
break
if line[-2:] == '\\\n':
result.append(line[:-2])
else:
result.append(line)
break
return string.join(result, '')
def readlines(self):
result = []
while 1:
line = self.readline()
if not line:
break
result.append(line)
return result
class UniqueList(UserList):
def __init__(self, seq = []):
UserList.__init__(self, seq)
self.unique = True
def __make_unique(self):
if not self.unique:
self.data = uniquer_hashables(self.data)
self.unique = True
def __lt__(self, other):
self.__make_unique()
return UserList.__lt__(self, other)
def __le__(self, other):
self.__make_unique()
return UserList.__le__(self, other)
def __eq__(self, other):
self.__make_unique()
return UserList.__eq__(self, other)
def __ne__(self, other):
self.__make_unique()
return UserList.__ne__(self, other)
def __gt__(self, other):
self.__make_unique()
return UserList.__gt__(self, other)
def __ge__(self, other):
self.__make_unique()
return UserList.__ge__(self, other)
def __cmp__(self, other):
self.__make_unique()
return UserList.__cmp__(self, other)
def __len__(self):
self.__make_unique()
return UserList.__len__(self)
def __getitem__(self, i):
self.__make_unique()
return UserList.__getitem__(self, i)
def __setitem__(self, i, item):
UserList.__setitem__(self, i, item)
self.unique = False
def __getslice__(self, i, j):
self.__make_unique()
return UserList.__getslice__(self, i, j)
def __setslice__(self, i, j, other):
UserList.__setslice__(self, i, j, other)
self.unique = False
def __add__(self, other):
result = UserList.__add__(self, other)
result.unique = False
return result
def __radd__(self, other):
result = UserList.__radd__(self, other)
result.unique = False
return result
def __iadd__(self, other):
result = UserList.__iadd__(self, other)
result.unique = False
return result
def __mul__(self, other):
result = UserList.__mul__(self, other)
result.unique = False
return result
def __rmul__(self, other):
result = UserList.__rmul__(self, other)
result.unique = False
return result
def __imul__(self, other):
result = UserList.__imul__(self, other)
result.unique = False
return result
def append(self, item):
UserList.append(self, item)
self.unique = False
def insert(self, i):
UserList.insert(self, i)
self.unique = False
def count(self, item):
self.__make_unique()
return UserList.count(self, item)
def index(self, item):
self.__make_unique()
return UserList.index(self, item)
def reverse(self):
self.__make_unique()
UserList.reverse(self)
def sort(self, *args, **kwds):
self.__make_unique()
#return UserList.sort(self, *args, **kwds)
return apply(UserList.sort, (self,)+args, kwds)
def extend(self, other):
UserList.extend(self, other)
self.unique = False
class Unbuffered:
"""
A proxy class that wraps a file object, flushing after every write,
and delegating everything else to the wrapped object.
"""
def __init__(self, file):
self.file = file
def write(self, arg):
try:
self.file.write(arg)
self.file.flush()
except IOError:
# Stdout might be connected to a pipe that has been closed
# by now. The most likely reason for the pipe being closed
# is that the user has press ctrl-c. It this is the case,
# then SCons is currently shutdown. We therefore ignore
# IOError's here so that SCons can continue and shutdown
# properly so that the .sconsign is correctly written
# before SCons exits.
pass
def __getattr__(self, attr):
return getattr(self.file, attr)
def make_path_relative(path):
""" makes an absolute path name to a relative pathname.
"""
if os.path.isabs(path):
drive_s,path = os.path.splitdrive(path)
import re
if not drive_s:
path=re.compile("/*(.*)").findall(path)[0]
else:
path=path[1:]
assert( not os.path.isabs( path ) ), path
return path
# The original idea for AddMethod() and RenameFunction() come from the
# following post to the ActiveState Python Cookbook:
#
# ASPN: Python Cookbook : Install bound methods in an instance
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223613
#
# That code was a little fragile, though, so the following changes
# have been wrung on it:
#
# * Switched the installmethod() "object" and "function" arguments,
# so the order reflects that the left-hand side is the thing being
# "assigned to" and the right-hand side is the value being assigned.
#
# * Changed explicit type-checking to the "try: klass = object.__class__"
# block in installmethod() below so that it still works with the
# old-style classes that SCons uses.
#
# * Replaced the by-hand creation of methods and functions with use of
# the "new" module, as alluded to in Alex Martelli's response to the
# following Cookbook post:
#
# ASPN: Python Cookbook : Dynamically added methods to a class
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732
def AddMethod(object, function, name = None):
"""
Adds either a bound method to an instance or an unbound method to
a class. If name is ommited the name of the specified function
is used by default.
Example:
a = A()
def f(self, x, y):
self.z = x + y
AddMethod(f, A, "add")
a.add(2, 4)
print a.z
AddMethod(lambda self, i: self.l[i], a, "listIndex")
print a.listIndex(5)
"""
import new
if name is None:
name = function.func_name
else:
function = RenameFunction(function, name)
try:
klass = object.__class__
except AttributeError:
# "object" is really a class, so it gets an unbound method.
object.__dict__[name] = new.instancemethod(function, None, object)
else:
# "object" is really an instance, so it gets a bound method.
object.__dict__[name] = new.instancemethod(function, object, klass)
def RenameFunction(function, name):
"""
Returns a function identical to the specified function, but with
the specified name.
"""
import new
# Compatibility for Python 1.5 and 2.1. Can be removed in favor of
# passing function.func_defaults directly to new.function() once
# we base on Python 2.2 or later.
func_defaults = function.func_defaults
if func_defaults is None:
func_defaults = ()
return new.function(function.func_code,
function.func_globals,
name,
func_defaults)
md5 = False
def MD5signature(s):
return str(s)
def MD5filesignature(fname, chunksize=65536):
f = open(fname, "rb")
result = f.read()
f.close()
return result
try:
import hashlib
except ImportError:
pass
else:
if hasattr(hashlib, 'md5'):
md5 = True
def MD5signature(s):
m = hashlib.md5()
m.update(str(s))
return m.hexdigest()
def MD5filesignature(fname, chunksize=65536):
m = hashlib.md5()
f = open(fname, "rb")
while 1:
blck = f.read(chunksize)
if not blck:
break
m.update(str(blck))
f.close()
return m.hexdigest()
def MD5collect(signatures):
"""
Collects a list of signatures into an aggregate signature.
signatures - a list of signatures
returns - the aggregate signature
"""
if len(signatures) == 1:
return signatures[0]
else:
return MD5signature(string.join(signatures, ', '))
# Wrap the intern() function so it doesn't throw exceptions if ineligible
# arguments are passed. The intern() function was moved into the sys module in
# Python 3.
try:
intern
except NameError:
from sys import intern
def silent_intern(x):
"""
Perform intern() on the passed argument and return the result.
If the input is ineligible (e.g. a unicode string) the original argument is
returned and no exception is thrown.
"""
try:
return intern(x)
except TypeError:
return x
# From Dinu C. Gherman,
# Python Cookbook, second edition, recipe 6.17, p. 277.
# Also:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
# ASPN: Python Cookbook: Null Object Design Pattern
# TODO(1.5):
#class Null(object):
class Null:
""" Null objects always and reliably "do nothing." """
def __new__(cls, *args, **kwargs):
if not '_inst' in vars(cls):
#cls._inst = type.__new__(cls, *args, **kwargs)
cls._inst = apply(type.__new__, (cls,) + args, kwargs)
return cls._inst
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return self
def __repr__(self):
return "Null(0x%08X)" % id(self)
def __nonzero__(self):
return False
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
return self
def __delattr__(self, name):
return self
class NullSeq(Null):
def __len__(self):
return 0
def __iter__(self):
return iter(())
def __getitem__(self, i):
return self
def __delitem__(self, i):
return self
def __setitem__(self, i, v):
return self
del __revision__
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/PathList.py 4720 2010/03/24 03:14:11 jars"
__doc__ = """SCons.PathList
A module for handling lists of directory paths (the sort of things
that get set as CPPPATH, LIBPATH, etc.) with as much caching of data and
efficiency as we can while still keeping the evaluation delayed so that we
Do the Right Thing (almost) regardless of how the variable is specified.
"""
import os
import string
import SCons.Memoize
import SCons.Node
import SCons.Util
#
# Variables to specify the different types of entries in a PathList object:
#
TYPE_STRING_NO_SUBST = 0 # string with no '$'
TYPE_STRING_SUBST = 1 # string containing '$'
TYPE_OBJECT = 2 # other object
def node_conv(obj):
"""
This is the "string conversion" routine that we have our substitutions
use to return Nodes, not strings. This relies on the fact that an
EntryProxy object has a get() method that returns the underlying
Node that it wraps, which is a bit of architectural dependence
that we might need to break or modify in the future in response to
additional requirements.
"""
try:
get = obj.get
except AttributeError:
if isinstance(obj, SCons.Node.Node) or SCons.Util.is_Sequence( obj ):
result = obj
else:
result = str(obj)
else:
result = get()
return result
class _PathList:
"""
An actual PathList object.
"""
def __init__(self, pathlist):
"""
Initializes a PathList object, canonicalizing the input and
pre-processing it for quicker substitution later.
The stored representation of the PathList is a list of tuples
containing (type, value), where the "type" is one of the TYPE_*
variables defined above. We distinguish between:
strings that contain no '$' and therefore need no
delayed-evaluation string substitution (we expect that there
will be many of these and that we therefore get a pretty
big win from avoiding string substitution)
strings that contain '$' and therefore need substitution
(the hard case is things like '${TARGET.dir}/include',
which require re-evaluation for every target + source)
other objects (which may be something like an EntryProxy
that needs a method called to return a Node)
Pre-identifying the type of each element in the PathList up-front
and storing the type in the list of tuples is intended to reduce
the amount of calculation when we actually do the substitution
over and over for each target.
"""
if SCons.Util.is_String(pathlist):
pathlist = string.split(pathlist, os.pathsep)
elif not SCons.Util.is_Sequence(pathlist):
pathlist = [pathlist]
pl = []
for p in pathlist:
try:
index = string.find(p, '$')
except (AttributeError, TypeError):
type = TYPE_OBJECT
else:
if index == -1:
type = TYPE_STRING_NO_SUBST
else:
type = TYPE_STRING_SUBST
pl.append((type, p))
self.pathlist = tuple(pl)
def __len__(self): return len(self.pathlist)
def __getitem__(self, i): return self.pathlist[i]
def subst_path(self, env, target, source):
"""
Performs construction variable substitution on a pre-digested
PathList for a specific target and source.
"""
result = []
for type, value in self.pathlist:
if type == TYPE_STRING_SUBST:
value = env.subst(value, target=target, source=source,
conv=node_conv)
if SCons.Util.is_Sequence(value):
result.extend(value)
continue
elif type == TYPE_OBJECT:
value = node_conv(value)
if value:
result.append(value)
return tuple(result)
class PathListCache:
"""
A class to handle caching of PathList lookups.
This class gets instantiated once and then deleted from the namespace,
so it's used as a Singleton (although we don't enforce that in the
usual Pythonic ways). We could have just made the cache a dictionary
in the module namespace, but putting it in this class allows us to
use the same Memoizer pattern that we use elsewhere to count cache
hits and misses, which is very valuable.
Lookup keys in the cache are computed by the _PathList_key() method.
Cache lookup should be quick, so we don't spend cycles canonicalizing
all forms of the same lookup key. For example, 'x:y' and ['x',
'y'] logically represent the same list, but we don't bother to
split string representations and treat those two equivalently.
(Note, however, that we do, treat lists and tuples the same.)
The main type of duplication we're trying to catch will come from
looking up the same path list from two different clones of the
same construction environment. That is, given
env2 = env1.Clone()
both env1 and env2 will have the same CPPPATH value, and we can
cheaply avoid re-parsing both values of CPPPATH by using the
common value from this cache.
"""
if SCons.Memoize.use_memoizer:
__metaclass__ = SCons.Memoize.Memoized_Metaclass
memoizer_counters = []
def __init__(self):
self._memo = {}
def _PathList_key(self, pathlist):
"""
Returns the key for memoization of PathLists.
Note that we want this to be pretty quick, so we don't completely
canonicalize all forms of the same list. For example,
'dir1:$ROOT/dir2' and ['$ROOT/dir1', 'dir'] may logically
represent the same list if you're executing from $ROOT, but
we're not going to bother splitting strings into path elements,
or massaging strings into Nodes, to identify that equivalence.
We just want to eliminate obvious redundancy from the normal
case of re-using exactly the same cloned value for a path.
"""
if SCons.Util.is_Sequence(pathlist):
pathlist = tuple(SCons.Util.flatten(pathlist))
return pathlist
memoizer_counters.append(SCons.Memoize.CountDict('PathList', _PathList_key))
def PathList(self, pathlist):
"""
Returns the cached _PathList object for the specified pathlist,
creating and caching a new object as necessary.
"""
pathlist = self._PathList_key(pathlist)
try:
memo_dict = self._memo['PathList']
except KeyError:
memo_dict = {}
self._memo['PathList'] = memo_dict
else:
try:
return memo_dict[pathlist]
except KeyError:
pass
result = _PathList(pathlist)
memo_dict[pathlist] = result
return result
PathList = PathListCache().PathList
del PathListCache
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.SConf
Autoconf-like configuration support.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/SConf.py 4720 2010/03/24 03:14:11 jars"
import os
import re
import string
import StringIO
import sys
import traceback
import types
import SCons.Action
import SCons.Builder
import SCons.Errors
import SCons.Job
import SCons.Node.FS
import SCons.Taskmaster
import SCons.Util
import SCons.Warnings
import SCons.Conftest
from SCons.Debug import Trace
# Turn off the Conftest error logging
SCons.Conftest.LogInputFiles = 0
SCons.Conftest.LogErrorMessages = 0
# Set
build_type = None
build_types = ['clean', 'help']
def SetBuildType(type):
global build_type
build_type = type
# to be set, if we are in dry-run mode
dryrun = 0
AUTO=0 # use SCons dependency scanning for up-to-date checks
FORCE=1 # force all tests to be rebuilt
CACHE=2 # force all tests to be taken from cache (raise an error, if necessary)
cache_mode = AUTO
def SetCacheMode(mode):
"""Set the Configure cache mode. mode must be one of "auto", "force",
or "cache"."""
global cache_mode
if mode == "auto":
cache_mode = AUTO
elif mode == "force":
cache_mode = FORCE
elif mode == "cache":
cache_mode = CACHE
else:
raise ValueError, "SCons.SConf.SetCacheMode: Unknown mode " + mode
progress_display = SCons.Util.display # will be overwritten by SCons.Script
def SetProgressDisplay(display):
"""Set the progress display to use (called from SCons.Script)"""
global progress_display
progress_display = display
SConfFS = None
_ac_build_counter = 0 # incremented, whenever TryBuild is called
_ac_config_logs = {} # all config.log files created in this build
_ac_config_hs = {} # all config.h files created in this build
sconf_global = None # current sconf object
def _createConfigH(target, source, env):
t = open(str(target[0]), "w")
defname = re.sub('[^A-Za-z0-9_]', '_', string.upper(str(target[0])))
t.write("""#ifndef %(DEFNAME)s_SEEN
#define %(DEFNAME)s_SEEN
""" % {'DEFNAME' : defname})
t.write(source[0].get_contents())
t.write("""
#endif /* %(DEFNAME)s_SEEN */
""" % {'DEFNAME' : defname})
t.close()
def _stringConfigH(target, source, env):
return "scons: Configure: creating " + str(target[0])
def CreateConfigHBuilder(env):
"""Called just before the building targets phase begins."""
if len(_ac_config_hs) == 0:
return
action = SCons.Action.Action(_createConfigH,
_stringConfigH)
sconfigHBld = SCons.Builder.Builder(action=action)
env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} )
for k in _ac_config_hs.keys():
env.SConfigHBuilder(k, env.Value(_ac_config_hs[k]))
class SConfWarning(SCons.Warnings.Warning):
pass
SCons.Warnings.enableWarningClass(SConfWarning)
# some error definitions
class SConfError(SCons.Errors.UserError):
def __init__(self,msg):
SCons.Errors.UserError.__init__(self,msg)
class ConfigureDryRunError(SConfError):
"""Raised when a file or directory needs to be updated during a Configure
process, but the user requested a dry-run"""
def __init__(self,target):
if not isinstance(target, SCons.Node.FS.File):
msg = 'Cannot create configure directory "%s" within a dry-run.' % str(target)
else:
msg = 'Cannot update configure test "%s" within a dry-run.' % str(target)
SConfError.__init__(self,msg)
class ConfigureCacheError(SConfError):
"""Raised when a use explicitely requested the cache feature, but the test
is run the first time."""
def __init__(self,target):
SConfError.__init__(self, '"%s" is not yet built and cache is forced.' % str(target))
# define actions for building text files
def _createSource( target, source, env ):
fd = open(str(target[0]), "w")
fd.write(source[0].get_contents())
fd.close()
def _stringSource( target, source, env ):
return (str(target[0]) + ' <-\n |' +
string.replace( source[0].get_contents(),
'\n', "\n |" ) )
# python 2.2 introduces types.BooleanType
BooleanTypes = [types.IntType]
if hasattr(types, 'BooleanType'): BooleanTypes.append(types.BooleanType)
class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
"""
Special build info for targets of configure tests. Additional members
are result (did the builder succeed last time?) and string, which
contains messages of the original build phase.
"""
result = None # -> 0/None -> no error, != 0 error
string = None # the stdout / stderr output when building the target
def set_build_result(self, result, string):
self.result = result
self.string = string
class Streamer:
"""
'Sniffer' for a file-like writable object. Similar to the unix tool tee.
"""
def __init__(self, orig):
self.orig = orig
self.s = StringIO.StringIO()
def write(self, str):
if self.orig:
self.orig.write(str)
self.s.write(str)
def writelines(self, lines):
for l in lines:
self.write(l + '\n')
def getvalue(self):
"""
Return everything written to orig since the Streamer was created.
"""
return self.s.getvalue()
def flush(self):
if self.orig:
self.orig.flush()
self.s.flush()
class SConfBuildTask(SCons.Taskmaster.AlwaysTask):
"""
This is almost the same as SCons.Script.BuildTask. Handles SConfErrors
correctly and knows about the current cache_mode.
"""
def display(self, message):
if sconf_global.logstream:
sconf_global.logstream.write("scons: Configure: " + message + "\n")
def display_cached_string(self, bi):
"""
Logs the original builder messages, given the SConfBuildInfo instance
bi.
"""
if not isinstance(bi, SConfBuildInfo):
SCons.Warnings.warn(SConfWarning,
"The stored build information has an unexpected class: %s" % bi.__class__)
else:
self.display("The original builder output was:\n" +
string.replace(" |" + str(bi.string),
"\n", "\n |"))
def failed(self):
# check, if the reason was a ConfigureDryRunError or a
# ConfigureCacheError and if yes, reraise the exception
exc_type = self.exc_info()[0]
if issubclass(exc_type, SConfError):
raise
elif issubclass(exc_type, SCons.Errors.BuildError):
# we ignore Build Errors (occurs, when a test doesn't pass)
# Clear the exception to prevent the contained traceback
# to build a reference cycle.
self.exc_clear()
else:
self.display('Caught exception while building "%s":\n' %
self.targets[0])
try:
excepthook = sys.excepthook
except AttributeError:
# Earlier versions of Python don't have sys.excepthook...
def excepthook(type, value, tb):
traceback.print_tb(tb)
print type, value
apply(excepthook, self.exc_info())
return SCons.Taskmaster.Task.failed(self)
def collect_node_states(self):
# returns (is_up_to_date, cached_error, cachable)
# where is_up_to_date is 1, if the node(s) are up_to_date
# cached_error is 1, if the node(s) are up_to_date, but the
# build will fail
# cachable is 0, if some nodes are not in our cache
T = 0
changed = False
cached_error = False
cachable = True
for t in self.targets:
if T: Trace('%s' % (t))
bi = t.get_stored_info().binfo
if isinstance(bi, SConfBuildInfo):
if T: Trace(': SConfBuildInfo')
if cache_mode == CACHE:
t.set_state(SCons.Node.up_to_date)
if T: Trace(': set_state(up_to-date)')
else:
if T: Trace(': get_state() %s' % t.get_state())
if T: Trace(': changed() %s' % t.changed())
if (t.get_state() != SCons.Node.up_to_date and t.changed()):
changed = True
if T: Trace(': changed %s' % changed)
cached_error = cached_error or bi.result
else:
if T: Trace(': else')
# the node hasn't been built in a SConf context or doesn't
# exist
cachable = False
changed = ( t.get_state() != SCons.Node.up_to_date )
if T: Trace(': changed %s' % changed)
if T: Trace('\n')
return (not changed, cached_error, cachable)
def execute(self):
if not self.targets[0].has_builder():
return
sconf = sconf_global
is_up_to_date, cached_error, cachable = self.collect_node_states()
if cache_mode == CACHE and not cachable:
raise ConfigureCacheError(self.targets[0])
elif cache_mode == FORCE:
is_up_to_date = 0
if cached_error and is_up_to_date:
self.display("Building \"%s\" failed in a previous run and all "
"its sources are up to date." % str(self.targets[0]))
binfo = self.targets[0].get_stored_info().binfo
self.display_cached_string(binfo)
raise SCons.Errors.BuildError # will be 'caught' in self.failed
elif is_up_to_date:
self.display("\"%s\" is up to date." % str(self.targets[0]))
binfo = self.targets[0].get_stored_info().binfo
self.display_cached_string(binfo)
elif dryrun:
raise ConfigureDryRunError(self.targets[0])
else:
# note stdout and stderr are the same here
s = sys.stdout = sys.stderr = Streamer(sys.stdout)
try:
env = self.targets[0].get_build_env()
if cache_mode == FORCE:
# Set up the Decider() to force rebuilds by saying
# that every source has changed. Note that we still
# call the environment's underlying source decider so
# that the correct .sconsign info will get calculated
# and keep the build state consistent.
def force_build(dependency, target, prev_ni,
env_decider=env.decide_source):
env_decider(dependency, target, prev_ni)
return True
if env.decide_source.func_code is not force_build.func_code:
env.Decider(force_build)
env['PSTDOUT'] = env['PSTDERR'] = s
try:
sconf.cached = 0
self.targets[0].build()
finally:
sys.stdout = sys.stderr = env['PSTDOUT'] = \
env['PSTDERR'] = sconf.logstream
except KeyboardInterrupt:
raise
except SystemExit:
exc_value = sys.exc_info()[1]
raise SCons.Errors.ExplicitExit(self.targets[0],exc_value.code)
except Exception, e:
for t in self.targets:
binfo = t.get_binfo()
binfo.__class__ = SConfBuildInfo
binfo.set_build_result(1, s.getvalue())
sconsign_entry = SCons.SConsign.SConsignEntry()
sconsign_entry.binfo = binfo
#sconsign_entry.ninfo = self.get_ninfo()
# We'd like to do this as follows:
# t.store_info(binfo)
# However, we need to store it as an SConfBuildInfo
# object, and store_info() will turn it into a
# regular FileNodeInfo if the target is itself a
# regular File.
sconsign = t.dir.sconsign()
sconsign.set_entry(t.name, sconsign_entry)
sconsign.merge()
raise e
else:
for t in self.targets:
binfo = t.get_binfo()
binfo.__class__ = SConfBuildInfo
binfo.set_build_result(0, s.getvalue())
sconsign_entry = SCons.SConsign.SConsignEntry()
sconsign_entry.binfo = binfo
#sconsign_entry.ninfo = self.get_ninfo()
# We'd like to do this as follows:
# t.store_info(binfo)
# However, we need to store it as an SConfBuildInfo
# object, and store_info() will turn it into a
# regular FileNodeInfo if the target is itself a
# regular File.
sconsign = t.dir.sconsign()
sconsign.set_entry(t.name, sconsign_entry)
sconsign.merge()
class SConfBase:
"""This is simply a class to represent a configure context. After
creating a SConf object, you can call any tests. After finished with your
tests, be sure to call the Finish() method, which returns the modified
environment.
Some words about caching: In most cases, it is not necessary to cache
Test results explicitely. Instead, we use the scons dependency checking
mechanism. For example, if one wants to compile a test program
(SConf.TryLink), the compiler is only called, if the program dependencies
have changed. However, if the program could not be compiled in a former
SConf run, we need to explicitely cache this error.
"""
def __init__(self, env, custom_tests = {}, conf_dir='$CONFIGUREDIR',
log_file='$CONFIGURELOG', config_h = None, _depth = 0):
"""Constructor. Pass additional tests in the custom_tests-dictinary,
e.g. custom_tests={'CheckPrivate':MyPrivateTest}, where MyPrivateTest
defines a custom test.
Note also the conf_dir and log_file arguments (you may want to
build tests in the VariantDir, not in the SourceDir)
"""
global SConfFS
if not SConfFS:
SConfFS = SCons.Node.FS.default_fs or \
SCons.Node.FS.FS(env.fs.pathTop)
if sconf_global is not None:
raise (SCons.Errors.UserError,
"Only one SConf object may be active at one time")
self.env = env
if log_file is not None:
log_file = SConfFS.File(env.subst(log_file))
self.logfile = log_file
self.logstream = None
self.lastTarget = None
self.depth = _depth
self.cached = 0 # will be set, if all test results are cached
# add default tests
default_tests = {
'CheckCC' : CheckCC,
'CheckCXX' : CheckCXX,
'CheckSHCC' : CheckSHCC,
'CheckSHCXX' : CheckSHCXX,
'CheckFunc' : CheckFunc,
'CheckType' : CheckType,
'CheckTypeSize' : CheckTypeSize,
'CheckDeclaration' : CheckDeclaration,
'CheckHeader' : CheckHeader,
'CheckCHeader' : CheckCHeader,
'CheckCXXHeader' : CheckCXXHeader,
'CheckLib' : CheckLib,
'CheckLibWithHeader' : CheckLibWithHeader,
}
self.AddTests(default_tests)
self.AddTests(custom_tests)
self.confdir = SConfFS.Dir(env.subst(conf_dir))
if config_h is not None:
config_h = SConfFS.File(config_h)
self.config_h = config_h
self._startup()
def Finish(self):
"""Call this method after finished with your tests:
env = sconf.Finish()
"""
self._shutdown()
return self.env
def Define(self, name, value = None, comment = None):
"""
Define a pre processor symbol name, with the optional given value in the
current config header.
If value is None (default), then #define name is written. If value is not
none, then #define name value is written.
comment is a string which will be put as a C comment in the
header, to explain the meaning of the value (appropriate C comments /* and
*/ will be put automatically."""
lines = []
if comment:
comment_str = "/* %s */" % comment
lines.append(comment_str)
if value is not None:
define_str = "#define %s %s" % (name, value)
else:
define_str = "#define %s" % name
lines.append(define_str)
lines.append('')
self.config_h_text = self.config_h_text + string.join(lines, '\n')
def BuildNodes(self, nodes):
"""
Tries to build the given nodes immediately. Returns 1 on success,
0 on error.
"""
if self.logstream is not None:
# override stdout / stderr to write in log file
oldStdout = sys.stdout
sys.stdout = self.logstream
oldStderr = sys.stderr
sys.stderr = self.logstream
# the engine assumes the current path is the SConstruct directory ...
old_fs_dir = SConfFS.getcwd()
old_os_dir = os.getcwd()
SConfFS.chdir(SConfFS.Top, change_os_dir=1)
# Because we take responsibility here for writing out our
# own .sconsign info (see SConfBuildTask.execute(), above),
# we override the store_info() method with a null place-holder
# so we really control how it gets written.
for n in nodes:
n.store_info = n.do_not_store_info
ret = 1
try:
# ToDo: use user options for calc
save_max_drift = SConfFS.get_max_drift()
SConfFS.set_max_drift(0)
tm = SCons.Taskmaster.Taskmaster(nodes, SConfBuildTask)
# we don't want to build tests in parallel
jobs = SCons.Job.Jobs(1, tm )
jobs.run()
for n in nodes:
state = n.get_state()
if (state != SCons.Node.executed and
state != SCons.Node.up_to_date):
# the node could not be built. we return 0 in this case
ret = 0
finally:
SConfFS.set_max_drift(save_max_drift)
os.chdir(old_os_dir)
SConfFS.chdir(old_fs_dir, change_os_dir=0)
if self.logstream is not None:
# restore stdout / stderr
sys.stdout = oldStdout
sys.stderr = oldStderr
return ret
def pspawn_wrapper(self, sh, escape, cmd, args, env):
"""Wrapper function for handling piped spawns.
This looks to the calling interface (in Action.py) like a "normal"
spawn, but associates the call with the PSPAWN variable from
the construction environment and with the streams to which we
want the output logged. This gets slid into the construction
environment as the SPAWN variable so Action.py doesn't have to
know or care whether it's spawning a piped command or not.
"""
return self.pspawn(sh, escape, cmd, args, env, self.logstream, self.logstream)
def TryBuild(self, builder, text = None, extension = ""):
"""Low level TryBuild implementation. Normally you don't need to
call that - you can use TryCompile / TryLink / TryRun instead
"""
global _ac_build_counter
# Make sure we have a PSPAWN value, and save the current
# SPAWN value.
try:
self.pspawn = self.env['PSPAWN']
except KeyError:
raise SCons.Errors.UserError('Missing PSPAWN construction variable.')
try:
save_spawn = self.env['SPAWN']
except KeyError:
raise SCons.Errors.UserError('Missing SPAWN construction variable.')
nodesToBeBuilt = []
f = "conftest_" + str(_ac_build_counter)
pref = self.env.subst( builder.builder.prefix )
suff = self.env.subst( builder.builder.suffix )
target = self.confdir.File(pref + f + suff)
try:
# Slide our wrapper into the construction environment as
# the SPAWN function.
self.env['SPAWN'] = self.pspawn_wrapper
sourcetext = self.env.Value(text)
if text is not None:
textFile = self.confdir.File(f + extension)
textFileNode = self.env.SConfSourceBuilder(target=textFile,
source=sourcetext)
nodesToBeBuilt.extend(textFileNode)
source = textFileNode
else:
source = None
nodes = builder(target = target, source = source)
if not SCons.Util.is_List(nodes):
nodes = [nodes]
nodesToBeBuilt.extend(nodes)
result = self.BuildNodes(nodesToBeBuilt)
finally:
self.env['SPAWN'] = save_spawn
_ac_build_counter = _ac_build_counter + 1
if result:
self.lastTarget = nodes[0]
else:
self.lastTarget = None
return result
def TryAction(self, action, text = None, extension = ""):
"""Tries to execute the given action with optional source file
contents <text> and optional source file extension <extension>,
Returns the status (0 : failed, 1 : ok) and the contents of the
output file.
"""
builder = SCons.Builder.Builder(action=action)
self.env.Append( BUILDERS = {'SConfActionBuilder' : builder} )
ok = self.TryBuild(self.env.SConfActionBuilder, text, extension)
del self.env['BUILDERS']['SConfActionBuilder']
if ok:
outputStr = self.lastTarget.get_contents()
return (1, outputStr)
return (0, "")
def TryCompile( self, text, extension):
"""Compiles the program given in text to an env.Object, using extension
as file extension (e.g. '.c'). Returns 1, if compilation was
successful, 0 otherwise. The target is saved in self.lastTarget (for
further processing).
"""
return self.TryBuild(self.env.Object, text, extension)
def TryLink( self, text, extension ):
"""Compiles the program given in text to an executable env.Program,
using extension as file extension (e.g. '.c'). Returns 1, if
compilation was successful, 0 otherwise. The target is saved in
self.lastTarget (for further processing).
"""
return self.TryBuild(self.env.Program, text, extension )
def TryRun(self, text, extension ):
"""Compiles and runs the program given in text, using extension
as file extension (e.g. '.c'). Returns (1, outputStr) on success,
(0, '') otherwise. The target (a file containing the program's stdout)
is saved in self.lastTarget (for further processing).
"""
ok = self.TryLink(text, extension)
if( ok ):
prog = self.lastTarget
pname = prog.path
output = self.confdir.File(os.path.basename(pname)+'.out')
node = self.env.Command(output, prog, [ [ pname, ">", "${TARGET}"] ])
ok = self.BuildNodes(node)
if ok:
outputStr = output.get_contents()
return( 1, outputStr)
return (0, "")
class TestWrapper:
"""A wrapper around Tests (to ensure sanity)"""
def __init__(self, test, sconf):
self.test = test
self.sconf = sconf
def __call__(self, *args, **kw):
if not self.sconf.active:
raise (SCons.Errors.UserError,
"Test called after sconf.Finish()")
context = CheckContext(self.sconf)
ret = apply(self.test, (context,) + args, kw)
if self.sconf.config_h is not None:
self.sconf.config_h_text = self.sconf.config_h_text + context.config_h
context.Result("error: no result")
return ret
def AddTest(self, test_name, test_instance):
"""Adds test_class to this SConf instance. It can be called with
self.test_name(...)"""
setattr(self, test_name, SConfBase.TestWrapper(test_instance, self))
def AddTests(self, tests):
"""Adds all the tests given in the tests dictionary to this SConf
instance
"""
for name in tests.keys():
self.AddTest(name, tests[name])
def _createDir( self, node ):
dirName = str(node)
if dryrun:
if not os.path.isdir( dirName ):
raise ConfigureDryRunError(dirName)
else:
if not os.path.isdir( dirName ):
os.makedirs( dirName )
node._exists = 1
def _startup(self):
"""Private method. Set up logstream, and set the environment
variables necessary for a piped build
"""
global _ac_config_logs
global sconf_global
global SConfFS
self.lastEnvFs = self.env.fs
self.env.fs = SConfFS
self._createDir(self.confdir)
self.confdir.up().add_ignore( [self.confdir] )
if self.logfile is not None and not dryrun:
# truncate logfile, if SConf.Configure is called for the first time
# in a build
if _ac_config_logs.has_key(self.logfile):
log_mode = "a"
else:
_ac_config_logs[self.logfile] = None
log_mode = "w"
fp = open(str(self.logfile), log_mode)
self.logstream = SCons.Util.Unbuffered(fp)
# logfile may stay in a build directory, so we tell
# the build system not to override it with a eventually
# existing file with the same name in the source directory
self.logfile.dir.add_ignore( [self.logfile] )
tb = traceback.extract_stack()[-3-self.depth]
old_fs_dir = SConfFS.getcwd()
SConfFS.chdir(SConfFS.Top, change_os_dir=0)
self.logstream.write('file %s,line %d:\n\tConfigure(confdir = %s)\n' %
(tb[0], tb[1], str(self.confdir)) )
SConfFS.chdir(old_fs_dir)
else:
self.logstream = None
# we use a special builder to create source files from TEXT
action = SCons.Action.Action(_createSource,
_stringSource)
sconfSrcBld = SCons.Builder.Builder(action=action)
self.env.Append( BUILDERS={'SConfSourceBuilder':sconfSrcBld} )
self.config_h_text = _ac_config_hs.get(self.config_h, "")
self.active = 1
# only one SConf instance should be active at a time ...
sconf_global = self
def _shutdown(self):
"""Private method. Reset to non-piped spawn"""
global sconf_global, _ac_config_hs
if not self.active:
raise SCons.Errors.UserError, "Finish may be called only once!"
if self.logstream is not None and not dryrun:
self.logstream.write("\n")
self.logstream.close()
self.logstream = None
# remove the SConfSourceBuilder from the environment
blds = self.env['BUILDERS']
del blds['SConfSourceBuilder']
self.env.Replace( BUILDERS=blds )
self.active = 0
sconf_global = None
if not self.config_h is None:
_ac_config_hs[self.config_h] = self.config_h_text
self.env.fs = self.lastEnvFs
class CheckContext:
"""Provides a context for configure tests. Defines how a test writes to the
screen and log file.
A typical test is just a callable with an instance of CheckContext as
first argument:
def CheckCustom(context, ...)
context.Message('Checking my weird test ... ')
ret = myWeirdTestFunction(...)
context.Result(ret)
Often, myWeirdTestFunction will be one of
context.TryCompile/context.TryLink/context.TryRun. The results of
those are cached, for they are only rebuild, if the dependencies have
changed.
"""
def __init__(self, sconf):
"""Constructor. Pass the corresponding SConf instance."""
self.sconf = sconf
self.did_show_result = 0
# for Conftest.py:
self.vardict = {}
self.havedict = {}
self.headerfilename = None
self.config_h = "" # config_h text will be stored here
# we don't regenerate the config.h file after each test. That means,
# that tests won't be able to include the config.h file, and so
# they can't do an #ifdef HAVE_XXX_H. This shouldn't be a major
# issue, though. If it turns out, that we need to include config.h
# in tests, we must ensure, that the dependencies are worked out
# correctly. Note that we can't use Conftest.py's support for config.h,
# cause we will need to specify a builder for the config.h file ...
def Message(self, text):
"""Inform about what we are doing right now, e.g.
'Checking for SOMETHING ... '
"""
self.Display(text)
self.sconf.cached = 1
self.did_show_result = 0
def Result(self, res):
"""Inform about the result of the test. res may be an integer or a
string. In case of an integer, the written text will be 'yes' or 'no'.
The result is only displayed when self.did_show_result is not set.
"""
if type(res) in BooleanTypes:
if res:
text = "yes"
else:
text = "no"
elif type(res) == types.StringType:
text = res
else:
raise TypeError, "Expected string, int or bool, got " + str(type(res))
if self.did_show_result == 0:
# Didn't show result yet, do it now.
self.Display(text + "\n")
self.did_show_result = 1
def TryBuild(self, *args, **kw):
return apply(self.sconf.TryBuild, args, kw)
def TryAction(self, *args, **kw):
return apply(self.sconf.TryAction, args, kw)
def TryCompile(self, *args, **kw):
return apply(self.sconf.TryCompile, args, kw)
def TryLink(self, *args, **kw):
return apply(self.sconf.TryLink, args, kw)
def TryRun(self, *args, **kw):
return apply(self.sconf.TryRun, args, kw)
def __getattr__( self, attr ):
if( attr == 'env' ):
return self.sconf.env
elif( attr == 'lastTarget' ):
return self.sconf.lastTarget
else:
raise AttributeError, "CheckContext instance has no attribute '%s'" % attr
#### Stuff used by Conftest.py (look there for explanations).
def BuildProg(self, text, ext):
self.sconf.cached = 1
# TODO: should use self.vardict for $CC, $CPPFLAGS, etc.
return not self.TryBuild(self.env.Program, text, ext)
def CompileProg(self, text, ext):
self.sconf.cached = 1
# TODO: should use self.vardict for $CC, $CPPFLAGS, etc.
return not self.TryBuild(self.env.Object, text, ext)
def CompileSharedObject(self, text, ext):
self.sconf.cached = 1
# TODO: should use self.vardict for $SHCC, $CPPFLAGS, etc.
return not self.TryBuild(self.env.SharedObject, text, ext)
def RunProg(self, text, ext):
self.sconf.cached = 1
# TODO: should use self.vardict for $CC, $CPPFLAGS, etc.
st, out = self.TryRun(text, ext)
return not st, out
def AppendLIBS(self, lib_name_list):
oldLIBS = self.env.get( 'LIBS', [] )
self.env.Append(LIBS = lib_name_list)
return oldLIBS
def PrependLIBS(self, lib_name_list):
oldLIBS = self.env.get( 'LIBS', [] )
self.env.Prepend(LIBS = lib_name_list)
return oldLIBS
def SetLIBS(self, val):
oldLIBS = self.env.get( 'LIBS', [] )
self.env.Replace(LIBS = val)
return oldLIBS
def Display(self, msg):
if self.sconf.cached:
# We assume that Display is called twice for each test here
# once for the Checking for ... message and once for the result.
# The self.sconf.cached flag can only be set between those calls
msg = "(cached) " + msg
self.sconf.cached = 0
progress_display(msg, append_newline=0)
self.Log("scons: Configure: " + msg + "\n")
def Log(self, msg):
if self.sconf.logstream is not None:
self.sconf.logstream.write(msg)
#### End of stuff used by Conftest.py.
def SConf(*args, **kw):
if kw.get(build_type, True):
kw['_depth'] = kw.get('_depth', 0) + 1
for bt in build_types:
try:
del kw[bt]
except KeyError:
pass
return apply(SConfBase, args, kw)
else:
return SCons.Util.Null()
def CheckFunc(context, function_name, header = None, language = None):
res = SCons.Conftest.CheckFunc(context, function_name, header = header, language = language)
context.did_show_result = 1
return not res
def CheckType(context, type_name, includes = "", language = None):
res = SCons.Conftest.CheckType(context, type_name,
header = includes, language = language)
context.did_show_result = 1
return not res
def CheckTypeSize(context, type_name, includes = "", language = None, expect = None):
res = SCons.Conftest.CheckTypeSize(context, type_name,
header = includes, language = language,
expect = expect)
context.did_show_result = 1
return res
def CheckDeclaration(context, declaration, includes = "", language = None):
res = SCons.Conftest.CheckDeclaration(context, declaration,
includes = includes,
language = language)
context.did_show_result = 1
return not res
def createIncludesFromHeaders(headers, leaveLast, include_quotes = '""'):
# used by CheckHeader and CheckLibWithHeader to produce C - #include
# statements from the specified header (list)
if not SCons.Util.is_List(headers):
headers = [headers]
l = []
if leaveLast:
lastHeader = headers[-1]
headers = headers[:-1]
else:
lastHeader = None
for s in headers:
l.append("#include %s%s%s\n"
% (include_quotes[0], s, include_quotes[1]))
return string.join(l, ''), lastHeader
def CheckHeader(context, header, include_quotes = '<>', language = None):
"""
A test for a C or C++ header file.
"""
prog_prefix, hdr_to_check = \
createIncludesFromHeaders(header, 1, include_quotes)
res = SCons.Conftest.CheckHeader(context, hdr_to_check, prog_prefix,
language = language,
include_quotes = include_quotes)
context.did_show_result = 1
return not res
def CheckCC(context):
res = SCons.Conftest.CheckCC(context)
context.did_show_result = 1
return not res
def CheckCXX(context):
res = SCons.Conftest.CheckCXX(context)
context.did_show_result = 1
return not res
def CheckSHCC(context):
res = SCons.Conftest.CheckSHCC(context)
context.did_show_result = 1
return not res
def CheckSHCXX(context):
res = SCons.Conftest.CheckSHCXX(context)
context.did_show_result = 1
return not res
# Bram: Make this function obsolete? CheckHeader() is more generic.
def CheckCHeader(context, header, include_quotes = '""'):
"""
A test for a C header file.
"""
return CheckHeader(context, header, include_quotes, language = "C")
# Bram: Make this function obsolete? CheckHeader() is more generic.
def CheckCXXHeader(context, header, include_quotes = '""'):
"""
A test for a C++ header file.
"""
return CheckHeader(context, header, include_quotes, language = "C++")
def CheckLib(context, library = None, symbol = "main",
header = None, language = None, autoadd = 1):
"""
A test for a library. See also CheckLibWithHeader.
Note that library may also be None to test whether the given symbol
compiles without flags.
"""
if library == []:
library = [None]
if not SCons.Util.is_List(library):
library = [library]
# ToDo: accept path for the library
res = SCons.Conftest.CheckLib(context, library, symbol, header = header,
language = language, autoadd = autoadd)
context.did_show_result = 1
return not res
# XXX
# Bram: Can only include one header and can't use #ifdef HAVE_HEADER_H.
def CheckLibWithHeader(context, libs, header, language,
call = None, autoadd = 1):
# ToDo: accept path for library. Support system header files.
"""
Another (more sophisticated) test for a library.
Checks, if library and header is available for language (may be 'C'
or 'CXX'). Call maybe be a valid expression _with_ a trailing ';'.
As in CheckLib, we support library=None, to test if the call compiles
without extra link flags.
"""
prog_prefix, dummy = \
createIncludesFromHeaders(header, 0)
if libs == []:
libs = [None]
if not SCons.Util.is_List(libs):
libs = [libs]
res = SCons.Conftest.CheckLib(context, libs, None, prog_prefix,
call = call, language = language, autoadd = autoadd)
context.did_show_result = 1
return not res
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Defaults
Builders and other things for the local site. Here's where we'll
duplicate the functionality of autoconf until we move it into the
installation procedure or use something like qmconf.
The code that reads the registry to find MSVC components was borrowed
from distutils.msvccompiler.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Defaults.py 4720 2010/03/24 03:14:11 jars"
import os
import os.path
import errno
import shutil
import stat
import string
import time
import types
import sys
import SCons.Action
import SCons.Builder
import SCons.CacheDir
import SCons.Environment
import SCons.PathList
import SCons.Subst
import SCons.Tool
# A placeholder for a default Environment (for fetching source files
# from source code management systems and the like). This must be
# initialized later, after the top-level directory is set by the calling
# interface.
_default_env = None
# Lazily instantiate the default environment so the overhead of creating
# it doesn't apply when it's not needed.
def _fetch_DefaultEnvironment(*args, **kw):
"""
Returns the already-created default construction environment.
"""
global _default_env
return _default_env
def DefaultEnvironment(*args, **kw):
"""
Initial public entry point for creating the default construction
Environment.
After creating the environment, we overwrite our name
(DefaultEnvironment) with the _fetch_DefaultEnvironment() function,
which more efficiently returns the initialized default construction
environment without checking for its existence.
(This function still exists with its _default_check because someone
else (*cough* Script/__init__.py *cough*) may keep a reference
to this function. So we can't use the fully functional idiom of
having the name originally be a something that *only* creates the
construction environment and then overwrites the name.)
"""
global _default_env
if not _default_env:
import SCons.Util
_default_env = apply(SCons.Environment.Environment, args, kw)
if SCons.Util.md5:
_default_env.Decider('MD5')
else:
_default_env.Decider('timestamp-match')
global DefaultEnvironment
DefaultEnvironment = _fetch_DefaultEnvironment
_default_env._CacheDir_path = None
return _default_env
# Emitters for setting the shared attribute on object files,
# and an action for checking that all of the source files
# going into a shared library are, in fact, shared.
def StaticObjectEmitter(target, source, env):
for tgt in target:
tgt.attributes.shared = None
return (target, source)
def SharedObjectEmitter(target, source, env):
for tgt in target:
tgt.attributes.shared = 1
return (target, source)
def SharedFlagChecker(source, target, env):
same = env.subst('$STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME')
if same == '0' or same == '' or same == 'False':
for src in source:
try:
shared = src.attributes.shared
except AttributeError:
shared = None
if not shared:
raise SCons.Errors.UserError, "Source file: %s is static and is not compatible with shared target: %s" % (src, target[0])
SharedCheck = SCons.Action.Action(SharedFlagChecker, None)
# Some people were using these variable name before we made
# SourceFileScanner part of the public interface. Don't break their
# SConscript files until we've given them some fair warning and a
# transition period.
CScan = SCons.Tool.CScanner
DScan = SCons.Tool.DScanner
LaTeXScan = SCons.Tool.LaTeXScanner
ObjSourceScan = SCons.Tool.SourceFileScanner
ProgScan = SCons.Tool.ProgramScanner
# These aren't really tool scanners, so they don't quite belong with
# the rest of those in Tool/__init__.py, but I'm not sure where else
# they should go. Leave them here for now.
import SCons.Scanner.Dir
DirScanner = SCons.Scanner.Dir.DirScanner()
DirEntryScanner = SCons.Scanner.Dir.DirEntryScanner()
# Actions for common languages.
CAction = SCons.Action.Action("$CCCOM", "$CCCOMSTR")
ShCAction = SCons.Action.Action("$SHCCCOM", "$SHCCCOMSTR")
CXXAction = SCons.Action.Action("$CXXCOM", "$CXXCOMSTR")
ShCXXAction = SCons.Action.Action("$SHCXXCOM", "$SHCXXCOMSTR")
ASAction = SCons.Action.Action("$ASCOM", "$ASCOMSTR")
ASPPAction = SCons.Action.Action("$ASPPCOM", "$ASPPCOMSTR")
LinkAction = SCons.Action.Action("$LINKCOM", "$LINKCOMSTR")
ShLinkAction = SCons.Action.Action("$SHLINKCOM", "$SHLINKCOMSTR")
LdModuleLinkAction = SCons.Action.Action("$LDMODULECOM", "$LDMODULECOMSTR")
# Common tasks that we allow users to perform in platform-independent
# ways by creating ActionFactory instances.
ActionFactory = SCons.Action.ActionFactory
def get_paths_str(dest):
# If dest is a list, we need to manually call str() on each element
if SCons.Util.is_List(dest):
elem_strs = []
for element in dest:
elem_strs.append('"' + str(element) + '"')
return '[' + string.join(elem_strs, ', ') + ']'
else:
return '"' + str(dest) + '"'
def chmod_func(dest, mode):
SCons.Node.FS.invalidate_node_memos(dest)
if not SCons.Util.is_List(dest):
dest = [dest]
for element in dest:
os.chmod(str(element), mode)
def chmod_strfunc(dest, mode):
return 'Chmod(%s, 0%o)' % (get_paths_str(dest), mode)
Chmod = ActionFactory(chmod_func, chmod_strfunc)
def copy_func(dest, src):
SCons.Node.FS.invalidate_node_memos(dest)
if SCons.Util.is_List(src) and os.path.isdir(dest):
for file in src:
shutil.copy2(file, dest)
return 0
elif os.path.isfile(src):
return shutil.copy2(src, dest)
else:
return shutil.copytree(src, dest, 1)
Copy = ActionFactory(copy_func,
lambda dest, src: 'Copy("%s", "%s")' % (dest, src),
convert=str)
def delete_func(dest, must_exist=0):
SCons.Node.FS.invalidate_node_memos(dest)
if not SCons.Util.is_List(dest):
dest = [dest]
for entry in dest:
entry = str(entry)
if not must_exist and not os.path.exists(entry):
continue
if not os.path.exists(entry) or os.path.isfile(entry):
os.unlink(entry)
continue
else:
shutil.rmtree(entry, 1)
continue
def delete_strfunc(dest, must_exist=0):
return 'Delete(%s)' % get_paths_str(dest)
Delete = ActionFactory(delete_func, delete_strfunc)
def mkdir_func(dest):
SCons.Node.FS.invalidate_node_memos(dest)
if not SCons.Util.is_List(dest):
dest = [dest]
for entry in dest:
try:
os.makedirs(str(entry))
except os.error, e:
p = str(entry)
if (e[0] == errno.EEXIST or (sys.platform=='win32' and e[0]==183)) \
and os.path.isdir(str(entry)):
pass # not an error if already exists
else:
raise
Mkdir = ActionFactory(mkdir_func,
lambda dir: 'Mkdir(%s)' % get_paths_str(dir))
def move_func(dest, src):
SCons.Node.FS.invalidate_node_memos(dest)
SCons.Node.FS.invalidate_node_memos(src)
shutil.move(src, dest)
Move = ActionFactory(move_func,
lambda dest, src: 'Move("%s", "%s")' % (dest, src),
convert=str)
def touch_func(dest):
SCons.Node.FS.invalidate_node_memos(dest)
if not SCons.Util.is_List(dest):
dest = [dest]
for file in dest:
file = str(file)
mtime = int(time.time())
if os.path.exists(file):
atime = os.path.getatime(file)
else:
open(file, 'w')
atime = mtime
os.utime(file, (atime, mtime))
Touch = ActionFactory(touch_func,
lambda file: 'Touch(%s)' % get_paths_str(file))
# Internal utility functions
def _concat(prefix, list, suffix, env, f=lambda x: x, target=None, source=None):
"""
Creates a new list from 'list' by first interpolating each element
in the list using the 'env' dictionary and then calling f on the
list, and finally calling _concat_ixes to concatenate 'prefix' and
'suffix' onto each element of the list.
"""
if not list:
return list
l = f(SCons.PathList.PathList(list).subst_path(env, target, source))
if l is not None:
list = l
return _concat_ixes(prefix, list, suffix, env)
def _concat_ixes(prefix, list, suffix, env):
"""
Creates a new list from 'list' by concatenating the 'prefix' and
'suffix' arguments onto each element of the list. A trailing space
on 'prefix' or leading space on 'suffix' will cause them to be put
into separate list elements rather than being concatenated.
"""
result = []
# ensure that prefix and suffix are strings
prefix = str(env.subst(prefix, SCons.Subst.SUBST_RAW))
suffix = str(env.subst(suffix, SCons.Subst.SUBST_RAW))
for x in list:
if isinstance(x, SCons.Node.FS.File):
result.append(x)
continue
x = str(x)
if x:
if prefix:
if prefix[-1] == ' ':
result.append(prefix[:-1])
elif x[:len(prefix)] != prefix:
x = prefix + x
result.append(x)
if suffix:
if suffix[0] == ' ':
result.append(suffix[1:])
elif x[-len(suffix):] != suffix:
result[-1] = result[-1]+suffix
return result
def _stripixes(prefix, list, suffix, stripprefixes, stripsuffixes, env, c=None):
"""
This is a wrapper around _concat()/_concat_ixes() that checks for the
existence of prefixes or suffixes on list elements and strips them
where it finds them. This is used by tools (like the GNU linker)
that need to turn something like 'libfoo.a' into '-lfoo'.
"""
if not list:
return list
if not callable(c):
env_c = env['_concat']
if env_c != _concat and callable(env_c):
# There's a custom _concat() method in the construction
# environment, and we've allowed people to set that in
# the past (see test/custom-concat.py), so preserve the
# backwards compatibility.
c = env_c
else:
c = _concat_ixes
stripprefixes = map(env.subst, SCons.Util.flatten(stripprefixes))
stripsuffixes = map(env.subst, SCons.Util.flatten(stripsuffixes))
stripped = []
for l in SCons.PathList.PathList(list).subst_path(env, None, None):
if isinstance(l, SCons.Node.FS.File):
stripped.append(l)
continue
if not SCons.Util.is_String(l):
l = str(l)
for stripprefix in stripprefixes:
lsp = len(stripprefix)
if l[:lsp] == stripprefix:
l = l[lsp:]
# Do not strip more than one prefix
break
for stripsuffix in stripsuffixes:
lss = len(stripsuffix)
if l[-lss:] == stripsuffix:
l = l[:-lss]
# Do not strip more than one suffix
break
stripped.append(l)
return c(prefix, stripped, suffix, env)
def processDefines(defs):
"""process defines, resolving strings, lists, dictionaries, into a list of
strings
"""
if SCons.Util.is_List(defs):
l = []
for d in defs:
if SCons.Util.is_List(d) or type(d) is types.TupleType:
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
elif SCons.Util.is_Dict(defs):
# The items in a dictionary are stored in random order, but
# if the order of the command-line options changes from
# invocation to invocation, then the signature of the command
# line will change and we'll get random unnecessary rebuilds.
# Consequently, we have to sort the keys to ensure a
# consistent order...
l = []
keys = defs.keys()
keys.sort()
for k in keys:
v = defs[k]
if v is None:
l.append(str(k))
else:
l.append(str(k) + '=' + str(v))
else:
l = [str(defs)]
return l
def _defines(prefix, defs, suffix, env, c=_concat_ixes):
"""A wrapper around _concat_ixes that turns a list or string
into a list of C preprocessor command-line definitions.
"""
return c(prefix, env.subst_path(processDefines(defs)), suffix, env)
class NullCmdGenerator:
"""This is a callable class that can be used in place of other
command generators if you don't want them to do anything.
The __call__ method for this class simply returns the thing
you instantiated it with.
Example usage:
env["DO_NOTHING"] = NullCmdGenerator
env["LINKCOM"] = "${DO_NOTHING('$LINK $SOURCES $TARGET')}"
"""
def __init__(self, cmd):
self.cmd = cmd
def __call__(self, target, source, env, for_signature=None):
return self.cmd
class Variable_Method_Caller:
"""A class for finding a construction variable on the stack and
calling one of its methods.
We use this to support "construction variables" in our string
eval()s that actually stand in for methods--specifically, use
of "RDirs" in call to _concat that should actually execute the
"TARGET.RDirs" method. (We used to support this by creating a little
"build dictionary" that mapped RDirs to the method, but this got in
the way of Memoizing construction environments, because we had to
create new environment objects to hold the variables.)
"""
def __init__(self, variable, method):
self.variable = variable
self.method = method
def __call__(self, *args, **kw):
try: 1/0
except ZeroDivisionError:
# Don't start iterating with the current stack-frame to
# prevent creating reference cycles (f_back is safe).
frame = sys.exc_info()[2].tb_frame.f_back
variable = self.variable
while frame:
if frame.f_locals.has_key(variable):
v = frame.f_locals[variable]
if v:
method = getattr(v, self.method)
return apply(method, args, kw)
frame = frame.f_back
return None
ConstructionEnvironment = {
'BUILDERS' : {},
'SCANNERS' : [],
'CONFIGUREDIR' : '#/.sconf_temp',
'CONFIGURELOG' : '#/config.log',
'CPPSUFFIXES' : SCons.Tool.CSuffixes,
'DSUFFIXES' : SCons.Tool.DSuffixes,
'ENV' : {},
'IDLSUFFIXES' : SCons.Tool.IDLSuffixes,
# 'LATEXSUFFIXES' : SCons.Tool.LaTeXSuffixes, # moved to the TeX tools generate functions
'_concat' : _concat,
'_defines' : _defines,
'_stripixes' : _stripixes,
'_LIBFLAGS' : '${_concat(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, __env__)}',
'_LIBDIRFLAGS' : '$( ${_concat(LIBDIRPREFIX, LIBPATH, LIBDIRSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)',
'_CPPINCFLAGS' : '$( ${_concat(INCPREFIX, CPPPATH, INCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)',
'_CPPDEFFLAGS' : '${_defines(CPPDEFPREFIX, CPPDEFINES, CPPDEFSUFFIX, __env__)}',
'TEMPFILE' : NullCmdGenerator,
'Dir' : Variable_Method_Caller('TARGET', 'Dir'),
'Dirs' : Variable_Method_Caller('TARGET', 'Dirs'),
'File' : Variable_Method_Caller('TARGET', 'File'),
'RDirs' : Variable_Method_Caller('TARGET', 'RDirs'),
}
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/CacheDir.py 4720 2010/03/24 03:14:11 jars"
__doc__ = """
CacheDir support
"""
import os.path
import stat
import string
import sys
import SCons.Action
cache_enabled = True
cache_debug = False
cache_force = False
cache_show = False
def CacheRetrieveFunc(target, source, env):
t = target[0]
fs = t.fs
cd = env.get_CacheDir()
cachedir, cachefile = cd.cachepath(t)
if not fs.exists(cachefile):
cd.CacheDebug('CacheRetrieve(%s): %s not in cache\n', t, cachefile)
return 1
cd.CacheDebug('CacheRetrieve(%s): retrieving from %s\n', t, cachefile)
if SCons.Action.execute_actions:
if fs.islink(cachefile):
fs.symlink(fs.readlink(cachefile), t.path)
else:
env.copy_from_cache(cachefile, t.path)
st = fs.stat(cachefile)
fs.chmod(t.path, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
return 0
def CacheRetrieveString(target, source, env):
t = target[0]
fs = t.fs
cd = env.get_CacheDir()
cachedir, cachefile = cd.cachepath(t)
if t.fs.exists(cachefile):
return "Retrieved `%s' from cache" % t.path
return None
CacheRetrieve = SCons.Action.Action(CacheRetrieveFunc, CacheRetrieveString)
CacheRetrieveSilent = SCons.Action.Action(CacheRetrieveFunc, None)
def CachePushFunc(target, source, env):
t = target[0]
if t.nocache:
return
fs = t.fs
cd = env.get_CacheDir()
cachedir, cachefile = cd.cachepath(t)
if fs.exists(cachefile):
# Don't bother copying it if it's already there. Note that
# usually this "shouldn't happen" because if the file already
# existed in cache, we'd have retrieved the file from there,
# not built it. This can happen, though, in a race, if some
# other person running the same build pushes their copy to
# the cache after we decide we need to build it but before our
# build completes.
cd.CacheDebug('CachePush(%s): %s already exists in cache\n', t, cachefile)
return
cd.CacheDebug('CachePush(%s): pushing to %s\n', t, cachefile)
tempfile = cachefile+'.tmp'+str(os.getpid())
errfmt = "Unable to copy %s to cache. Cache file is %s"
if not fs.isdir(cachedir):
try:
fs.makedirs(cachedir)
except EnvironmentError:
# We may have received an exception because another process
# has beaten us creating the directory.
if not fs.isdir(cachedir):
msg = errfmt % (str(target), cachefile)
raise SCons.Errors.EnvironmentError, msg
try:
if fs.islink(t.path):
fs.symlink(fs.readlink(t.path), tempfile)
else:
fs.copy2(t.path, tempfile)
fs.rename(tempfile, cachefile)
st = fs.stat(t.path)
fs.chmod(cachefile, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
except EnvironmentError:
# It's possible someone else tried writing the file at the
# same time we did, or else that there was some problem like
# the CacheDir being on a separate file system that's full.
# In any case, inability to push a file to cache doesn't affect
# the correctness of the build, so just print a warning.
msg = errfmt % (str(target), cachefile)
SCons.Warnings.warn(SCons.Warnings.CacheWriteErrorWarning, msg)
CachePush = SCons.Action.Action(CachePushFunc, None)
class CacheDir:
def __init__(self, path):
try:
import hashlib
except ImportError:
msg = "No hashlib or MD5 module available, CacheDir() not supported"
SCons.Warnings.warn(SCons.Warnings.NoMD5ModuleWarning, msg)
self.path = None
else:
self.path = path
self.current_cache_debug = None
self.debugFP = None
def CacheDebug(self, fmt, target, cachefile):
if cache_debug != self.current_cache_debug:
if cache_debug == '-':
self.debugFP = sys.stdout
elif cache_debug:
self.debugFP = open(cache_debug, 'w')
else:
self.debugFP = None
self.current_cache_debug = cache_debug
if self.debugFP:
self.debugFP.write(fmt % (target, os.path.split(cachefile)[1]))
def is_enabled(self):
return (cache_enabled and not self.path is None)
def cachepath(self, node):
"""
"""
if not self.is_enabled():
return None, None
sig = node.get_cachedir_bsig()
subdir = string.upper(sig[0])
dir = os.path.join(self.path, subdir)
return dir, os.path.join(dir, sig)
def retrieve(self, node):
"""
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff in
built().
Note that there's a special trick here with the execute flag
(one that's not normally done for other actions). Basically
if the user requested a no_exec (-n) build, then
SCons.Action.execute_actions is set to 0 and when any action
is called, it does its showing but then just returns zero
instead of actually calling the action execution operation.
The problem for caching is that if the file does NOT exist in
cache then the CacheRetrieveString won't return anything to
show for the task, but the Action.__call__ won't call
CacheRetrieveFunc; instead it just returns zero, which makes
the code below think that the file *was* successfully
retrieved from the cache, therefore it doesn't do any
subsequent building. However, the CacheRetrieveString didn't
print anything because it didn't actually exist in the cache,
and no more build actions will be performed, so the user just
sees nothing. The fix is to tell Action.__call__ to always
execute the CacheRetrieveFunc and then have the latter
explicitly check SCons.Action.execute_actions itself.
"""
if not self.is_enabled():
return False
env = node.get_build_env()
if cache_show:
if CacheRetrieveSilent(node, [], env, execute=1) == 0:
node.build(presub=0, execute=0)
return True
else:
if CacheRetrieve(node, [], env, execute=1) == 0:
return True
return False
def push(self, node):
if not self.is_enabled():
return
return CachePush(node, [], node.get_build_env())
def push_if_forced(self, node):
if cache_force:
return self.push(node)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.SConsign
Writing and reading information to the .sconsign file or files.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/SConsign.py 4720 2010/03/24 03:14:11 jars"
import cPickle
import os
import os.path
import SCons.dblite
import SCons.Warnings
def corrupt_dblite_warning(filename):
SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
"Ignoring corrupt .sconsign file: %s"%filename)
SCons.dblite.ignore_corrupt_dbfiles = 1
SCons.dblite.corruption_warning = corrupt_dblite_warning
#XXX Get rid of the global array so this becomes re-entrant.
sig_files = []
# Info for the database SConsign implementation (now the default):
# "DataBase" is a dictionary that maps top-level SConstruct directories
# to open database handles.
# "DB_Module" is the Python database module to create the handles.
# "DB_Name" is the base name of the database file (minus any
# extension the underlying DB module will add).
DataBase = {}
DB_Module = SCons.dblite
DB_Name = ".sconsign"
DB_sync_list = []
def Get_DataBase(dir):
global DataBase, DB_Module, DB_Name
top = dir.fs.Top
if not os.path.isabs(DB_Name) and top.repositories:
mode = "c"
for d in [top] + top.repositories:
if dir.is_under(d):
try:
return DataBase[d], mode
except KeyError:
path = d.entry_abspath(DB_Name)
try: db = DataBase[d] = DB_Module.open(path, mode)
except (IOError, OSError): pass
else:
if mode != "r":
DB_sync_list.append(db)
return db, mode
mode = "r"
try:
return DataBase[top], "c"
except KeyError:
db = DataBase[top] = DB_Module.open(DB_Name, "c")
DB_sync_list.append(db)
return db, "c"
except TypeError:
print "DataBase =", DataBase
raise
def Reset():
"""Reset global state. Used by unit tests that end up using
SConsign multiple times to get a clean slate for each test."""
global sig_files, DB_sync_list
sig_files = []
DB_sync_list = []
normcase = os.path.normcase
def write():
global sig_files
for sig_file in sig_files:
sig_file.write(sync=0)
for db in DB_sync_list:
try:
syncmethod = db.sync
except AttributeError:
pass # Not all anydbm modules have sync() methods.
else:
syncmethod()
class SConsignEntry:
"""
Wrapper class for the generic entry in a .sconsign file.
The Node subclass populates it with attributes as it pleases.
XXX As coded below, we do expect a '.binfo' attribute to be added,
but we'll probably generalize this in the next refactorings.
"""
current_version_id = 1
def __init__(self):
# Create an object attribute from the class attribute so it ends up
# in the pickled data in the .sconsign file.
_version_id = self.current_version_id
def convert_to_sconsign(self):
self.binfo.convert_to_sconsign()
def convert_from_sconsign(self, dir, name):
self.binfo.convert_from_sconsign(dir, name)
class Base:
"""
This is the controlling class for the signatures for the collection of
entries associated with a specific directory. The actual directory
association will be maintained by a subclass that is specific to
the underlying storage method. This class provides a common set of
methods for fetching and storing the individual bits of information
that make up signature entry.
"""
def __init__(self):
self.entries = {}
self.dirty = False
self.to_be_merged = {}
def get_entry(self, filename):
"""
Fetch the specified entry attribute.
"""
return self.entries[filename]
def set_entry(self, filename, obj):
"""
Set the entry.
"""
self.entries[filename] = obj
self.dirty = True
def do_not_set_entry(self, filename, obj):
pass
def store_info(self, filename, node):
entry = node.get_stored_info()
entry.binfo.merge(node.get_binfo())
self.to_be_merged[filename] = node
self.dirty = True
def do_not_store_info(self, filename, node):
pass
def merge(self):
for key, node in self.to_be_merged.items():
entry = node.get_stored_info()
try:
ninfo = entry.ninfo
except AttributeError:
# This happens with SConf Nodes, because the configuration
# subsystem takes direct control over how the build decision
# is made and its information stored.
pass
else:
ninfo.merge(node.get_ninfo())
self.entries[key] = entry
self.to_be_merged = {}
class DB(Base):
"""
A Base subclass that reads and writes signature information
from a global .sconsign.db* file--the actual file suffix is
determined by the database module.
"""
def __init__(self, dir):
Base.__init__(self)
self.dir = dir
db, mode = Get_DataBase(dir)
# Read using the path relative to the top of the Repository
# (self.dir.tpath) from which we're fetching the signature
# information.
path = normcase(dir.tpath)
try:
rawentries = db[path]
except KeyError:
pass
else:
try:
self.entries = cPickle.loads(rawentries)
if type(self.entries) is not type({}):
self.entries = {}
raise TypeError
except KeyboardInterrupt:
raise
except Exception, e:
SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
"Ignoring corrupt sconsign entry : %s (%s)\n"%(self.dir.tpath, e))
for key, entry in self.entries.items():
entry.convert_from_sconsign(dir, key)
if mode == "r":
# This directory is actually under a repository, which means
# likely they're reaching in directly for a dependency on
# a file there. Don't actually set any entry info, so we
# won't try to write to that .sconsign.dblite file.
self.set_entry = self.do_not_set_entry
self.store_info = self.do_not_store_info
global sig_files
sig_files.append(self)
def write(self, sync=1):
if not self.dirty:
return
self.merge()
db, mode = Get_DataBase(self.dir)
# Write using the path relative to the top of the SConstruct
# directory (self.dir.path), not relative to the top of
# the Repository; we only write to our own .sconsign file,
# not to .sconsign files in Repositories.
path = normcase(self.dir.path)
for key, entry in self.entries.items():
entry.convert_to_sconsign()
db[path] = cPickle.dumps(self.entries, 1)
if sync:
try:
syncmethod = db.sync
except AttributeError:
# Not all anydbm modules have sync() methods.
pass
else:
syncmethod()
class Dir(Base):
def __init__(self, fp=None, dir=None):
"""
fp - file pointer to read entries from
"""
Base.__init__(self)
if not fp:
return
self.entries = cPickle.load(fp)
if type(self.entries) is not type({}):
self.entries = {}
raise TypeError
if dir:
for key, entry in self.entries.items():
entry.convert_from_sconsign(dir, key)
class DirFile(Dir):
"""
Encapsulates reading and writing a per-directory .sconsign file.
"""
def __init__(self, dir):
"""
dir - the directory for the file
"""
self.dir = dir
self.sconsign = os.path.join(dir.path, '.sconsign')
try:
fp = open(self.sconsign, 'rb')
except IOError:
fp = None
try:
Dir.__init__(self, fp, dir)
except KeyboardInterrupt:
raise
except:
SCons.Warnings.warn(SCons.Warnings.CorruptSConsignWarning,
"Ignoring corrupt .sconsign file: %s"%self.sconsign)
global sig_files
sig_files.append(self)
def write(self, sync=1):
"""
Write the .sconsign file to disk.
Try to write to a temporary file first, and rename it if we
succeed. If we can't write to the temporary file, it's
probably because the directory isn't writable (and if so,
how did we build anything in this directory, anyway?), so
try to write directly to the .sconsign file as a backup.
If we can't rename, try to copy the temporary contents back
to the .sconsign file. Either way, always try to remove
the temporary file at the end.
"""
if not self.dirty:
return
self.merge()
temp = os.path.join(self.dir.path, '.scons%d' % os.getpid())
try:
file = open(temp, 'wb')
fname = temp
except IOError:
try:
file = open(self.sconsign, 'wb')
fname = self.sconsign
except IOError:
return
for key, entry in self.entries.items():
entry.convert_to_sconsign()
cPickle.dump(self.entries, file, 1)
file.close()
if fname != self.sconsign:
try:
mode = os.stat(self.sconsign)[0]
os.chmod(self.sconsign, 0666)
os.unlink(self.sconsign)
except (IOError, OSError):
# Try to carry on in the face of either OSError
# (things like permission issues) or IOError (disk
# or network issues). If there's a really dangerous
# issue, it should get re-raised by the calls below.
pass
try:
os.rename(fname, self.sconsign)
except OSError:
# An OSError failure to rename may indicate something
# like the directory has no write permission, but
# the .sconsign file itself might still be writable,
# so try writing on top of it directly. An IOError
# here, or in any of the following calls, would get
# raised, indicating something like a potentially
# serious disk or network issue.
open(self.sconsign, 'wb').write(open(fname, 'rb').read())
os.chmod(self.sconsign, mode)
try:
os.unlink(temp)
except (IOError, OSError):
pass
ForDirectory = DB
def File(name, dbm_module=None):
"""
Arrange for all signatures to be stored in a global .sconsign.db*
file.
"""
global ForDirectory, DB_Name, DB_Module
if name is None:
ForDirectory = DirFile
DB_Module = None
else:
ForDirectory = DB
DB_Name = name
if not dbm_module is None:
DB_Module = dbm_module
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
"""SCons.Errors
This file contains the exception classes used to handle internal
and user errors in SCons.
"""
__revision__ = "src/engine/SCons/Errors.py 4720 2010/03/24 03:14:11 jars"
import SCons.Util
import exceptions
class BuildError(Exception):
""" Errors occuring while building.
BuildError have the following attributes:
Information about the cause of the build error:
-----------------------------------------------
errstr : a description of the error message
status : the return code of the action that caused the build
error. Must be set to a non-zero value even if the
build error is not due to an action returning a
non-zero returned code.
exitstatus : SCons exit status due to this build error.
Must be nonzero unless due to an explicit Exit()
call. Not always the same as status, since
actions return a status code that should be
respected, but SCons typically exits with 2
irrespective of the return value of the failed
action.
filename : The name of the file or directory that caused the
build error. Set to None if no files are associated with
this error. This might be different from the target
being built. For example, failure to create the
directory in which the target file will appear. It
can be None if the error is not due to a particular
filename.
exc_info : Info about exception that caused the build
error. Set to (None, None, None) if this build
error is not due to an exception.
Information about the cause of the location of the error:
---------------------------------------------------------
node : the error occured while building this target node(s)
executor : the executor that caused the build to fail (might
be None if the build failures is not due to the
executor failing)
action : the action that caused the build to fail (might be
None if the build failures is not due to the an
action failure)
command : the command line for the action that caused the
build to fail (might be None if the build failures
is not due to the an action failure)
"""
def __init__(self,
node=None, errstr="Unknown error", status=2, exitstatus=2,
filename=None, executor=None, action=None, command=None,
exc_info=(None, None, None)):
self.errstr = errstr
self.status = status
self.exitstatus = exitstatus
self.filename = filename
self.exc_info = exc_info
self.node = node
self.executor = executor
self.action = action
self.command = command
Exception.__init__(self, node, errstr, status, exitstatus, filename,
executor, action, command, exc_info)
def __str__(self):
if self.filename:
return self.filename + ': ' + self.errstr
else:
return self.errstr
class InternalError(Exception):
pass
class UserError(Exception):
pass
class StopError(Exception):
pass
class EnvironmentError(Exception):
pass
class MSVCError(IOError):
pass
class ExplicitExit(Exception):
def __init__(self, node=None, status=None, *args):
self.node = node
self.status = status
self.exitstatus = status
apply(Exception.__init__, (self,) + args)
def convert_to_BuildError(status, exc_info=None):
"""
Convert any return code a BuildError Exception.
`status' can either be a return code or an Exception.
The buildError.status we set here will normally be
used as the exit status of the "scons" process.
"""
if not exc_info and isinstance(status, Exception):
exc_info = (status.__class__, status, None)
if isinstance(status, BuildError):
buildError = status
buildError.exitstatus = 2 # always exit with 2 on build errors
elif isinstance(status, ExplicitExit):
status = status.status
errstr = 'Explicit exit, status %s' % status
buildError = BuildError(
errstr=errstr,
status=status, # might be 0, OK here
exitstatus=status, # might be 0, OK here
exc_info=exc_info)
# TODO(1.5):
#elif isinstance(status, (StopError, UserError)):
elif isinstance(status, StopError) or isinstance(status, UserError):
buildError = BuildError(
errstr=str(status),
status=2,
exitstatus=2,
exc_info=exc_info)
elif isinstance(status, exceptions.EnvironmentError):
# If an IOError/OSError happens, raise a BuildError.
# Report the name of the file or directory that caused the
# error, which might be different from the target being built
# (for example, failure to create the directory in which the
# target file will appear).
try: filename = status.filename
except AttributeError: filename = None
buildError = BuildError(
errstr=status.strerror,
status=status.errno,
exitstatus=2,
filename=filename,
exc_info=exc_info)
elif isinstance(status, Exception):
buildError = BuildError(
errstr='%s : %s' % (status.__class__.__name__, status),
status=2,
exitstatus=2,
exc_info=exc_info)
elif SCons.Util.is_String(status):
buildError = BuildError(
errstr=status,
status=2,
exitstatus=2)
else:
buildError = BuildError(
errstr="Error %s" % status,
status=status,
exitstatus=2)
#import sys
#sys.stderr.write("convert_to_BuildError: status %s => (errstr %s, status %s)"%(status,buildError.errstr, buildError.status))
return buildError
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Subst
SCons string substitution.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Subst.py 4720 2010/03/24 03:14:11 jars"
import re
import string
import types
import UserList
import UserString
import SCons.Errors
from SCons.Util import is_String, is_Sequence
# Indexed by the SUBST_* constants below.
_strconv = [SCons.Util.to_String_for_subst,
SCons.Util.to_String_for_subst,
SCons.Util.to_String_for_signature]
AllowableExceptions = (IndexError, NameError)
def SetAllowableExceptions(*excepts):
global AllowableExceptions
AllowableExceptions = filter(None, excepts)
def raise_exception(exception, target, s):
name = exception.__class__.__name__
msg = "%s `%s' trying to evaluate `%s'" % (name, exception, s)
if target:
raise SCons.Errors.BuildError, (target[0], msg)
else:
raise SCons.Errors.UserError, msg
class Literal:
"""A wrapper for a string. If you use this object wrapped
around a string, then it will be interpreted as literal.
When passed to the command interpreter, all special
characters will be escaped."""
def __init__(self, lstr):
self.lstr = lstr
def __str__(self):
return self.lstr
def escape(self, escape_func):
return escape_func(self.lstr)
def for_signature(self):
return self.lstr
def is_literal(self):
return 1
class SpecialAttrWrapper:
"""This is a wrapper for what we call a 'Node special attribute.'
This is any of the attributes of a Node that we can reference from
Environment variable substitution, such as $TARGET.abspath or
$SOURCES[1].filebase. We implement the same methods as Literal
so we can handle special characters, plus a for_signature method,
such that we can return some canonical string during signature
calculation to avoid unnecessary rebuilds."""
def __init__(self, lstr, for_signature=None):
"""The for_signature parameter, if supplied, will be the
canonical string we return from for_signature(). Else
we will simply return lstr."""
self.lstr = lstr
if for_signature:
self.forsig = for_signature
else:
self.forsig = lstr
def __str__(self):
return self.lstr
def escape(self, escape_func):
return escape_func(self.lstr)
def for_signature(self):
return self.forsig
def is_literal(self):
return 1
def quote_spaces(arg):
"""Generic function for putting double quotes around any string that
has white space in it."""
if ' ' in arg or '\t' in arg:
return '"%s"' % arg
else:
return str(arg)
class CmdStringHolder(UserString.UserString):
"""This is a special class used to hold strings generated by
scons_subst() and scons_subst_list(). It defines a special method
escape(). When passed a function with an escape algorithm for a
particular platform, it will return the contained string with the
proper escape sequences inserted.
"""
def __init__(self, cmd, literal=None):
UserString.UserString.__init__(self, cmd)
self.literal = literal
def is_literal(self):
return self.literal
def escape(self, escape_func, quote_func=quote_spaces):
"""Escape the string with the supplied function. The
function is expected to take an arbitrary string, then
return it with all special characters escaped and ready
for passing to the command interpreter.
After calling this function, the next call to str() will
return the escaped string.
"""
if self.is_literal():
return escape_func(self.data)
elif ' ' in self.data or '\t' in self.data:
return quote_func(self.data)
else:
return self.data
def escape_list(list, escape_func):
"""Escape a list of arguments by running the specified escape_func
on every object in the list that has an escape() method."""
def escape(obj, escape_func=escape_func):
try:
e = obj.escape
except AttributeError:
return obj
else:
return e(escape_func)
return map(escape, list)
class NLWrapper:
"""A wrapper class that delays turning a list of sources or targets
into a NodeList until it's needed. The specified function supplied
when the object is initialized is responsible for turning raw nodes
into proxies that implement the special attributes like .abspath,
.source, etc. This way, we avoid creating those proxies just
"in case" someone is going to use $TARGET or the like, and only
go through the trouble if we really have to.
In practice, this might be a wash performance-wise, but it's a little
cleaner conceptually...
"""
def __init__(self, list, func):
self.list = list
self.func = func
def _return_nodelist(self):
return self.nodelist
def _gen_nodelist(self):
list = self.list
if list is None:
list = []
elif not is_Sequence(list):
list = [list]
# The map(self.func) call is what actually turns
# a list into appropriate proxies.
self.nodelist = SCons.Util.NodeList(map(self.func, list))
self._create_nodelist = self._return_nodelist
return self.nodelist
_create_nodelist = _gen_nodelist
class Targets_or_Sources(UserList.UserList):
"""A class that implements $TARGETS or $SOURCES expansions by in turn
wrapping a NLWrapper. This class handles the different methods used
to access the list, calling the NLWrapper to create proxies on demand.
Note that we subclass UserList.UserList purely so that the
is_Sequence() function will identify an object of this class as
a list during variable expansion. We're not really using any
UserList.UserList methods in practice.
"""
def __init__(self, nl):
self.nl = nl
def __getattr__(self, attr):
nl = self.nl._create_nodelist()
return getattr(nl, attr)
def __getitem__(self, i):
nl = self.nl._create_nodelist()
return nl[i]
def __getslice__(self, i, j):
nl = self.nl._create_nodelist()
i = max(i, 0); j = max(j, 0)
return nl[i:j]
def __str__(self):
nl = self.nl._create_nodelist()
return str(nl)
def __repr__(self):
nl = self.nl._create_nodelist()
return repr(nl)
class Target_or_Source:
"""A class that implements $TARGET or $SOURCE expansions by in turn
wrapping a NLWrapper. This class handles the different methods used
to access an individual proxy Node, calling the NLWrapper to create
a proxy on demand.
"""
def __init__(self, nl):
self.nl = nl
def __getattr__(self, attr):
nl = self.nl._create_nodelist()
try:
nl0 = nl[0]
except IndexError:
# If there is nothing in the list, then we have no attributes to
# pass through, so raise AttributeError for everything.
raise AttributeError, "NodeList has no attribute: %s" % attr
return getattr(nl0, attr)
def __str__(self):
nl = self.nl._create_nodelist()
if nl:
return str(nl[0])
return ''
def __repr__(self):
nl = self.nl._create_nodelist()
if nl:
return repr(nl[0])
return ''
class NullNodeList(SCons.Util.NullSeq):
def __call__(self, *args, **kwargs): return ''
def __str__(self): return ''
# TODO(1.5): unneeded after new-style classes introduce iterators
def __getitem__(self, i):
raise IndexError
NullNodesList = NullNodeList()
def subst_dict(target, source):
"""Create a dictionary for substitution of special
construction variables.
This translates the following special arguments:
target - the target (object or array of objects),
used to generate the TARGET and TARGETS
construction variables
source - the source (object or array of objects),
used to generate the SOURCES and SOURCE
construction variables
"""
dict = {}
if target:
def get_tgt_subst_proxy(thing):
try:
subst_proxy = thing.get_subst_proxy()
except AttributeError:
subst_proxy = thing # probably a string, just return it
return subst_proxy
tnl = NLWrapper(target, get_tgt_subst_proxy)
dict['TARGETS'] = Targets_or_Sources(tnl)
dict['TARGET'] = Target_or_Source(tnl)
# This is a total cheat, but hopefully this dictionary goes
# away soon anyway. We just let these expand to $TARGETS
# because that's "good enough" for the use of ToolSurrogates
# (see test/ToolSurrogate.py) to generate documentation.
dict['CHANGED_TARGETS'] = '$TARGETS'
dict['UNCHANGED_TARGETS'] = '$TARGETS'
else:
dict['TARGETS'] = NullNodesList
dict['TARGET'] = NullNodesList
if source:
def get_src_subst_proxy(node):
try:
rfile = node.rfile
except AttributeError:
pass
else:
node = rfile()
try:
return node.get_subst_proxy()
except AttributeError:
return node # probably a String, just return it
snl = NLWrapper(source, get_src_subst_proxy)
dict['SOURCES'] = Targets_or_Sources(snl)
dict['SOURCE'] = Target_or_Source(snl)
# This is a total cheat, but hopefully this dictionary goes
# away soon anyway. We just let these expand to $TARGETS
# because that's "good enough" for the use of ToolSurrogates
# (see test/ToolSurrogate.py) to generate documentation.
dict['CHANGED_SOURCES'] = '$SOURCES'
dict['UNCHANGED_SOURCES'] = '$SOURCES'
else:
dict['SOURCES'] = NullNodesList
dict['SOURCE'] = NullNodesList
return dict
# Constants for the "mode" parameter to scons_subst_list() and
# scons_subst(). SUBST_RAW gives the raw command line. SUBST_CMD
# gives a command line suitable for passing to a shell. SUBST_SIG
# gives a command line appropriate for calculating the signature
# of a command line...if this changes, we should rebuild.
SUBST_CMD = 0
SUBST_RAW = 1
SUBST_SIG = 2
_rm = re.compile(r'\$[()]')
_remove = re.compile(r'\$\([^\$]*(\$[^\)][^\$]*)*\$\)')
# Indexed by the SUBST_* constants above.
_regex_remove = [ _rm, None, _remove ]
def _rm_list(list):
#return [ l for l in list if not l in ('$(', '$)') ]
return filter(lambda l: not l in ('$(', '$)'), list)
def _remove_list(list):
result = []
do_append = result.append
for l in list:
if l == '$(':
do_append = lambda x: None
elif l == '$)':
do_append = result.append
else:
do_append(l)
return result
# Indexed by the SUBST_* constants above.
_list_remove = [ _rm_list, None, _remove_list ]
# Regular expressions for splitting strings and handling substitutions,
# for use by the scons_subst() and scons_subst_list() functions:
#
# The first expression compiled matches all of the $-introduced tokens
# that we need to process in some way, and is used for substitutions.
# The expressions it matches are:
#
# "$$"
# "$("
# "$)"
# "$variable" [must begin with alphabetic or underscore]
# "${any stuff}"
#
# The second expression compiled is used for splitting strings into tokens
# to be processed, and it matches all of the tokens listed above, plus
# the following that affect how arguments do or don't get joined together:
#
# " " [white space]
# "non-white-space" [without any dollar signs]
# "$" [single dollar sign]
#
_dollar_exps_str = r'\$[\$\(\)]|\$[_a-zA-Z][\.\w]*|\${[^}]*}'
_dollar_exps = re.compile(r'(%s)' % _dollar_exps_str)
_separate_args = re.compile(r'(%s|\s+|[^\s\$]+|\$)' % _dollar_exps_str)
# This regular expression is used to replace strings of multiple white
# space characters in the string result from the scons_subst() function.
_space_sep = re.compile(r'[\t ]+(?![^{]*})')
def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
"""Expand a string or list containing construction variable
substitutions.
This is the work-horse function for substitutions in file names
and the like. The companion scons_subst_list() function (below)
handles separating command lines into lists of arguments, so see
that function if that's what you're looking for.
"""
if type(strSubst) == types.StringType and string.find(strSubst, '$') < 0:
return strSubst
class StringSubber:
"""A class to construct the results of a scons_subst() call.
This binds a specific construction environment, mode, target and
source with two methods (substitute() and expand()) that handle
the expansion.
"""
def __init__(self, env, mode, conv, gvars):
self.env = env
self.mode = mode
self.conv = conv
self.gvars = gvars
def expand(self, s, lvars):
"""Expand a single "token" as necessary, returning an
appropriate string containing the expansion.
This handles expanding different types of things (strings,
lists, callables) appropriately. It calls the wrapper
substitute() method to re-expand things as necessary, so that
the results of expansions of side-by-side strings still get
re-evaluated separately, not smushed together.
"""
if is_String(s):
try:
s0, s1 = s[:2]
except (IndexError, ValueError):
return s
if s0 != '$':
return s
if s1 == '$':
return '$'
elif s1 in '()':
return s
else:
key = s[1:]
if key[0] == '{' or string.find(key, '.') >= 0:
if key[0] == '{':
key = key[1:-1]
try:
s = eval(key, self.gvars, lvars)
except KeyboardInterrupt:
raise
except Exception, e:
if e.__class__ in AllowableExceptions:
return ''
raise_exception(e, lvars['TARGETS'], s)
else:
if lvars.has_key(key):
s = lvars[key]
elif self.gvars.has_key(key):
s = self.gvars[key]
elif not NameError in AllowableExceptions:
raise_exception(NameError(key), lvars['TARGETS'], s)
else:
return ''
# Before re-expanding the result, handle
# recursive expansion by copying the local
# variable dictionary and overwriting a null
# string for the value of the variable name
# we just expanded.
#
# This could potentially be optimized by only
# copying lvars when s contains more expansions,
# but lvars is usually supposed to be pretty
# small, and deeply nested variable expansions
# are probably more the exception than the norm,
# so it should be tolerable for now.
lv = lvars.copy()
var = string.split(key, '.')[0]
lv[var] = ''
return self.substitute(s, lv)
elif is_Sequence(s):
def func(l, conv=self.conv, substitute=self.substitute, lvars=lvars):
return conv(substitute(l, lvars))
return map(func, s)
elif callable(s):
try:
s = s(target=lvars['TARGETS'],
source=lvars['SOURCES'],
env=self.env,
for_signature=(self.mode != SUBST_CMD))
except TypeError:
# This probably indicates that it's a callable
# object that doesn't match our calling arguments
# (like an Action).
if self.mode == SUBST_RAW:
return s
s = self.conv(s)
return self.substitute(s, lvars)
elif s is None:
return ''
else:
return s
def substitute(self, args, lvars):
"""Substitute expansions in an argument or list of arguments.
This serves as a wrapper for splitting up a string into
separate tokens.
"""
if is_String(args) and not isinstance(args, CmdStringHolder):
args = str(args) # In case it's a UserString.
try:
def sub_match(match, conv=self.conv, expand=self.expand, lvars=lvars):
return conv(expand(match.group(1), lvars))
result = _dollar_exps.sub(sub_match, args)
except TypeError:
# If the internal conversion routine doesn't return
# strings (it could be overridden to return Nodes, for
# example), then the 1.5.2 re module will throw this
# exception. Back off to a slower, general-purpose
# algorithm that works for all data types.
args = _separate_args.findall(args)
result = []
for a in args:
result.append(self.conv(self.expand(a, lvars)))
if len(result) == 1:
result = result[0]
else:
result = string.join(map(str, result), '')
return result
else:
return self.expand(args, lvars)
if conv is None:
conv = _strconv[mode]
# Doing this every time is a bit of a waste, since the Executor
# has typically already populated the OverrideEnvironment with
# $TARGET/$SOURCE variables. We're keeping this (for now), though,
# because it supports existing behavior that allows us to call
# an Action directly with an arbitrary target+source pair, which
# we use in Tool/tex.py to handle calling $BIBTEX when necessary.
# If we dropped that behavior (or found another way to cover it),
# we could get rid of this call completely and just rely on the
# Executor setting the variables.
if not lvars.has_key('TARGET'):
d = subst_dict(target, source)
if d:
lvars = lvars.copy()
lvars.update(d)
# We're (most likely) going to eval() things. If Python doesn't
# find a __builtins__ value in the global dictionary used for eval(),
# it copies the current global values for you. Avoid this by
# setting it explicitly and then deleting, so we don't pollute the
# construction environment Dictionary(ies) that are typically used
# for expansion.
gvars['__builtins__'] = __builtins__
ss = StringSubber(env, mode, conv, gvars)
result = ss.substitute(strSubst, lvars)
try:
del gvars['__builtins__']
except KeyError:
pass
if is_String(result):
# Remove $(-$) pairs and any stuff in between,
# if that's appropriate.
remove = _regex_remove[mode]
if remove:
result = remove.sub('', result)
if mode != SUBST_RAW:
# Compress strings of white space characters into
# a single space.
result = string.strip(_space_sep.sub(' ', result))
elif is_Sequence(result):
remove = _list_remove[mode]
if remove:
result = remove(result)
return result
#Subst_List_Strings = {}
def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
"""Substitute construction variables in a string (or list or other
object) and separate the arguments into a command list.
The companion scons_subst() function (above) handles basic
substitutions within strings, so see that function instead
if that's what you're looking for.
"""
# try:
# Subst_List_Strings[strSubst] = Subst_List_Strings[strSubst] + 1
# except KeyError:
# Subst_List_Strings[strSubst] = 1
# import SCons.Debug
# SCons.Debug.caller_trace(1)
class ListSubber(UserList.UserList):
"""A class to construct the results of a scons_subst_list() call.
Like StringSubber, this class binds a specific construction
environment, mode, target and source with two methods
(substitute() and expand()) that handle the expansion.
In addition, however, this class is used to track the state of
the result(s) we're gathering so we can do the appropriate thing
whenever we have to append another word to the result--start a new
line, start a new word, append to the current word, etc. We do
this by setting the "append" attribute to the right method so
that our wrapper methods only need ever call ListSubber.append(),
and the rest of the object takes care of doing the right thing
internally.
"""
def __init__(self, env, mode, conv, gvars):
UserList.UserList.__init__(self, [])
self.env = env
self.mode = mode
self.conv = conv
self.gvars = gvars
if self.mode == SUBST_RAW:
self.add_strip = lambda x, s=self: s.append(x)
else:
self.add_strip = lambda x, s=self: None
self.in_strip = None
self.next_line()
def expand(self, s, lvars, within_list):
"""Expand a single "token" as necessary, appending the
expansion to the current result.
This handles expanding different types of things (strings,
lists, callables) appropriately. It calls the wrapper
substitute() method to re-expand things as necessary, so that
the results of expansions of side-by-side strings still get
re-evaluated separately, not smushed together.
"""
if is_String(s):
try:
s0, s1 = s[:2]
except (IndexError, ValueError):
self.append(s)
return
if s0 != '$':
self.append(s)
return
if s1 == '$':
self.append('$')
elif s1 == '(':
self.open_strip('$(')
elif s1 == ')':
self.close_strip('$)')
else:
key = s[1:]
if key[0] == '{' or string.find(key, '.') >= 0:
if key[0] == '{':
key = key[1:-1]
try:
s = eval(key, self.gvars, lvars)
except KeyboardInterrupt:
raise
except Exception, e:
if e.__class__ in AllowableExceptions:
return
raise_exception(e, lvars['TARGETS'], s)
else:
if lvars.has_key(key):
s = lvars[key]
elif self.gvars.has_key(key):
s = self.gvars[key]
elif not NameError in AllowableExceptions:
raise_exception(NameError(), lvars['TARGETS'], s)
else:
return
# Before re-expanding the result, handle
# recursive expansion by copying the local
# variable dictionary and overwriting a null
# string for the value of the variable name
# we just expanded.
lv = lvars.copy()
var = string.split(key, '.')[0]
lv[var] = ''
self.substitute(s, lv, 0)
self.this_word()
elif is_Sequence(s):
for a in s:
self.substitute(a, lvars, 1)
self.next_word()
elif callable(s):
try:
s = s(target=lvars['TARGETS'],
source=lvars['SOURCES'],
env=self.env,
for_signature=(self.mode != SUBST_CMD))
except TypeError:
# This probably indicates that it's a callable
# object that doesn't match our calling arguments
# (like an Action).
if self.mode == SUBST_RAW:
self.append(s)
return
s = self.conv(s)
self.substitute(s, lvars, within_list)
elif s is None:
self.this_word()
else:
self.append(s)
def substitute(self, args, lvars, within_list):
"""Substitute expansions in an argument or list of arguments.
This serves as a wrapper for splitting up a string into
separate tokens.
"""
if is_String(args) and not isinstance(args, CmdStringHolder):
args = str(args) # In case it's a UserString.
args = _separate_args.findall(args)
for a in args:
if a[0] in ' \t\n\r\f\v':
if '\n' in a:
self.next_line()
elif within_list:
self.append(a)
else:
self.next_word()
else:
self.expand(a, lvars, within_list)
else:
self.expand(args, lvars, within_list)
def next_line(self):
"""Arrange for the next word to start a new line. This
is like starting a new word, except that we have to append
another line to the result."""
UserList.UserList.append(self, [])
self.next_word()
def this_word(self):
"""Arrange for the next word to append to the end of the
current last word in the result."""
self.append = self.add_to_current_word
def next_word(self):
"""Arrange for the next word to start a new word."""
self.append = self.add_new_word
def add_to_current_word(self, x):
"""Append the string x to the end of the current last word
in the result. If that is not possible, then just add
it as a new word. Make sure the entire concatenated string
inherits the object attributes of x (in particular, the
escape function) by wrapping it as CmdStringHolder."""
if not self.in_strip or self.mode != SUBST_SIG:
try:
current_word = self[-1][-1]
except IndexError:
self.add_new_word(x)
else:
# All right, this is a hack and it should probably
# be refactored out of existence in the future.
# The issue is that we want to smoosh words together
# and make one file name that gets escaped if
# we're expanding something like foo$EXTENSION,
# but we don't want to smoosh them together if
# it's something like >$TARGET, because then we'll
# treat the '>' like it's part of the file name.
# So for now, just hard-code looking for the special
# command-line redirection characters...
try:
last_char = str(current_word)[-1]
except IndexError:
last_char = '\0'
if last_char in '<>|':
self.add_new_word(x)
else:
y = current_word + x
# We used to treat a word appended to a literal
# as a literal itself, but this caused problems
# with interpreting quotes around space-separated
# targets on command lines. Removing this makes
# none of the "substantive" end-to-end tests fail,
# so we'll take this out but leave it commented
# for now in case there's a problem not covered
# by the test cases and we need to resurrect this.
#literal1 = self.literal(self[-1][-1])
#literal2 = self.literal(x)
y = self.conv(y)
if is_String(y):
#y = CmdStringHolder(y, literal1 or literal2)
y = CmdStringHolder(y, None)
self[-1][-1] = y
def add_new_word(self, x):
if not self.in_strip or self.mode != SUBST_SIG:
literal = self.literal(x)
x = self.conv(x)
if is_String(x):
x = CmdStringHolder(x, literal)
self[-1].append(x)
self.append = self.add_to_current_word
def literal(self, x):
try:
l = x.is_literal
except AttributeError:
return None
else:
return l()
def open_strip(self, x):
"""Handle the "open strip" $( token."""
self.add_strip(x)
self.in_strip = 1
def close_strip(self, x):
"""Handle the "close strip" $) token."""
self.add_strip(x)
self.in_strip = None
if conv is None:
conv = _strconv[mode]
# Doing this every time is a bit of a waste, since the Executor
# has typically already populated the OverrideEnvironment with
# $TARGET/$SOURCE variables. We're keeping this (for now), though,
# because it supports existing behavior that allows us to call
# an Action directly with an arbitrary target+source pair, which
# we use in Tool/tex.py to handle calling $BIBTEX when necessary.
# If we dropped that behavior (or found another way to cover it),
# we could get rid of this call completely and just rely on the
# Executor setting the variables.
if not lvars.has_key('TARGET'):
d = subst_dict(target, source)
if d:
lvars = lvars.copy()
lvars.update(d)
# We're (most likely) going to eval() things. If Python doesn't
# find a __builtins__ value in the global dictionary used for eval(),
# it copies the current global values for you. Avoid this by
# setting it explicitly and then deleting, so we don't pollute the
# construction environment Dictionary(ies) that are typically used
# for expansion.
gvars['__builtins__'] = __builtins__
ls = ListSubber(env, mode, conv, gvars)
ls.substitute(strSubst, lvars, 0)
try:
del gvars['__builtins__']
except KeyError:
pass
return ls.data
def scons_subst_once(strSubst, env, key):
"""Perform single (non-recursive) substitution of a single
construction variable keyword.
This is used when setting a variable when copying or overriding values
in an Environment. We want to capture (expand) the old value before
we override it, so people can do things like:
env2 = env.Clone(CCFLAGS = '$CCFLAGS -g')
We do this with some straightforward, brute-force code here...
"""
if type(strSubst) == types.StringType and string.find(strSubst, '$') < 0:
return strSubst
matchlist = ['$' + key, '${' + key + '}']
val = env.get(key, '')
def sub_match(match, val=val, matchlist=matchlist):
a = match.group(1)
if a in matchlist:
a = val
if is_Sequence(a):
return string.join(map(str, a))
else:
return str(a)
if is_Sequence(strSubst):
result = []
for arg in strSubst:
if is_String(arg):
if arg in matchlist:
arg = val
if is_Sequence(arg):
result.extend(arg)
else:
result.append(arg)
else:
result.append(_dollar_exps.sub(sub_match, arg))
else:
result.append(arg)
return result
elif is_String(strSubst):
return _dollar_exps.sub(sub_match, strSubst)
else:
return strSubst
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""scons.Node.FS
File system nodes.
These Nodes represent the canonical external objects that people think
of when they think of building software: files and directories.
This holds a "default_fs" variable that should be initialized with an FS
that can be used by scripts or modules looking for the canonical default.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Node/FS.py 4720 2010/03/24 03:14:11 jars"
from itertools import izip
import cStringIO
import fnmatch
import os
import os.path
import re
import shutil
import stat
import string
import sys
import time
try:
import codecs
except ImportError:
pass
else:
# TODO(2.2): Remove when 2.3 becomes the minimal supported version.
try:
codecs.BOM_UTF8
except AttributeError:
codecs.BOM_UTF8 = '\xef\xbb\xbf'
try:
codecs.BOM_UTF16_LE
codecs.BOM_UTF16_BE
except AttributeError:
codecs.BOM_UTF16_LE = '\xff\xfe'
codecs.BOM_UTF16_BE = '\xfe\xff'
# Provide a wrapper function to handle decoding differences in
# different versions of Python. Normally, we'd try to do this in the
# compat layer (and maybe it still makes sense to move there?) but
# that doesn't provide a way to supply the string class used in
# pre-2.3 Python versions with a .decode() method that all strings
# naturally have. Plus, the 2.[01] encodings behave differently
# enough that we have to settle for a lowest-common-denominator
# wrapper approach.
#
# Note that the 2.[012] implementations below may be inefficient
# because they perform an explicit look up of the encoding for every
# decode, but they're old enough (and we want to stop supporting
# them soon enough) that it's not worth complicating the interface.
# Think of it as additional incentive for people to upgrade...
try:
''.decode
except AttributeError:
# 2.0 through 2.2: strings have no .decode() method
try:
codecs.lookup('ascii').decode
except AttributeError:
# 2.0 and 2.1: encodings are a tuple of functions, and the
# decode() function returns a (result, length) tuple.
def my_decode(contents, encoding):
return codecs.lookup(encoding)[1](contents)[0]
else:
# 2.2: encodings are an object with methods, and the
# .decode() method returns just the decoded bytes.
def my_decode(contents, encoding):
return codecs.lookup(encoding).decode(contents)
else:
# 2.3 or later: use the .decode() string method
def my_decode(contents, encoding):
return contents.decode(encoding)
import SCons.Action
from SCons.Debug import logInstanceCreation
import SCons.Errors
import SCons.Memoize
import SCons.Node
import SCons.Node.Alias
import SCons.Subst
import SCons.Util
import SCons.Warnings
from SCons.Debug import Trace
do_store_info = True
class EntryProxyAttributeError(AttributeError):
"""
An AttributeError subclass for recording and displaying the name
of the underlying Entry involved in an AttributeError exception.
"""
def __init__(self, entry_proxy, attribute):
AttributeError.__init__(self)
self.entry_proxy = entry_proxy
self.attribute = attribute
def __str__(self):
entry = self.entry_proxy.get()
fmt = "%s instance %s has no attribute %s"
return fmt % (entry.__class__.__name__,
repr(entry.name),
repr(self.attribute))
# The max_drift value: by default, use a cached signature value for
# any file that's been untouched for more than two days.
default_max_drift = 2*24*60*60
#
# We stringify these file system Nodes a lot. Turning a file system Node
# into a string is non-trivial, because the final string representation
# can depend on a lot of factors: whether it's a derived target or not,
# whether it's linked to a repository or source directory, and whether
# there's duplication going on. The normal technique for optimizing
# calculations like this is to memoize (cache) the string value, so you
# only have to do the calculation once.
#
# A number of the above factors, however, can be set after we've already
# been asked to return a string for a Node, because a Repository() or
# VariantDir() call or the like may not occur until later in SConscript
# files. So this variable controls whether we bother trying to save
# string values for Nodes. The wrapper interface can set this whenever
# they're done mucking with Repository and VariantDir and the other stuff,
# to let this module know it can start returning saved string values
# for Nodes.
#
Save_Strings = None
def save_strings(val):
global Save_Strings
Save_Strings = val
#
# Avoid unnecessary function calls by recording a Boolean value that
# tells us whether or not os.path.splitdrive() actually does anything
# on this system, and therefore whether we need to bother calling it
# when looking up path names in various methods below.
#
do_splitdrive = None
def initialize_do_splitdrive():
global do_splitdrive
drive, path = os.path.splitdrive('X:/foo')
do_splitdrive = not not drive
initialize_do_splitdrive()
#
needs_normpath_check = None
def initialize_normpath_check():
"""
Initialize the normpath_check regular expression.
This function is used by the unit tests to re-initialize the pattern
when testing for behavior with different values of os.sep.
"""
global needs_normpath_check
if os.sep == '/':
pattern = r'.*/|\.$|\.\.$'
else:
pattern = r'.*[/%s]|\.$|\.\.$' % re.escape(os.sep)
needs_normpath_check = re.compile(pattern)
initialize_normpath_check()
#
# SCons.Action objects for interacting with the outside world.
#
# The Node.FS methods in this module should use these actions to
# create and/or remove files and directories; they should *not* use
# os.{link,symlink,unlink,mkdir}(), etc., directly.
#
# Using these SCons.Action objects ensures that descriptions of these
# external activities are properly displayed, that the displays are
# suppressed when the -s (silent) option is used, and (most importantly)
# the actions are disabled when the the -n option is used, in which case
# there should be *no* changes to the external file system(s)...
#
if hasattr(os, 'link'):
def _hardlink_func(fs, src, dst):
# If the source is a symlink, we can't just hard-link to it
# because a relative symlink may point somewhere completely
# different. We must disambiguate the symlink and then
# hard-link the final destination file.
while fs.islink(src):
link = fs.readlink(src)
if not os.path.isabs(link):
src = link
else:
src = os.path.join(os.path.dirname(src), link)
fs.link(src, dst)
else:
_hardlink_func = None
if hasattr(os, 'symlink'):
def _softlink_func(fs, src, dst):
fs.symlink(src, dst)
else:
_softlink_func = None
def _copy_func(fs, src, dest):
shutil.copy2(src, dest)
st = fs.stat(src)
fs.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)
Valid_Duplicates = ['hard-soft-copy', 'soft-hard-copy',
'hard-copy', 'soft-copy', 'copy']
Link_Funcs = [] # contains the callables of the specified duplication style
def set_duplicate(duplicate):
# Fill in the Link_Funcs list according to the argument
# (discarding those not available on the platform).
# Set up the dictionary that maps the argument names to the
# underlying implementations. We do this inside this function,
# not in the top-level module code, so that we can remap os.link
# and os.symlink for testing purposes.
link_dict = {
'hard' : _hardlink_func,
'soft' : _softlink_func,
'copy' : _copy_func
}
if not duplicate in Valid_Duplicates:
raise SCons.Errors.InternalError, ("The argument of set_duplicate "
"should be in Valid_Duplicates")
global Link_Funcs
Link_Funcs = []
for func in string.split(duplicate,'-'):
if link_dict[func]:
Link_Funcs.append(link_dict[func])
def LinkFunc(target, source, env):
# Relative paths cause problems with symbolic links, so
# we use absolute paths, which may be a problem for people
# who want to move their soft-linked src-trees around. Those
# people should use the 'hard-copy' mode, softlinks cannot be
# used for that; at least I have no idea how ...
src = source[0].abspath
dest = target[0].abspath
dir, file = os.path.split(dest)
if dir and not target[0].fs.isdir(dir):
os.makedirs(dir)
if not Link_Funcs:
# Set a default order of link functions.
set_duplicate('hard-soft-copy')
fs = source[0].fs
# Now link the files with the previously specified order.
for func in Link_Funcs:
try:
func(fs, src, dest)
break
except (IOError, OSError):
# An OSError indicates something happened like a permissions
# problem or an attempt to symlink across file-system
# boundaries. An IOError indicates something like the file
# not existing. In either case, keeping trying additional
# functions in the list and only raise an error if the last
# one failed.
if func == Link_Funcs[-1]:
# exception of the last link method (copy) are fatal
raise
return 0
Link = SCons.Action.Action(LinkFunc, None)
def LocalString(target, source, env):
return 'Local copy of %s from %s' % (target[0], source[0])
LocalCopy = SCons.Action.Action(LinkFunc, LocalString)
def UnlinkFunc(target, source, env):
t = target[0]
t.fs.unlink(t.abspath)
return 0
Unlink = SCons.Action.Action(UnlinkFunc, None)
def MkdirFunc(target, source, env):
t = target[0]
if not t.exists():
t.fs.mkdir(t.abspath)
return 0
Mkdir = SCons.Action.Action(MkdirFunc, None, presub=None)
MkdirBuilder = None
def get_MkdirBuilder():
global MkdirBuilder
if MkdirBuilder is None:
import SCons.Builder
import SCons.Defaults
# "env" will get filled in by Executor.get_build_env()
# calling SCons.Defaults.DefaultEnvironment() when necessary.
MkdirBuilder = SCons.Builder.Builder(action = Mkdir,
env = None,
explain = None,
is_explicit = None,
target_scanner = SCons.Defaults.DirEntryScanner,
name = "MkdirBuilder")
return MkdirBuilder
class _Null:
pass
_null = _Null()
DefaultSCCSBuilder = None
DefaultRCSBuilder = None
def get_DefaultSCCSBuilder():
global DefaultSCCSBuilder
if DefaultSCCSBuilder is None:
import SCons.Builder
# "env" will get filled in by Executor.get_build_env()
# calling SCons.Defaults.DefaultEnvironment() when necessary.
act = SCons.Action.Action('$SCCSCOM', '$SCCSCOMSTR')
DefaultSCCSBuilder = SCons.Builder.Builder(action = act,
env = None,
name = "DefaultSCCSBuilder")
return DefaultSCCSBuilder
def get_DefaultRCSBuilder():
global DefaultRCSBuilder
if DefaultRCSBuilder is None:
import SCons.Builder
# "env" will get filled in by Executor.get_build_env()
# calling SCons.Defaults.DefaultEnvironment() when necessary.
act = SCons.Action.Action('$RCS_COCOM', '$RCS_COCOMSTR')
DefaultRCSBuilder = SCons.Builder.Builder(action = act,
env = None,
name = "DefaultRCSBuilder")
return DefaultRCSBuilder
# Cygwin's os.path.normcase pretends it's on a case-sensitive filesystem.
_is_cygwin = sys.platform == "cygwin"
if os.path.normcase("TeSt") == os.path.normpath("TeSt") and not _is_cygwin:
def _my_normcase(x):
return x
else:
def _my_normcase(x):
return string.upper(x)
class DiskChecker:
def __init__(self, type, do, ignore):
self.type = type
self.do = do
self.ignore = ignore
self.set_do()
def set_do(self):
self.__call__ = self.do
def set_ignore(self):
self.__call__ = self.ignore
def set(self, list):
if self.type in list:
self.set_do()
else:
self.set_ignore()
def do_diskcheck_match(node, predicate, errorfmt):
result = predicate()
try:
# If calling the predicate() cached a None value from stat(),
# remove it so it doesn't interfere with later attempts to
# build this Node as we walk the DAG. (This isn't a great way
# to do this, we're reaching into an interface that doesn't
# really belong to us, but it's all about performance, so
# for now we'll just document the dependency...)
if node._memo['stat'] is None:
del node._memo['stat']
except (AttributeError, KeyError):
pass
if result:
raise TypeError, errorfmt % node.abspath
def ignore_diskcheck_match(node, predicate, errorfmt):
pass
def do_diskcheck_rcs(node, name):
try:
rcs_dir = node.rcs_dir
except AttributeError:
if node.entry_exists_on_disk('RCS'):
rcs_dir = node.Dir('RCS')
else:
rcs_dir = None
node.rcs_dir = rcs_dir
if rcs_dir:
return rcs_dir.entry_exists_on_disk(name+',v')
return None
def ignore_diskcheck_rcs(node, name):
return None
def do_diskcheck_sccs(node, name):
try:
sccs_dir = node.sccs_dir
except AttributeError:
if node.entry_exists_on_disk('SCCS'):
sccs_dir = node.Dir('SCCS')
else:
sccs_dir = None
node.sccs_dir = sccs_dir
if sccs_dir:
return sccs_dir.entry_exists_on_disk('s.'+name)
return None
def ignore_diskcheck_sccs(node, name):
return None
diskcheck_match = DiskChecker('match', do_diskcheck_match, ignore_diskcheck_match)
diskcheck_rcs = DiskChecker('rcs', do_diskcheck_rcs, ignore_diskcheck_rcs)
diskcheck_sccs = DiskChecker('sccs', do_diskcheck_sccs, ignore_diskcheck_sccs)
diskcheckers = [
diskcheck_match,
diskcheck_rcs,
diskcheck_sccs,
]
def set_diskcheck(list):
for dc in diskcheckers:
dc.set(list)
def diskcheck_types():
return map(lambda dc: dc.type, diskcheckers)
class EntryProxy(SCons.Util.Proxy):
def __get_abspath(self):
entry = self.get()
return SCons.Subst.SpecialAttrWrapper(entry.get_abspath(),
entry.name + "_abspath")
def __get_filebase(self):
name = self.get().name
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(name)[0],
name + "_filebase")
def __get_suffix(self):
name = self.get().name
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(name)[1],
name + "_suffix")
def __get_file(self):
name = self.get().name
return SCons.Subst.SpecialAttrWrapper(name, name + "_file")
def __get_base_path(self):
"""Return the file's directory and file name, with the
suffix stripped."""
entry = self.get()
return SCons.Subst.SpecialAttrWrapper(SCons.Util.splitext(entry.get_path())[0],
entry.name + "_base")
def __get_posix_path(self):
"""Return the path with / as the path separator,
regardless of platform."""
if os.sep == '/':
return self
else:
entry = self.get()
r = string.replace(entry.get_path(), os.sep, '/')
return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_posix")
def __get_windows_path(self):
"""Return the path with \ as the path separator,
regardless of platform."""
if os.sep == '\\':
return self
else:
entry = self.get()
r = string.replace(entry.get_path(), os.sep, '\\')
return SCons.Subst.SpecialAttrWrapper(r, entry.name + "_windows")
def __get_srcnode(self):
return EntryProxy(self.get().srcnode())
def __get_srcdir(self):
"""Returns the directory containing the source node linked to this
node via VariantDir(), or the directory of this node if not linked."""
return EntryProxy(self.get().srcnode().dir)
def __get_rsrcnode(self):
return EntryProxy(self.get().srcnode().rfile())
def __get_rsrcdir(self):
"""Returns the directory containing the source node linked to this
node via VariantDir(), or the directory of this node if not linked."""
return EntryProxy(self.get().srcnode().rfile().dir)
def __get_dir(self):
return EntryProxy(self.get().dir)
dictSpecialAttrs = { "base" : __get_base_path,
"posix" : __get_posix_path,
"windows" : __get_windows_path,
"win32" : __get_windows_path,
"srcpath" : __get_srcnode,
"srcdir" : __get_srcdir,
"dir" : __get_dir,
"abspath" : __get_abspath,
"filebase" : __get_filebase,
"suffix" : __get_suffix,
"file" : __get_file,
"rsrcpath" : __get_rsrcnode,
"rsrcdir" : __get_rsrcdir,
}
def __getattr__(self, name):
# This is how we implement the "special" attributes
# such as base, posix, srcdir, etc.
try:
attr_function = self.dictSpecialAttrs[name]
except KeyError:
try:
attr = SCons.Util.Proxy.__getattr__(self, name)
except AttributeError, e:
# Raise our own AttributeError subclass with an
# overridden __str__() method that identifies the
# name of the entry that caused the exception.
raise EntryProxyAttributeError(self, name)
return attr
else:
return attr_function(self)
class Base(SCons.Node.Node):
"""A generic class for file system entries. This class is for
when we don't know yet whether the entry being looked up is a file
or a directory. Instances of this class can morph into either
Dir or File objects by a later, more precise lookup.
Note: this class does not define __cmp__ and __hash__ for
efficiency reasons. SCons does a lot of comparing of
Node.FS.{Base,Entry,File,Dir} objects, so those operations must be
as fast as possible, which means we want to use Python's built-in
object identity comparisons.
"""
memoizer_counters = []
def __init__(self, name, directory, fs):
"""Initialize a generic Node.FS.Base object.
Call the superclass initialization, take care of setting up
our relative and absolute paths, identify our parent
directory, and indicate that this node should use
signatures."""
if __debug__: logInstanceCreation(self, 'Node.FS.Base')
SCons.Node.Node.__init__(self)
# Filenames and paths are probably reused and are intern'ed to
# save some memory.
self.name = SCons.Util.silent_intern(name)
self.suffix = SCons.Util.silent_intern(SCons.Util.splitext(name)[1])
self.fs = fs
assert directory, "A directory must be provided"
self.abspath = SCons.Util.silent_intern(directory.entry_abspath(name))
self.labspath = SCons.Util.silent_intern(directory.entry_labspath(name))
if directory.path == '.':
self.path = SCons.Util.silent_intern(name)
else:
self.path = SCons.Util.silent_intern(directory.entry_path(name))
if directory.tpath == '.':
self.tpath = SCons.Util.silent_intern(name)
else:
self.tpath = SCons.Util.silent_intern(directory.entry_tpath(name))
self.path_elements = directory.path_elements + [self]
self.dir = directory
self.cwd = None # will hold the SConscript directory for target nodes
self.duplicate = directory.duplicate
def str_for_display(self):
return '"' + self.__str__() + '"'
def must_be_same(self, klass):
"""
This node, which already existed, is being looked up as the
specified klass. Raise an exception if it isn't.
"""
if isinstance(self, klass) or klass is Entry:
return
raise TypeError, "Tried to lookup %s '%s' as a %s." %\
(self.__class__.__name__, self.path, klass.__name__)
def get_dir(self):
return self.dir
def get_suffix(self):
return self.suffix
def rfile(self):
return self
def __str__(self):
"""A Node.FS.Base object's string representation is its path
name."""
global Save_Strings
if Save_Strings:
return self._save_str()
return self._get_str()
memoizer_counters.append(SCons.Memoize.CountValue('_save_str'))
def _save_str(self):
try:
return self._memo['_save_str']
except KeyError:
pass
result = intern(self._get_str())
self._memo['_save_str'] = result
return result
def _get_str(self):
global Save_Strings
if self.duplicate or self.is_derived():
return self.get_path()
srcnode = self.srcnode()
if srcnode.stat() is None and self.stat() is not None:
result = self.get_path()
else:
result = srcnode.get_path()
if not Save_Strings:
# We're not at the point where we're saving the string string
# representations of FS Nodes (because we haven't finished
# reading the SConscript files and need to have str() return
# things relative to them). That also means we can't yet
# cache values returned (or not returned) by stat(), since
# Python code in the SConscript files might still create
# or otherwise affect the on-disk file. So get rid of the
# values that the underlying stat() method saved.
try: del self._memo['stat']
except KeyError: pass
if self is not srcnode:
try: del srcnode._memo['stat']
except KeyError: pass
return result
rstr = __str__
memoizer_counters.append(SCons.Memoize.CountValue('stat'))
def stat(self):
try: return self._memo['stat']
except KeyError: pass
try: result = self.fs.stat(self.abspath)
except os.error: result = None
self._memo['stat'] = result
return result
def exists(self):
return self.stat() is not None
def rexists(self):
return self.rfile().exists()
def getmtime(self):
st = self.stat()
if st: return st[stat.ST_MTIME]
else: return None
def getsize(self):
st = self.stat()
if st: return st[stat.ST_SIZE]
else: return None
def isdir(self):
st = self.stat()
return st is not None and stat.S_ISDIR(st[stat.ST_MODE])
def isfile(self):
st = self.stat()
return st is not None and stat.S_ISREG(st[stat.ST_MODE])
if hasattr(os, 'symlink'):
def islink(self):
try: st = self.fs.lstat(self.abspath)
except os.error: return 0
return stat.S_ISLNK(st[stat.ST_MODE])
else:
def islink(self):
return 0 # no symlinks
def is_under(self, dir):
if self is dir:
return 1
else:
return self.dir.is_under(dir)
def set_local(self):
self._local = 1
def srcnode(self):
"""If this node is in a build path, return the node
corresponding to its source file. Otherwise, return
ourself.
"""
srcdir_list = self.dir.srcdir_list()
if srcdir_list:
srcnode = srcdir_list[0].Entry(self.name)
srcnode.must_be_same(self.__class__)
return srcnode
return self
def get_path(self, dir=None):
"""Return path relative to the current working directory of the
Node.FS.Base object that owns us."""
if not dir:
dir = self.fs.getcwd()
if self == dir:
return '.'
path_elems = self.path_elements
try: i = path_elems.index(dir)
except ValueError: pass
else: path_elems = path_elems[i+1:]
path_elems = map(lambda n: n.name, path_elems)
return string.join(path_elems, os.sep)
def set_src_builder(self, builder):
"""Set the source code builder for this node."""
self.sbuilder = builder
if not self.has_builder():
self.builder_set(builder)
def src_builder(self):
"""Fetch the source code builder for this node.
If there isn't one, we cache the source code builder specified
for the directory (which in turn will cache the value from its
parent directory, and so on up to the file system root).
"""
try:
scb = self.sbuilder
except AttributeError:
scb = self.dir.src_builder()
self.sbuilder = scb
return scb
def get_abspath(self):
"""Get the absolute path of the file."""
return self.abspath
def for_signature(self):
# Return just our name. Even an absolute path would not work,
# because that can change thanks to symlinks or remapped network
# paths.
return self.name
def get_subst_proxy(self):
try:
return self._proxy
except AttributeError:
ret = EntryProxy(self)
self._proxy = ret
return ret
def target_from_source(self, prefix, suffix, splitext=SCons.Util.splitext):
"""
Generates a target entry that corresponds to this entry (usually
a source file) with the specified prefix and suffix.
Note that this method can be overridden dynamically for generated
files that need different behavior. See Tool/swig.py for
an example.
"""
return self.dir.Entry(prefix + splitext(self.name)[0] + suffix)
def _Rfindalldirs_key(self, pathlist):
return pathlist
memoizer_counters.append(SCons.Memoize.CountDict('Rfindalldirs', _Rfindalldirs_key))
def Rfindalldirs(self, pathlist):
"""
Return all of the directories for a given path list, including
corresponding "backing" directories in any repositories.
The Node lookups are relative to this Node (typically a
directory), so memoizing result saves cycles from looking
up the same path for each target in a given directory.
"""
try:
memo_dict = self._memo['Rfindalldirs']
except KeyError:
memo_dict = {}
self._memo['Rfindalldirs'] = memo_dict
else:
try:
return memo_dict[pathlist]
except KeyError:
pass
create_dir_relative_to_self = self.Dir
result = []
for path in pathlist:
if isinstance(path, SCons.Node.Node):
result.append(path)
else:
dir = create_dir_relative_to_self(path)
result.extend(dir.get_all_rdirs())
memo_dict[pathlist] = result
return result
def RDirs(self, pathlist):
"""Search for a list of directories in the Repository list."""
cwd = self.cwd or self.fs._cwd
return cwd.Rfindalldirs(pathlist)
memoizer_counters.append(SCons.Memoize.CountValue('rentry'))
def rentry(self):
try:
return self._memo['rentry']
except KeyError:
pass
result = self
if not self.exists():
norm_name = _my_normcase(self.name)
for dir in self.dir.get_all_rdirs():
try:
node = dir.entries[norm_name]
except KeyError:
if dir.entry_exists_on_disk(self.name):
result = dir.Entry(self.name)
break
self._memo['rentry'] = result
return result
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
return []
class Entry(Base):
"""This is the class for generic Node.FS entries--that is, things
that could be a File or a Dir, but we're just not sure yet.
Consequently, the methods in this class really exist just to
transform their associated object into the right class when the
time comes, and then call the same-named method in the transformed
class."""
def diskcheck_match(self):
pass
def disambiguate(self, must_exist=None):
"""
"""
if self.isdir():
self.__class__ = Dir
self._morph()
elif self.isfile():
self.__class__ = File
self._morph()
self.clear()
else:
# There was nothing on-disk at this location, so look in
# the src directory.
#
# We can't just use self.srcnode() straight away because
# that would create an actual Node for this file in the src
# directory, and there might not be one. Instead, use the
# dir_on_disk() method to see if there's something on-disk
# with that name, in which case we can go ahead and call
# self.srcnode() to create the right type of entry.
srcdir = self.dir.srcnode()
if srcdir != self.dir and \
srcdir.entry_exists_on_disk(self.name) and \
self.srcnode().isdir():
self.__class__ = Dir
self._morph()
elif must_exist:
msg = "No such file or directory: '%s'" % self.abspath
raise SCons.Errors.UserError, msg
else:
self.__class__ = File
self._morph()
self.clear()
return self
def rfile(self):
"""We're a generic Entry, but the caller is actually looking for
a File at this point, so morph into one."""
self.__class__ = File
self._morph()
self.clear()
return File.rfile(self)
def scanner_key(self):
return self.get_suffix()
def get_contents(self):
"""Fetch the contents of the entry. Returns the exact binary
contents of the file."""
try:
self = self.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Entry, but return a null
# string so calls to get_contents() in emitters and the
# like (e.g. in qt.py) don't have to disambiguate by hand
# or catch the exception.
return ''
else:
return self.get_contents()
def get_text_contents(self):
"""Fetch the decoded text contents of a Unicode encoded Entry.
Since this should return the text contents from the file
system, we check to see into what sort of subclass we should
morph this Entry."""
try:
self = self.disambiguate(must_exist=1)
except SCons.Errors.UserError:
# There was nothing on disk with which to disambiguate
# this entry. Leave it as an Entry, but return a null
# string so calls to get_text_contents() in emitters and
# the like (e.g. in qt.py) don't have to disambiguate by
# hand or catch the exception.
return ''
else:
return self.get_text_contents()
def must_be_same(self, klass):
"""Called to make sure a Node is a Dir. Since we're an
Entry, we can morph into one."""
if self.__class__ is not klass:
self.__class__ = klass
self._morph()
self.clear()
# The following methods can get called before the Taskmaster has
# had a chance to call disambiguate() directly to see if this Entry
# should really be a Dir or a File. We therefore use these to call
# disambiguate() transparently (from our caller's point of view).
#
# Right now, this minimal set of methods has been derived by just
# looking at some of the methods that will obviously be called early
# in any of the various Taskmasters' calling sequences, and then
# empirically figuring out which additional methods are necessary
# to make various tests pass.
def exists(self):
"""Return if the Entry exists. Check the file system to see
what we should turn into first. Assume a file if there's no
directory."""
return self.disambiguate().exists()
def rel_path(self, other):
d = self.disambiguate()
if d.__class__ is Entry:
raise "rel_path() could not disambiguate File/Dir"
return d.rel_path(other)
def new_ninfo(self):
return self.disambiguate().new_ninfo()
def changed_since_last_build(self, target, prev_ni):
return self.disambiguate().changed_since_last_build(target, prev_ni)
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
return self.disambiguate()._glob1(pattern, ondisk, source, strings)
def get_subst_proxy(self):
return self.disambiguate().get_subst_proxy()
# This is for later so we can differentiate between Entry the class and Entry
# the method of the FS class.
_classEntry = Entry
class LocalFS:
if SCons.Memoize.use_memoizer:
__metaclass__ = SCons.Memoize.Memoized_Metaclass
# This class implements an abstraction layer for operations involving
# a local file system. Essentially, this wraps any function in
# the os, os.path or shutil modules that we use to actually go do
# anything with or to the local file system.
#
# Note that there's a very good chance we'll refactor this part of
# the architecture in some way as we really implement the interface(s)
# for remote file system Nodes. For example, the right architecture
# might be to have this be a subclass instead of a base class.
# Nevertheless, we're using this as a first step in that direction.
#
# We're not using chdir() yet because the calling subclass method
# needs to use os.chdir() directly to avoid recursion. Will we
# really need this one?
#def chdir(self, path):
# return os.chdir(path)
def chmod(self, path, mode):
return os.chmod(path, mode)
def copy(self, src, dst):
return shutil.copy(src, dst)
def copy2(self, src, dst):
return shutil.copy2(src, dst)
def exists(self, path):
return os.path.exists(path)
def getmtime(self, path):
return os.path.getmtime(path)
def getsize(self, path):
return os.path.getsize(path)
def isdir(self, path):
return os.path.isdir(path)
def isfile(self, path):
return os.path.isfile(path)
def link(self, src, dst):
return os.link(src, dst)
def lstat(self, path):
return os.lstat(path)
def listdir(self, path):
return os.listdir(path)
def makedirs(self, path):
return os.makedirs(path)
def mkdir(self, path):
return os.mkdir(path)
def rename(self, old, new):
return os.rename(old, new)
def stat(self, path):
return os.stat(path)
def symlink(self, src, dst):
return os.symlink(src, dst)
def open(self, path):
return open(path)
def unlink(self, path):
return os.unlink(path)
if hasattr(os, 'symlink'):
def islink(self, path):
return os.path.islink(path)
else:
def islink(self, path):
return 0 # no symlinks
if hasattr(os, 'readlink'):
def readlink(self, file):
return os.readlink(file)
else:
def readlink(self, file):
return ''
#class RemoteFS:
# # Skeleton for the obvious methods we might need from the
# # abstraction layer for a remote filesystem.
# def upload(self, local_src, remote_dst):
# pass
# def download(self, remote_src, local_dst):
# pass
class FS(LocalFS):
memoizer_counters = []
def __init__(self, path = None):
"""Initialize the Node.FS subsystem.
The supplied path is the top of the source tree, where we
expect to find the top-level build file. If no path is
supplied, the current directory is the default.
The path argument must be a valid absolute path.
"""
if __debug__: logInstanceCreation(self, 'Node.FS')
self._memo = {}
self.Root = {}
self.SConstruct_dir = None
self.max_drift = default_max_drift
self.Top = None
if path is None:
self.pathTop = os.getcwd()
else:
self.pathTop = path
self.defaultDrive = _my_normcase(os.path.splitdrive(self.pathTop)[0])
self.Top = self.Dir(self.pathTop)
self.Top.path = '.'
self.Top.tpath = '.'
self._cwd = self.Top
DirNodeInfo.fs = self
FileNodeInfo.fs = self
def set_SConstruct_dir(self, dir):
self.SConstruct_dir = dir
def get_max_drift(self):
return self.max_drift
def set_max_drift(self, max_drift):
self.max_drift = max_drift
def getcwd(self):
return self._cwd
def chdir(self, dir, change_os_dir=0):
"""Change the current working directory for lookups.
If change_os_dir is true, we will also change the "real" cwd
to match.
"""
curr=self._cwd
try:
if dir is not None:
self._cwd = dir
if change_os_dir:
os.chdir(dir.abspath)
except OSError:
self._cwd = curr
raise
def get_root(self, drive):
"""
Returns the root directory for the specified drive, creating
it if necessary.
"""
drive = _my_normcase(drive)
try:
return self.Root[drive]
except KeyError:
root = RootDir(drive, self)
self.Root[drive] = root
if not drive:
self.Root[self.defaultDrive] = root
elif drive == self.defaultDrive:
self.Root[''] = root
return root
def _lookup(self, p, directory, fsclass, create=1):
"""
The generic entry point for Node lookup with user-supplied data.
This translates arbitrary input into a canonical Node.FS object
of the specified fsclass. The general approach for strings is
to turn it into a fully normalized absolute path and then call
the root directory's lookup_abs() method for the heavy lifting.
If the path name begins with '#', it is unconditionally
interpreted relative to the top-level directory of this FS. '#'
is treated as a synonym for the top-level SConstruct directory,
much like '~' is treated as a synonym for the user's home
directory in a UNIX shell. So both '#foo' and '#/foo' refer
to the 'foo' subdirectory underneath the top-level SConstruct
directory.
If the path name is relative, then the path is looked up relative
to the specified directory, or the current directory (self._cwd,
typically the SConscript directory) if the specified directory
is None.
"""
if isinstance(p, Base):
# It's already a Node.FS object. Make sure it's the right
# class and return.
p.must_be_same(fsclass)
return p
# str(p) in case it's something like a proxy object
p = str(p)
initial_hash = (p[0:1] == '#')
if initial_hash:
# There was an initial '#', so we strip it and override
# whatever directory they may have specified with the
# top-level SConstruct directory.
p = p[1:]
directory = self.Top
if directory and not isinstance(directory, Dir):
directory = self.Dir(directory)
if do_splitdrive:
drive, p = os.path.splitdrive(p)
else:
drive = ''
if drive and not p:
# This causes a naked drive letter to be treated as a synonym
# for the root directory on that drive.
p = os.sep
absolute = os.path.isabs(p)
needs_normpath = needs_normpath_check.match(p)
if initial_hash or not absolute:
# This is a relative lookup, either to the top-level
# SConstruct directory (because of the initial '#') or to
# the current directory (the path name is not absolute).
# Add the string to the appropriate directory lookup path,
# after which the whole thing gets normalized.
if not directory:
directory = self._cwd
if p:
p = directory.labspath + '/' + p
else:
p = directory.labspath
if needs_normpath:
p = os.path.normpath(p)
if drive or absolute:
root = self.get_root(drive)
else:
if not directory:
directory = self._cwd
root = directory.root
if os.sep != '/':
p = string.replace(p, os.sep, '/')
return root._lookup_abs(p, fsclass, create)
def Entry(self, name, directory = None, create = 1):
"""Look up or create a generic Entry node with the specified name.
If the name is a relative path (begins with ./, ../, or a file
name), then it is looked up relative to the supplied directory
node, or to the top level directory of the FS (supplied at
construction time) if no directory is supplied.
"""
return self._lookup(name, directory, Entry, create)
def File(self, name, directory = None, create = 1):
"""Look up or create a File node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supplied at construction
time) if no directory is supplied.
This method will raise TypeError if a directory is found at the
specified path.
"""
return self._lookup(name, directory, File, create)
def Dir(self, name, directory = None, create = True):
"""Look up or create a Dir node with the specified name. If
the name is a relative path (begins with ./, ../, or a file name),
then it is looked up relative to the supplied directory node,
or to the top level directory of the FS (supplied at construction
time) if no directory is supplied.
This method will raise TypeError if a normal file is found at the
specified path.
"""
return self._lookup(name, directory, Dir, create)
def VariantDir(self, variant_dir, src_dir, duplicate=1):
"""Link the supplied variant directory to the source directory
for purposes of building files."""
if not isinstance(src_dir, SCons.Node.Node):
src_dir = self.Dir(src_dir)
if not isinstance(variant_dir, SCons.Node.Node):
variant_dir = self.Dir(variant_dir)
if src_dir.is_under(variant_dir):
raise SCons.Errors.UserError, "Source directory cannot be under variant directory."
if variant_dir.srcdir:
if variant_dir.srcdir == src_dir:
return # We already did this.
raise SCons.Errors.UserError, "'%s' already has a source directory: '%s'."%(variant_dir, variant_dir.srcdir)
variant_dir.link(src_dir, duplicate)
def Repository(self, *dirs):
"""Specify Repository directories to search."""
for d in dirs:
if not isinstance(d, SCons.Node.Node):
d = self.Dir(d)
self.Top.addRepository(d)
def variant_dir_target_climb(self, orig, dir, tail):
"""Create targets in corresponding variant directories
Climb the directory tree, and look up path names
relative to any linked variant directories we find.
Even though this loops and walks up the tree, we don't memoize
the return value because this is really only used to process
the command-line targets.
"""
targets = []
message = None
fmt = "building associated VariantDir targets: %s"
start_dir = dir
while dir:
for bd in dir.variant_dirs:
if start_dir.is_under(bd):
# If already in the build-dir location, don't reflect
return [orig], fmt % str(orig)
p = apply(os.path.join, [bd.path] + tail)
targets.append(self.Entry(p))
tail = [dir.name] + tail
dir = dir.up()
if targets:
message = fmt % string.join(map(str, targets))
return targets, message
def Glob(self, pathname, ondisk=True, source=True, strings=False, cwd=None):
"""
Globs
This is mainly a shim layer
"""
if cwd is None:
cwd = self.getcwd()
return cwd.glob(pathname, ondisk, source, strings)
class DirNodeInfo(SCons.Node.NodeInfoBase):
# This should get reset by the FS initialization.
current_version_id = 1
fs = None
def str_to_node(self, s):
top = self.fs.Top
root = top.root
if do_splitdrive:
drive, s = os.path.splitdrive(s)
if drive:
root = self.fs.get_root(drive)
if not os.path.isabs(s):
s = top.labspath + '/' + s
return root._lookup_abs(s, Entry)
class DirBuildInfo(SCons.Node.BuildInfoBase):
current_version_id = 1
glob_magic_check = re.compile('[*?[]')
def has_glob_magic(s):
return glob_magic_check.search(s) is not None
class Dir(Base):
"""A class for directories in a file system.
"""
memoizer_counters = []
NodeInfo = DirNodeInfo
BuildInfo = DirBuildInfo
def __init__(self, name, directory, fs):
if __debug__: logInstanceCreation(self, 'Node.FS.Dir')
Base.__init__(self, name, directory, fs)
self._morph()
def _morph(self):
"""Turn a file system Node (either a freshly initialized directory
object or a separate Entry object) into a proper directory object.
Set up this directory's entries and hook it into the file
system tree. Specify that directories (this Node) don't use
signatures for calculating whether they're current.
"""
self.repositories = []
self.srcdir = None
self.entries = {}
self.entries['.'] = self
self.entries['..'] = self.dir
self.cwd = self
self.searched = 0
self._sconsign = None
self.variant_dirs = []
self.root = self.dir.root
# Don't just reset the executor, replace its action list,
# because it might have some pre-or post-actions that need to
# be preserved.
self.builder = get_MkdirBuilder()
self.get_executor().set_action_list(self.builder.action)
def diskcheck_match(self):
diskcheck_match(self, self.isfile,
"File %s found where directory expected.")
def __clearRepositoryCache(self, duplicate=None):
"""Called when we change the repository(ies) for a directory.
This clears any cached information that is invalidated by changing
the repository."""
for node in self.entries.values():
if node != self.dir:
if node != self and isinstance(node, Dir):
node.__clearRepositoryCache(duplicate)
else:
node.clear()
try:
del node._srcreps
except AttributeError:
pass
if duplicate is not None:
node.duplicate=duplicate
def __resetDuplicate(self, node):
if node != self:
node.duplicate = node.get_dir().duplicate
def Entry(self, name):
"""
Looks up or creates an entry node named 'name' relative to
this directory.
"""
return self.fs.Entry(name, self)
def Dir(self, name, create=True):
"""
Looks up or creates a directory node named 'name' relative to
this directory.
"""
return self.fs.Dir(name, self, create)
def File(self, name):
"""
Looks up or creates a file node named 'name' relative to
this directory.
"""
return self.fs.File(name, self)
def _lookup_rel(self, name, klass, create=1):
"""
Looks up a *normalized* relative path name, relative to this
directory.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the Entry(), Dir() and File() methods above.
This method does *no* input checking and will die or give
incorrect results if it's passed a non-normalized path name (e.g.,
a path containing '..'), an absolute path name, a top-relative
('#foo') path name, or any kind of object.
"""
name = self.entry_labspath(name)
return self.root._lookup_abs(name, klass, create)
def link(self, srcdir, duplicate):
"""Set this directory as the variant directory for the
supplied source directory."""
self.srcdir = srcdir
self.duplicate = duplicate
self.__clearRepositoryCache(duplicate)
srcdir.variant_dirs.append(self)
def getRepositories(self):
"""Returns a list of repositories for this directory.
"""
if self.srcdir and not self.duplicate:
return self.srcdir.get_all_rdirs() + self.repositories
return self.repositories
memoizer_counters.append(SCons.Memoize.CountValue('get_all_rdirs'))
def get_all_rdirs(self):
try:
return list(self._memo['get_all_rdirs'])
except KeyError:
pass
result = [self]
fname = '.'
dir = self
while dir:
for rep in dir.getRepositories():
result.append(rep.Dir(fname))
if fname == '.':
fname = dir.name
else:
fname = dir.name + os.sep + fname
dir = dir.up()
self._memo['get_all_rdirs'] = list(result)
return result
def addRepository(self, dir):
if dir != self and not dir in self.repositories:
self.repositories.append(dir)
dir.tpath = '.'
self.__clearRepositoryCache()
def up(self):
return self.entries['..']
def _rel_path_key(self, other):
return str(other)
memoizer_counters.append(SCons.Memoize.CountDict('rel_path', _rel_path_key))
def rel_path(self, other):
"""Return a path to "other" relative to this directory.
"""
# This complicated and expensive method, which constructs relative
# paths between arbitrary Node.FS objects, is no longer used
# by SCons itself. It was introduced to store dependency paths
# in .sconsign files relative to the target, but that ended up
# being significantly inefficient.
#
# We're continuing to support the method because some SConstruct
# files out there started using it when it was available, and
# we're all about backwards compatibility..
try:
memo_dict = self._memo['rel_path']
except KeyError:
memo_dict = {}
self._memo['rel_path'] = memo_dict
else:
try:
return memo_dict[other]
except KeyError:
pass
if self is other:
result = '.'
elif not other in self.path_elements:
try:
other_dir = other.get_dir()
except AttributeError:
result = str(other)
else:
if other_dir is None:
result = other.name
else:
dir_rel_path = self.rel_path(other_dir)
if dir_rel_path == '.':
result = other.name
else:
result = dir_rel_path + os.sep + other.name
else:
i = self.path_elements.index(other) + 1
path_elems = ['..'] * (len(self.path_elements) - i) \
+ map(lambda n: n.name, other.path_elements[i:])
result = string.join(path_elems, os.sep)
memo_dict[other] = result
return result
def get_env_scanner(self, env, kw={}):
import SCons.Defaults
return SCons.Defaults.DirEntryScanner
def get_target_scanner(self):
import SCons.Defaults
return SCons.Defaults.DirEntryScanner
def get_found_includes(self, env, scanner, path):
"""Return this directory's implicit dependencies.
We don't bother caching the results because the scan typically
shouldn't be requested more than once (as opposed to scanning
.h file contents, which can be requested as many times as the
files is #included by other files).
"""
if not scanner:
return []
# Clear cached info for this Dir. If we already visited this
# directory on our walk down the tree (because we didn't know at
# that point it was being used as the source for another Node)
# then we may have calculated build signature before realizing
# we had to scan the disk. Now that we have to, though, we need
# to invalidate the old calculated signature so that any node
# dependent on our directory structure gets one that includes
# info about everything on disk.
self.clear()
return scanner(self, env, path)
#
# Taskmaster interface subsystem
#
def prepare(self):
pass
def build(self, **kw):
"""A null "builder" for directories."""
global MkdirBuilder
if self.builder is not MkdirBuilder:
apply(SCons.Node.Node.build, [self,], kw)
#
#
#
def _create(self):
"""Create this directory, silently and without worrying about
whether the builder is the default or not."""
listDirs = []
parent = self
while parent:
if parent.exists():
break
listDirs.append(parent)
p = parent.up()
if p is None:
# Don't use while: - else: for this condition because
# if so, then parent is None and has no .path attribute.
raise SCons.Errors.StopError, parent.path
parent = p
listDirs.reverse()
for dirnode in listDirs:
try:
# Don't call dirnode.build(), call the base Node method
# directly because we definitely *must* create this
# directory. The dirnode.build() method will suppress
# the build if it's the default builder.
SCons.Node.Node.build(dirnode)
dirnode.get_executor().nullify()
# The build() action may or may not have actually
# created the directory, depending on whether the -n
# option was used or not. Delete the _exists and
# _rexists attributes so they can be reevaluated.
dirnode.clear()
except OSError:
pass
def multiple_side_effect_has_builder(self):
global MkdirBuilder
return self.builder is not MkdirBuilder and self.has_builder()
def alter_targets(self):
"""Return any corresponding targets in a variant directory.
"""
return self.fs.variant_dir_target_climb(self, self, [])
def scanner_key(self):
"""A directory does not get scanned."""
return None
def get_text_contents(self):
"""We already emit things in text, so just return the binary
version."""
return self.get_contents()
def get_contents(self):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
name_cmp = lambda a, b: cmp(a.name, b.name)
sorted_children = self.children()[:]
sorted_children.sort(name_cmp)
for node in sorted_children:
contents.append('%s %s\n' % (node.get_csig(), node.name))
return string.join(contents, '')
def get_csig(self):
"""Compute the content signature for Directory nodes. In
general, this is not needed and the content signature is not
stored in the DirNodeInfo. However, if get_contents on a Dir
node is called which has a child directory, the child
directory should return the hash of its contents."""
contents = self.get_contents()
return SCons.Util.MD5signature(contents)
def do_duplicate(self, src):
pass
changed_since_last_build = SCons.Node.Node.state_has_changed
def is_up_to_date(self):
"""If any child is not up-to-date, then this directory isn't,
either."""
if self.builder is not MkdirBuilder and not self.exists():
return 0
up_to_date = SCons.Node.up_to_date
for kid in self.children():
if kid.get_state() > up_to_date:
return 0
return 1
def rdir(self):
if not self.exists():
norm_name = _my_normcase(self.name)
for dir in self.dir.get_all_rdirs():
try: node = dir.entries[norm_name]
except KeyError: node = dir.dir_on_disk(self.name)
if node and node.exists() and \
(isinstance(dir, Dir) or isinstance(dir, Entry)):
return node
return self
def sconsign(self):
"""Return the .sconsign file info for this directory,
creating it first if necessary."""
if not self._sconsign:
import SCons.SConsign
self._sconsign = SCons.SConsign.ForDirectory(self)
return self._sconsign
def srcnode(self):
"""Dir has a special need for srcnode()...if we
have a srcdir attribute set, then that *is* our srcnode."""
if self.srcdir:
return self.srcdir
return Base.srcnode(self)
def get_timestamp(self):
"""Return the latest timestamp from among our children"""
stamp = 0
for kid in self.children():
if kid.get_timestamp() > stamp:
stamp = kid.get_timestamp()
return stamp
def entry_abspath(self, name):
return self.abspath + os.sep + name
def entry_labspath(self, name):
return self.labspath + '/' + name
def entry_path(self, name):
return self.path + os.sep + name
def entry_tpath(self, name):
return self.tpath + os.sep + name
def entry_exists_on_disk(self, name):
try:
d = self.on_disk_entries
except AttributeError:
d = {}
try:
entries = os.listdir(self.abspath)
except OSError:
pass
else:
for entry in map(_my_normcase, entries):
d[entry] = True
self.on_disk_entries = d
if sys.platform == 'win32':
name = _my_normcase(name)
result = d.get(name)
if result is None:
# Belt-and-suspenders for Windows: check directly for
# 8.3 file names that don't show up in os.listdir().
result = os.path.exists(self.abspath + os.sep + name)
d[name] = result
return result
else:
return d.has_key(name)
memoizer_counters.append(SCons.Memoize.CountValue('srcdir_list'))
def srcdir_list(self):
try:
return self._memo['srcdir_list']
except KeyError:
pass
result = []
dirname = '.'
dir = self
while dir:
if dir.srcdir:
result.append(dir.srcdir.Dir(dirname))
dirname = dir.name + os.sep + dirname
dir = dir.up()
self._memo['srcdir_list'] = result
return result
def srcdir_duplicate(self, name):
for dir in self.srcdir_list():
if self.is_under(dir):
# We shouldn't source from something in the build path;
# variant_dir is probably under src_dir, in which case
# we are reflecting.
break
if dir.entry_exists_on_disk(name):
srcnode = dir.Entry(name).disambiguate()
if self.duplicate:
node = self.Entry(name).disambiguate()
node.do_duplicate(srcnode)
return node
else:
return srcnode
return None
def _srcdir_find_file_key(self, filename):
return filename
memoizer_counters.append(SCons.Memoize.CountDict('srcdir_find_file', _srcdir_find_file_key))
def srcdir_find_file(self, filename):
try:
memo_dict = self._memo['srcdir_find_file']
except KeyError:
memo_dict = {}
self._memo['srcdir_find_file'] = memo_dict
else:
try:
return memo_dict[filename]
except KeyError:
pass
def func(node):
if (isinstance(node, File) or isinstance(node, Entry)) and \
(node.is_derived() or node.exists()):
return node
return None
norm_name = _my_normcase(filename)
for rdir in self.get_all_rdirs():
try: node = rdir.entries[norm_name]
except KeyError: node = rdir.file_on_disk(filename)
else: node = func(node)
if node:
result = (node, self)
memo_dict[filename] = result
return result
for srcdir in self.srcdir_list():
for rdir in srcdir.get_all_rdirs():
try: node = rdir.entries[norm_name]
except KeyError: node = rdir.file_on_disk(filename)
else: node = func(node)
if node:
result = (File(filename, self, self.fs), srcdir)
memo_dict[filename] = result
return result
result = (None, None)
memo_dict[filename] = result
return result
def dir_on_disk(self, name):
if self.entry_exists_on_disk(name):
try: return self.Dir(name)
except TypeError: pass
node = self.srcdir_duplicate(name)
if isinstance(node, File):
return None
return node
def file_on_disk(self, name):
if self.entry_exists_on_disk(name) or \
diskcheck_rcs(self, name) or \
diskcheck_sccs(self, name):
try: return self.File(name)
except TypeError: pass
node = self.srcdir_duplicate(name)
if isinstance(node, Dir):
return None
return node
def walk(self, func, arg):
"""
Walk this directory tree by calling the specified function
for each directory in the tree.
This behaves like the os.path.walk() function, but for in-memory
Node.FS.Dir objects. The function takes the same arguments as
the functions passed to os.path.walk():
func(arg, dirname, fnames)
Except that "dirname" will actually be the directory *Node*,
not the string. The '.' and '..' entries are excluded from
fnames. The fnames list may be modified in-place to filter the
subdirectories visited or otherwise impose a specific order.
The "arg" argument is always passed to func() and may be used
in any way (or ignored, passing None is common).
"""
entries = self.entries
names = entries.keys()
names.remove('.')
names.remove('..')
func(arg, self, names)
select_dirs = lambda n, e=entries: isinstance(e[n], Dir)
for dirname in filter(select_dirs, names):
entries[dirname].walk(func, arg)
def glob(self, pathname, ondisk=True, source=False, strings=False):
"""
Returns a list of Nodes (or strings) matching a specified
pathname pattern.
Pathname patterns follow UNIX shell semantics: * matches
any-length strings of any characters, ? matches any character,
and [] can enclose lists or ranges of characters. Matches do
not span directory separators.
The matches take into account Repositories, returning local
Nodes if a corresponding entry exists in a Repository (either
an in-memory Node or something on disk).
By defafult, the glob() function matches entries that exist
on-disk, in addition to in-memory Nodes. Setting the "ondisk"
argument to False (or some other non-true value) causes the glob()
function to only match in-memory Nodes. The default behavior is
to return both the on-disk and in-memory Nodes.
The "source" argument, when true, specifies that corresponding
source Nodes must be returned if you're globbing in a build
directory (initialized with VariantDir()). The default behavior
is to return Nodes local to the VariantDir().
The "strings" argument, when true, returns the matches as strings,
not Nodes. The strings are path names relative to this directory.
The underlying algorithm is adapted from the glob.glob() function
in the Python library (but heavily modified), and uses fnmatch()
under the covers.
"""
dirname, basename = os.path.split(pathname)
if not dirname:
result = self._glob1(basename, ondisk, source, strings)
result.sort(lambda a, b: cmp(str(a), str(b)))
return result
if has_glob_magic(dirname):
list = self.glob(dirname, ondisk, source, strings=False)
else:
list = [self.Dir(dirname, create=True)]
result = []
for dir in list:
r = dir._glob1(basename, ondisk, source, strings)
if strings:
r = map(lambda x, d=str(dir): os.path.join(d, x), r)
result.extend(r)
result.sort(lambda a, b: cmp(str(a), str(b)))
return result
def _glob1(self, pattern, ondisk=True, source=False, strings=False):
"""
Globs for and returns a list of entry names matching a single
pattern in this directory.
This searches any repositories and source directories for
corresponding entries and returns a Node (or string) relative
to the current directory if an entry is found anywhere.
TODO: handle pattern with no wildcard
"""
search_dir_list = self.get_all_rdirs()
for srcdir in self.srcdir_list():
search_dir_list.extend(srcdir.get_all_rdirs())
selfEntry = self.Entry
names = []
for dir in search_dir_list:
# We use the .name attribute from the Node because the keys of
# the dir.entries dictionary are normalized (that is, all upper
# case) on case-insensitive systems like Windows.
#node_names = [ v.name for k, v in dir.entries.items() if k not in ('.', '..') ]
entry_names = filter(lambda n: n not in ('.', '..'), dir.entries.keys())
node_names = map(lambda n, e=dir.entries: e[n].name, entry_names)
names.extend(node_names)
if not strings:
# Make sure the working directory (self) actually has
# entries for all Nodes in repositories or variant dirs.
for name in node_names: selfEntry(name)
if ondisk:
try:
disk_names = os.listdir(dir.abspath)
except os.error:
continue
names.extend(disk_names)
if not strings:
# We're going to return corresponding Nodes in
# the local directory, so we need to make sure
# those Nodes exist. We only want to create
# Nodes for the entries that will match the
# specified pattern, though, which means we
# need to filter the list here, even though
# the overall list will also be filtered later,
# after we exit this loop.
if pattern[0] != '.':
#disk_names = [ d for d in disk_names if d[0] != '.' ]
disk_names = filter(lambda x: x[0] != '.', disk_names)
disk_names = fnmatch.filter(disk_names, pattern)
dirEntry = dir.Entry
for name in disk_names:
# Add './' before disk filename so that '#' at
# beginning of filename isn't interpreted.
name = './' + name
node = dirEntry(name).disambiguate()
n = selfEntry(name)
if n.__class__ != node.__class__:
n.__class__ = node.__class__
n._morph()
names = set(names)
if pattern[0] != '.':
#names = [ n for n in names if n[0] != '.' ]
names = filter(lambda x: x[0] != '.', names)
names = fnmatch.filter(names, pattern)
if strings:
return names
#return [ self.entries[_my_normcase(n)] for n in names ]
return map(lambda n, e=self.entries: e[_my_normcase(n)], names)
class RootDir(Dir):
"""A class for the root directory of a file system.
This is the same as a Dir class, except that the path separator
('/' or '\\') is actually part of the name, so we don't need to
add a separator when creating the path names of entries within
this directory.
"""
def __init__(self, name, fs):
if __debug__: logInstanceCreation(self, 'Node.FS.RootDir')
# We're going to be our own parent directory (".." entry and .dir
# attribute) so we have to set up some values so Base.__init__()
# won't gag won't it calls some of our methods.
self.abspath = ''
self.labspath = ''
self.path = ''
self.tpath = ''
self.path_elements = []
self.duplicate = 0
self.root = self
Base.__init__(self, name, self, fs)
# Now set our paths to what we really want them to be: the
# initial drive letter (the name) plus the directory separator,
# except for the "lookup abspath," which does not have the
# drive letter.
self.abspath = name + os.sep
self.labspath = ''
self.path = name + os.sep
self.tpath = name + os.sep
self._morph()
self._lookupDict = {}
# The // and os.sep + os.sep entries are necessary because
# os.path.normpath() seems to preserve double slashes at the
# beginning of a path (presumably for UNC path names), but
# collapses triple slashes to a single slash.
self._lookupDict[''] = self
self._lookupDict['/'] = self
self._lookupDict['//'] = self
self._lookupDict[os.sep] = self
self._lookupDict[os.sep + os.sep] = self
def must_be_same(self, klass):
if klass is Dir:
return
Base.must_be_same(self, klass)
def _lookup_abs(self, p, klass, create=1):
"""
Fast (?) lookup of a *normalized* absolute path.
This method is intended for use by internal lookups with
already-normalized path data. For general-purpose lookups,
use the FS.Entry(), FS.Dir() or FS.File() methods.
The caller is responsible for making sure we're passed a
normalized absolute path; we merely let Python's dictionary look
up and return the One True Node.FS object for the path.
If no Node for the specified "p" doesn't already exist, and
"create" is specified, the Node may be created after recursive
invocation to find or create the parent directory or directories.
"""
k = _my_normcase(p)
try:
result = self._lookupDict[k]
except KeyError:
if not create:
msg = "No such file or directory: '%s' in '%s' (and create is False)" % (p, str(self))
raise SCons.Errors.UserError, msg
# There is no Node for this path name, and we're allowed
# to create it.
dir_name, file_name = os.path.split(p)
dir_node = self._lookup_abs(dir_name, Dir)
result = klass(file_name, dir_node, self.fs)
# Double-check on disk (as configured) that the Node we
# created matches whatever is out there in the real world.
result.diskcheck_match()
self._lookupDict[k] = result
dir_node.entries[_my_normcase(file_name)] = result
dir_node.implicit = None
else:
# There is already a Node for this path name. Allow it to
# complain if we were looking for an inappropriate type.
result.must_be_same(klass)
return result
def __str__(self):
return self.abspath
def entry_abspath(self, name):
return self.abspath + name
def entry_labspath(self, name):
return '/' + name
def entry_path(self, name):
return self.path + name
def entry_tpath(self, name):
return self.tpath + name
def is_under(self, dir):
if self is dir:
return 1
else:
return 0
def up(self):
return None
def get_dir(self):
return None
def src_builder(self):
return _null
class FileNodeInfo(SCons.Node.NodeInfoBase):
current_version_id = 1
field_list = ['csig', 'timestamp', 'size']
# This should get reset by the FS initialization.
fs = None
def str_to_node(self, s):
top = self.fs.Top
root = top.root
if do_splitdrive:
drive, s = os.path.splitdrive(s)
if drive:
root = self.fs.get_root(drive)
if not os.path.isabs(s):
s = top.labspath + '/' + s
return root._lookup_abs(s, Entry)
class FileBuildInfo(SCons.Node.BuildInfoBase):
current_version_id = 1
def convert_to_sconsign(self):
"""
Converts this FileBuildInfo object for writing to a .sconsign file
This replaces each Node in our various dependency lists with its
usual string representation: relative to the top-level SConstruct
directory, or an absolute path if it's outside.
"""
if os.sep == '/':
node_to_str = str
else:
def node_to_str(n):
try:
s = n.path
except AttributeError:
s = str(n)
else:
s = string.replace(s, os.sep, '/')
return s
for attr in ['bsources', 'bdepends', 'bimplicit']:
try:
val = getattr(self, attr)
except AttributeError:
pass
else:
setattr(self, attr, map(node_to_str, val))
def convert_from_sconsign(self, dir, name):
"""
Converts a newly-read FileBuildInfo object for in-SCons use
For normal up-to-date checking, we don't have any conversion to
perform--but we're leaving this method here to make that clear.
"""
pass
def prepare_dependencies(self):
"""
Prepares a FileBuildInfo object for explaining what changed
The bsources, bdepends and bimplicit lists have all been
stored on disk as paths relative to the top-level SConstruct
directory. Convert the strings to actual Nodes (for use by the
--debug=explain code and --implicit-cache).
"""
attrs = [
('bsources', 'bsourcesigs'),
('bdepends', 'bdependsigs'),
('bimplicit', 'bimplicitsigs'),
]
for (nattr, sattr) in attrs:
try:
strings = getattr(self, nattr)
nodeinfos = getattr(self, sattr)
except AttributeError:
continue
nodes = []
for s, ni in izip(strings, nodeinfos):
if not isinstance(s, SCons.Node.Node):
s = ni.str_to_node(s)
nodes.append(s)
setattr(self, nattr, nodes)
def format(self, names=0):
result = []
bkids = self.bsources + self.bdepends + self.bimplicit
bkidsigs = self.bsourcesigs + self.bdependsigs + self.bimplicitsigs
for bkid, bkidsig in izip(bkids, bkidsigs):
result.append(str(bkid) + ': ' +
string.join(bkidsig.format(names=names), ' '))
result.append('%s [%s]' % (self.bactsig, self.bact))
return string.join(result, '\n')
class File(Base):
"""A class for files in a file system.
"""
memoizer_counters = []
NodeInfo = FileNodeInfo
BuildInfo = FileBuildInfo
md5_chunksize = 64
def diskcheck_match(self):
diskcheck_match(self, self.isdir,
"Directory %s found where file expected.")
def __init__(self, name, directory, fs):
if __debug__: logInstanceCreation(self, 'Node.FS.File')
Base.__init__(self, name, directory, fs)
self._morph()
def Entry(self, name):
"""Create an entry node named 'name' relative to
the directory of this file."""
return self.dir.Entry(name)
def Dir(self, name, create=True):
"""Create a directory node named 'name' relative to
the directory of this file."""
return self.dir.Dir(name, create=create)
def Dirs(self, pathlist):
"""Create a list of directories relative to the SConscript
directory of this file."""
# TODO(1.5)
# return [self.Dir(p) for p in pathlist]
return map(lambda p, s=self: s.Dir(p), pathlist)
def File(self, name):
"""Create a file node named 'name' relative to
the directory of this file."""
return self.dir.File(name)
#def generate_build_dict(self):
# """Return an appropriate dictionary of values for building
# this File."""
# return {'Dir' : self.Dir,
# 'File' : self.File,
# 'RDirs' : self.RDirs}
def _morph(self):
"""Turn a file system node into a File object."""
self.scanner_paths = {}
if not hasattr(self, '_local'):
self._local = 0
# If there was already a Builder set on this entry, then
# we need to make sure we call the target-decider function,
# not the source-decider. Reaching in and doing this by hand
# is a little bogus. We'd prefer to handle this by adding
# an Entry.builder_set() method that disambiguates like the
# other methods, but that starts running into problems with the
# fragile way we initialize Dir Nodes with their Mkdir builders,
# yet still allow them to be overridden by the user. Since it's
# not clear right now how to fix that, stick with what works
# until it becomes clear...
if self.has_builder():
self.changed_since_last_build = self.decide_target
def scanner_key(self):
return self.get_suffix()
def get_contents(self):
if not self.rexists():
return ''
fname = self.rfile().abspath
try:
contents = open(fname, "rb").read()
except EnvironmentError, e:
if not e.filename:
e.filename = fname
raise
return contents
try:
import codecs
except ImportError:
get_text_contents = get_contents
else:
# This attempts to figure out what the encoding of the text is
# based upon the BOM bytes, and then decodes the contents so that
# it's a valid python string.
def get_text_contents(self):
contents = self.get_contents()
# The behavior of various decode() methods and functions
# w.r.t. the initial BOM bytes is different for different
# encodings and/or Python versions. ('utf-8' does not strip
# them, but has a 'utf-8-sig' which does; 'utf-16' seems to
# strip them; etc.) Just side step all the complication by
# explicitly stripping the BOM before we decode().
if contents.startswith(codecs.BOM_UTF8):
contents = contents[len(codecs.BOM_UTF8):]
# TODO(2.2): Remove when 2.3 becomes floor.
#contents = contents.decode('utf-8')
contents = my_decode(contents, 'utf-8')
elif contents.startswith(codecs.BOM_UTF16_LE):
contents = contents[len(codecs.BOM_UTF16_LE):]
# TODO(2.2): Remove when 2.3 becomes floor.
#contents = contents.decode('utf-16-le')
contents = my_decode(contents, 'utf-16-le')
elif contents.startswith(codecs.BOM_UTF16_BE):
contents = contents[len(codecs.BOM_UTF16_BE):]
# TODO(2.2): Remove when 2.3 becomes floor.
#contents = contents.decode('utf-16-be')
contents = my_decode(contents, 'utf-16-be')
return contents
def get_content_hash(self):
"""
Compute and return the MD5 hash for this file.
"""
if not self.rexists():
return SCons.Util.MD5signature('')
fname = self.rfile().abspath
try:
cs = SCons.Util.MD5filesignature(fname,
chunksize=SCons.Node.FS.File.md5_chunksize*1024)
except EnvironmentError, e:
if not e.filename:
e.filename = fname
raise
return cs
memoizer_counters.append(SCons.Memoize.CountValue('get_size'))
def get_size(self):
try:
return self._memo['get_size']
except KeyError:
pass
if self.rexists():
size = self.rfile().getsize()
else:
size = 0
self._memo['get_size'] = size
return size
memoizer_counters.append(SCons.Memoize.CountValue('get_timestamp'))
def get_timestamp(self):
try:
return self._memo['get_timestamp']
except KeyError:
pass
if self.rexists():
timestamp = self.rfile().getmtime()
else:
timestamp = 0
self._memo['get_timestamp'] = timestamp
return timestamp
def store_info(self):
# Merge our build information into the already-stored entry.
# This accomodates "chained builds" where a file that's a target
# in one build (SConstruct file) is a source in a different build.
# See test/chained-build.py for the use case.
if do_store_info:
self.dir.sconsign().store_info(self.name, self)
convert_copy_attrs = [
'bsources',
'bimplicit',
'bdepends',
'bact',
'bactsig',
'ninfo',
]
convert_sig_attrs = [
'bsourcesigs',
'bimplicitsigs',
'bdependsigs',
]
def convert_old_entry(self, old_entry):
# Convert a .sconsign entry from before the Big Signature
# Refactoring, doing what we can to convert its information
# to the new .sconsign entry format.
#
# The old format looked essentially like this:
#
# BuildInfo
# .ninfo (NodeInfo)
# .bsig
# .csig
# .timestamp
# .size
# .bsources
# .bsourcesigs ("signature" list)
# .bdepends
# .bdependsigs ("signature" list)
# .bimplicit
# .bimplicitsigs ("signature" list)
# .bact
# .bactsig
#
# The new format looks like this:
#
# .ninfo (NodeInfo)
# .bsig
# .csig
# .timestamp
# .size
# .binfo (BuildInfo)
# .bsources
# .bsourcesigs (NodeInfo list)
# .bsig
# .csig
# .timestamp
# .size
# .bdepends
# .bdependsigs (NodeInfo list)
# .bsig
# .csig
# .timestamp
# .size
# .bimplicit
# .bimplicitsigs (NodeInfo list)
# .bsig
# .csig
# .timestamp
# .size
# .bact
# .bactsig
#
# The basic idea of the new structure is that a NodeInfo always
# holds all available information about the state of a given Node
# at a certain point in time. The various .b*sigs lists can just
# be a list of pointers to the .ninfo attributes of the different
# dependent nodes, without any copying of information until it's
# time to pickle it for writing out to a .sconsign file.
#
# The complicating issue is that the *old* format only stored one
# "signature" per dependency, based on however the *last* build
# was configured. We don't know from just looking at it whether
# it was a build signature, a content signature, or a timestamp
# "signature". Since we no longer use build signatures, the
# best we can do is look at the length and if it's thirty two,
# assume that it was (or might have been) a content signature.
# If it was actually a build signature, then it will cause a
# rebuild anyway when it doesn't match the new content signature,
# but that's probably the best we can do.
import SCons.SConsign
new_entry = SCons.SConsign.SConsignEntry()
new_entry.binfo = self.new_binfo()
binfo = new_entry.binfo
for attr in self.convert_copy_attrs:
try:
value = getattr(old_entry, attr)
except AttributeError:
continue
setattr(binfo, attr, value)
delattr(old_entry, attr)
for attr in self.convert_sig_attrs:
try:
sig_list = getattr(old_entry, attr)
except AttributeError:
continue
value = []
for sig in sig_list:
ninfo = self.new_ninfo()
if len(sig) == 32:
ninfo.csig = sig
else:
ninfo.timestamp = sig
value.append(ninfo)
setattr(binfo, attr, value)
delattr(old_entry, attr)
return new_entry
memoizer_counters.append(SCons.Memoize.CountValue('get_stored_info'))
def get_stored_info(self):
try:
return self._memo['get_stored_info']
except KeyError:
pass
try:
sconsign_entry = self.dir.sconsign().get_entry(self.name)
except (KeyError, EnvironmentError):
import SCons.SConsign
sconsign_entry = SCons.SConsign.SConsignEntry()
sconsign_entry.binfo = self.new_binfo()
sconsign_entry.ninfo = self.new_ninfo()
else:
if isinstance(sconsign_entry, FileBuildInfo):
# This is a .sconsign file from before the Big Signature
# Refactoring; convert it as best we can.
sconsign_entry = self.convert_old_entry(sconsign_entry)
try:
delattr(sconsign_entry.ninfo, 'bsig')
except AttributeError:
pass
self._memo['get_stored_info'] = sconsign_entry
return sconsign_entry
def get_stored_implicit(self):
binfo = self.get_stored_info().binfo
binfo.prepare_dependencies()
try: return binfo.bimplicit
except AttributeError: return None
def rel_path(self, other):
return self.dir.rel_path(other)
def _get_found_includes_key(self, env, scanner, path):
return (id(env), id(scanner), path)
memoizer_counters.append(SCons.Memoize.CountDict('get_found_includes', _get_found_includes_key))
def get_found_includes(self, env, scanner, path):
"""Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested.
"""
memo_key = (id(env), id(scanner), path)
try:
memo_dict = self._memo['get_found_includes']
except KeyError:
memo_dict = {}
self._memo['get_found_includes'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
if scanner:
# result = [n.disambiguate() for n in scanner(self, env, path)]
result = scanner(self, env, path)
result = map(lambda N: N.disambiguate(), result)
else:
result = []
memo_dict[memo_key] = result
return result
def _createDir(self):
# ensure that the directories for this node are
# created.
self.dir._create()
def push_to_cache(self):
"""Try to push the node into a cache
"""
# This should get called before the Nodes' .built() method is
# called, which would clear the build signature if the file has
# a source scanner.
#
# We have to clear the local memoized values *before* we push
# the node to cache so that the memoization of the self.exists()
# return value doesn't interfere.
if self.nocache:
return
self.clear_memoized_values()
if self.exists():
self.get_build_env().get_CacheDir().push(self)
def retrieve_from_cache(self):
"""Try to retrieve the node's content from a cache
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff in
built().
Returns true iff the node was successfully retrieved.
"""
if self.nocache:
return None
if not self.is_derived():
return None
return self.get_build_env().get_CacheDir().retrieve(self)
def visited(self):
if self.exists():
self.get_build_env().get_CacheDir().push_if_forced(self)
ninfo = self.get_ninfo()
csig = self.get_max_drift_csig()
if csig:
ninfo.csig = csig
ninfo.timestamp = self.get_timestamp()
ninfo.size = self.get_size()
if not self.has_builder():
# This is a source file, but it might have been a target file
# in another build that included more of the DAG. Copy
# any build information that's stored in the .sconsign file
# into our binfo object so it doesn't get lost.
old = self.get_stored_info()
self.get_binfo().__dict__.update(old.binfo.__dict__)
self.store_info()
def find_src_builder(self):
if self.rexists():
return None
scb = self.dir.src_builder()
if scb is _null:
if diskcheck_sccs(self.dir, self.name):
scb = get_DefaultSCCSBuilder()
elif diskcheck_rcs(self.dir, self.name):
scb = get_DefaultRCSBuilder()
else:
scb = None
if scb is not None:
try:
b = self.builder
except AttributeError:
b = None
if b is None:
self.builder_set(scb)
return scb
def has_src_builder(self):
"""Return whether this Node has a source builder or not.
If this Node doesn't have an explicit source code builder, this
is where we figure out, on the fly, if there's a transparent
source code builder for it.
Note that if we found a source builder, we also set the
self.builder attribute, so that all of the methods that actually
*build* this file don't have to do anything different.
"""
try:
scb = self.sbuilder
except AttributeError:
scb = self.sbuilder = self.find_src_builder()
return scb is not None
def alter_targets(self):
"""Return any corresponding targets in a variant directory.
"""
if self.is_derived():
return [], None
return self.fs.variant_dir_target_climb(self, self.dir, [self.name])
def _rmv_existing(self):
self.clear_memoized_values()
e = Unlink(self, [], None)
if isinstance(e, SCons.Errors.BuildError):
raise e
#
# Taskmaster interface subsystem
#
def make_ready(self):
self.has_src_builder()
self.get_binfo()
def prepare(self):
"""Prepare for this file to be created."""
SCons.Node.Node.prepare(self)
if self.get_state() != SCons.Node.up_to_date:
if self.exists():
if self.is_derived() and not self.precious:
self._rmv_existing()
else:
try:
self._createDir()
except SCons.Errors.StopError, drive:
desc = "No drive `%s' for target `%s'." % (drive, self)
raise SCons.Errors.StopError, desc
#
#
#
def remove(self):
"""Remove this file."""
if self.exists() or self.islink():
self.fs.unlink(self.path)
return 1
return None
def do_duplicate(self, src):
self._createDir()
Unlink(self, None, None)
e = Link(self, src, None)
if isinstance(e, SCons.Errors.BuildError):
desc = "Cannot duplicate `%s' in `%s': %s." % (src.path, self.dir.path, e.errstr)
raise SCons.Errors.StopError, desc
self.linked = 1
# The Link() action may or may not have actually
# created the file, depending on whether the -n
# option was used or not. Delete the _exists and
# _rexists attributes so they can be reevaluated.
self.clear()
memoizer_counters.append(SCons.Memoize.CountValue('exists'))
def exists(self):
try:
return self._memo['exists']
except KeyError:
pass
# Duplicate from source path if we are set up to do this.
if self.duplicate and not self.is_derived() and not self.linked:
src = self.srcnode()
if src is not self:
# At this point, src is meant to be copied in a variant directory.
src = src.rfile()
if src.abspath != self.abspath:
if src.exists():
self.do_duplicate(src)
# Can't return 1 here because the duplication might
# not actually occur if the -n option is being used.
else:
# The source file does not exist. Make sure no old
# copy remains in the variant directory.
if Base.exists(self) or self.islink():
self.fs.unlink(self.path)
# Return None explicitly because the Base.exists() call
# above will have cached its value if the file existed.
self._memo['exists'] = None
return None
result = Base.exists(self)
self._memo['exists'] = result
return result
#
# SIGNATURE SUBSYSTEM
#
def get_max_drift_csig(self):
"""
Returns the content signature currently stored for this node
if it's been unmodified longer than the max_drift value, or the
max_drift value is 0. Returns None otherwise.
"""
old = self.get_stored_info()
mtime = self.get_timestamp()
max_drift = self.fs.max_drift
if max_drift > 0:
if (time.time() - mtime) > max_drift:
try:
n = old.ninfo
if n.timestamp and n.csig and n.timestamp == mtime:
return n.csig
except AttributeError:
pass
elif max_drift == 0:
try:
return old.ninfo.csig
except AttributeError:
pass
return None
def get_csig(self):
"""
Generate a node's content signature, the digested signature
of its content.
node - the node
cache - alternate node to use for the signature cache
returns - the content signature
"""
ninfo = self.get_ninfo()
try:
return ninfo.csig
except AttributeError:
pass
csig = self.get_max_drift_csig()
if csig is None:
try:
if self.get_size() < SCons.Node.FS.File.md5_chunksize:
contents = self.get_contents()
else:
csig = self.get_content_hash()
except IOError:
# This can happen if there's actually a directory on-disk,
# which can be the case if they've disabled disk checks,
# or if an action with a File target actually happens to
# create a same-named directory by mistake.
csig = ''
else:
if not csig:
csig = SCons.Util.MD5signature(contents)
ninfo.csig = csig
return csig
#
# DECISION SUBSYSTEM
#
def builder_set(self, builder):
SCons.Node.Node.builder_set(self, builder)
self.changed_since_last_build = self.decide_target
def changed_content(self, target, prev_ni):
cur_csig = self.get_csig()
try:
return cur_csig != prev_ni.csig
except AttributeError:
return 1
def changed_state(self, target, prev_ni):
return self.state != SCons.Node.up_to_date
def changed_timestamp_then_content(self, target, prev_ni):
if not self.changed_timestamp_match(target, prev_ni):
try:
self.get_ninfo().csig = prev_ni.csig
except AttributeError:
pass
return False
return self.changed_content(target, prev_ni)
def changed_timestamp_newer(self, target, prev_ni):
try:
return self.get_timestamp() > target.get_timestamp()
except AttributeError:
return 1
def changed_timestamp_match(self, target, prev_ni):
try:
return self.get_timestamp() != prev_ni.timestamp
except AttributeError:
return 1
def decide_source(self, target, prev_ni):
return target.get_build_env().decide_source(self, target, prev_ni)
def decide_target(self, target, prev_ni):
return target.get_build_env().decide_target(self, target, prev_ni)
# Initialize this Node's decider function to decide_source() because
# every file is a source file until it has a Builder attached...
changed_since_last_build = decide_source
def is_up_to_date(self):
T = 0
if T: Trace('is_up_to_date(%s):' % self)
if not self.exists():
if T: Trace(' not self.exists():')
# The file doesn't exist locally...
r = self.rfile()
if r != self:
# ...but there is one in a Repository...
if not self.changed(r):
if T: Trace(' changed(%s):' % r)
# ...and it's even up-to-date...
if self._local:
# ...and they'd like a local copy.
e = LocalCopy(self, r, None)
if isinstance(e, SCons.Errors.BuildError):
raise
self.store_info()
if T: Trace(' 1\n')
return 1
self.changed()
if T: Trace(' None\n')
return None
else:
r = self.changed()
if T: Trace(' self.exists(): %s\n' % r)
return not r
memoizer_counters.append(SCons.Memoize.CountValue('rfile'))
def rfile(self):
try:
return self._memo['rfile']
except KeyError:
pass
result = self
if not self.exists():
norm_name = _my_normcase(self.name)
for dir in self.dir.get_all_rdirs():
try: node = dir.entries[norm_name]
except KeyError: node = dir.file_on_disk(self.name)
if node and node.exists() and \
(isinstance(node, File) or isinstance(node, Entry) \
or not node.is_derived()):
result = node
# Copy over our local attributes to the repository
# Node so we identify shared object files in the
# repository and don't assume they're static.
#
# This isn't perfect; the attribute would ideally
# be attached to the object in the repository in
# case it was built statically in the repository
# and we changed it to shared locally, but that's
# rarely the case and would only occur if you
# intentionally used the same suffix for both
# shared and static objects anyway. So this
# should work well in practice.
result.attributes = self.attributes
break
self._memo['rfile'] = result
return result
def rstr(self):
return str(self.rfile())
def get_cachedir_csig(self):
"""
Fetch a Node's content signature for purposes of computing
another Node's cachesig.
This is a wrapper around the normal get_csig() method that handles
the somewhat obscure case of using CacheDir with the -n option.
Any files that don't exist would normally be "built" by fetching
them from the cache, but the normal get_csig() method will try
to open up the local file, which doesn't exist because the -n
option meant we didn't actually pull the file from cachedir.
But since the file *does* actually exist in the cachedir, we
can use its contents for the csig.
"""
try:
return self.cachedir_csig
except AttributeError:
pass
cachedir, cachefile = self.get_build_env().get_CacheDir().cachepath(self)
if not self.exists() and cachefile and os.path.exists(cachefile):
self.cachedir_csig = SCons.Util.MD5filesignature(cachefile, \
SCons.Node.FS.File.md5_chunksize * 1024)
else:
self.cachedir_csig = self.get_csig()
return self.cachedir_csig
def get_cachedir_bsig(self):
try:
return self.cachesig
except AttributeError:
pass
# Add the path to the cache signature, because multiple
# targets built by the same action will all have the same
# build signature, and we have to differentiate them somehow.
children = self.children()
executor = self.get_executor()
# sigs = [n.get_cachedir_csig() for n in children]
sigs = map(lambda n: n.get_cachedir_csig(), children)
sigs.append(SCons.Util.MD5signature(executor.get_contents()))
sigs.append(self.path)
result = self.cachesig = SCons.Util.MD5collect(sigs)
return result
default_fs = None
def get_default_fs():
global default_fs
if not default_fs:
default_fs = FS()
return default_fs
class FileFinder:
"""
"""
if SCons.Memoize.use_memoizer:
__metaclass__ = SCons.Memoize.Memoized_Metaclass
memoizer_counters = []
def __init__(self):
self._memo = {}
def filedir_lookup(self, p, fd=None):
"""
A helper method for find_file() that looks up a directory for
a file we're trying to find. This only creates the Dir Node if
it exists on-disk, since if the directory doesn't exist we know
we won't find any files in it... :-)
It would be more compact to just use this as a nested function
with a default keyword argument (see the commented-out version
below), but that doesn't work unless you have nested scopes,
so we define it here just so this work under Python 1.5.2.
"""
if fd is None:
fd = self.default_filedir
dir, name = os.path.split(fd)
drive, d = os.path.splitdrive(dir)
if not name and d[:1] in ('/', os.sep):
#return p.fs.get_root(drive).dir_on_disk(name)
return p.fs.get_root(drive)
if dir:
p = self.filedir_lookup(p, dir)
if not p:
return None
norm_name = _my_normcase(name)
try:
node = p.entries[norm_name]
except KeyError:
return p.dir_on_disk(name)
if isinstance(node, Dir):
return node
if isinstance(node, Entry):
node.must_be_same(Dir)
return node
return None
def _find_file_key(self, filename, paths, verbose=None):
return (filename, paths)
memoizer_counters.append(SCons.Memoize.CountDict('find_file', _find_file_key))
def find_file(self, filename, paths, verbose=None):
"""
find_file(str, [Dir()]) -> [nodes]
filename - a filename to find
paths - a list of directory path *nodes* to search in. Can be
represented as a list, a tuple, or a callable that is
called with no arguments and returns the list or tuple.
returns - the node created from the found file.
Find a node corresponding to either a derived file or a file
that exists already.
Only the first file found is returned, and none is returned
if no file is found.
"""
memo_key = self._find_file_key(filename, paths)
try:
memo_dict = self._memo['find_file']
except KeyError:
memo_dict = {}
self._memo['find_file'] = memo_dict
else:
try:
return memo_dict[memo_key]
except KeyError:
pass
if verbose and not callable(verbose):
if not SCons.Util.is_String(verbose):
verbose = "find_file"
verbose = ' %s: ' % verbose
verbose = lambda s, v=verbose: sys.stdout.write(v + s)
filedir, filename = os.path.split(filename)
if filedir:
# More compact code that we can't use until we drop
# support for Python 1.5.2:
#
#def filedir_lookup(p, fd=filedir):
# """
# A helper function that looks up a directory for a file
# we're trying to find. This only creates the Dir Node
# if it exists on-disk, since if the directory doesn't
# exist we know we won't find any files in it... :-)
# """
# dir, name = os.path.split(fd)
# if dir:
# p = filedir_lookup(p, dir)
# if not p:
# return None
# norm_name = _my_normcase(name)
# try:
# node = p.entries[norm_name]
# except KeyError:
# return p.dir_on_disk(name)
# if isinstance(node, Dir):
# return node
# if isinstance(node, Entry):
# node.must_be_same(Dir)
# return node
# if isinstance(node, Dir) or isinstance(node, Entry):
# return node
# return None
#paths = filter(None, map(filedir_lookup, paths))
self.default_filedir = filedir
paths = filter(None, map(self.filedir_lookup, paths))
result = None
for dir in paths:
if verbose:
verbose("looking for '%s' in '%s' ...\n" % (filename, dir))
node, d = dir.srcdir_find_file(filename)
if node:
if verbose:
verbose("... FOUND '%s' in '%s'\n" % (filename, d))
result = node
break
memo_dict[memo_key] = result
return result
find_file = FileFinder().find_file
def invalidate_node_memos(targets):
"""
Invalidate the memoized values of all Nodes (files or directories)
that are associated with the given entries. Has been added to
clear the cache of nodes affected by a direct execution of an
action (e.g. Delete/Copy/Chmod). Existing Node caches become
inconsistent if the action is run through Execute(). The argument
`targets` can be a single Node object or filename, or a sequence
of Nodes/filenames.
"""
from traceback import extract_stack
# First check if the cache really needs to be flushed. Only
# actions run in the SConscript with Execute() seem to be
# affected. XXX The way to check if Execute() is in the stacktrace
# is a very dirty hack and should be replaced by a more sensible
# solution.
for f in extract_stack():
if f[2] == 'Execute' and f[0][-14:] == 'Environment.py':
break
else:
# Dont have to invalidate, so return
return
if not SCons.Util.is_List(targets):
targets = [targets]
for entry in targets:
# If the target is a Node object, clear the cache. If it is a
# filename, look up potentially existing Node object first.
try:
entry.clear_memoized_values()
except AttributeError:
# Not a Node object, try to look up Node by filename. XXX
# This creates Node objects even for those filenames which
# do not correspond to an existing Node object.
node = get_default_fs().Entry(entry)
if node:
node.clear_memoized_values()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Node
The Node package for the SCons software construction utility.
This is, in many ways, the heart of SCons.
A Node is where we encapsulate all of the dependency information about
any thing that SCons can build, or about any thing which SCons can use
to build some other thing. The canonical "thing," of course, is a file,
but a Node can also represent something remote (like a web page) or
something completely abstract (like an Alias).
Each specific type of "thing" is specifically represented by a subclass
of the Node base class: Node.FS.File for files, Node.Alias for aliases,
etc. Dependency information is kept here in the base class, and
information specific to files/aliases/etc. is in the subclass. The
goal, if we've done this correctly, is that any type of "thing" should
be able to depend on any other type of "thing."
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Node/__init__.py 4720 2010/03/24 03:14:11 jars"
import copy
from itertools import chain, izip
import string
import UserList
from SCons.Debug import logInstanceCreation
import SCons.Executor
import SCons.Memoize
import SCons.Util
from SCons.Debug import Trace
def classname(obj):
return string.split(str(obj.__class__), '.')[-1]
# Node states
#
# These are in "priority" order, so that the maximum value for any
# child/dependency of a node represents the state of that node if
# it has no builder of its own. The canonical example is a file
# system directory, which is only up to date if all of its children
# were up to date.
no_state = 0
pending = 1
executing = 2
up_to_date = 3
executed = 4
failed = 5
StateString = {
0 : "no_state",
1 : "pending",
2 : "executing",
3 : "up_to_date",
4 : "executed",
5 : "failed",
}
# controls whether implicit dependencies are cached:
implicit_cache = 0
# controls whether implicit dep changes are ignored:
implicit_deps_unchanged = 0
# controls whether the cached implicit deps are ignored:
implicit_deps_changed = 0
# A variable that can be set to an interface-specific function be called
# to annotate a Node with information about its creation.
def do_nothing(node): pass
Annotate = do_nothing
# Classes for signature info for Nodes.
class NodeInfoBase:
"""
The generic base class for signature information for a Node.
Node subclasses should subclass NodeInfoBase to provide their own
logic for dealing with their own Node-specific signature information.
"""
current_version_id = 1
def __init__(self, node):
# Create an object attribute from the class attribute so it ends up
# in the pickled data in the .sconsign file.
self._version_id = self.current_version_id
def update(self, node):
try:
field_list = self.field_list
except AttributeError:
return
for f in field_list:
try:
delattr(self, f)
except AttributeError:
pass
try:
func = getattr(node, 'get_' + f)
except AttributeError:
pass
else:
setattr(self, f, func())
def convert(self, node, val):
pass
def merge(self, other):
self.__dict__.update(other.__dict__)
def format(self, field_list=None, names=0):
if field_list is None:
try:
field_list = self.field_list
except AttributeError:
field_list = self.__dict__.keys()
field_list.sort()
fields = []
for field in field_list:
try:
f = getattr(self, field)
except AttributeError:
f = None
f = str(f)
if names:
f = field + ': ' + f
fields.append(f)
return fields
class BuildInfoBase:
"""
The generic base class for build information for a Node.
This is what gets stored in a .sconsign file for each target file.
It contains a NodeInfo instance for this node (signature information
that's specific to the type of Node) and direct attributes for the
generic build stuff we have to track: sources, explicit dependencies,
implicit dependencies, and action information.
"""
current_version_id = 1
def __init__(self, node):
# Create an object attribute from the class attribute so it ends up
# in the pickled data in the .sconsign file.
self._version_id = self.current_version_id
self.bsourcesigs = []
self.bdependsigs = []
self.bimplicitsigs = []
self.bactsig = None
def merge(self, other):
self.__dict__.update(other.__dict__)
class Node:
"""The base Node class, for entities that we know how to
build, or use to build other Nodes.
"""
if SCons.Memoize.use_memoizer:
__metaclass__ = SCons.Memoize.Memoized_Metaclass
memoizer_counters = []
class Attrs:
pass
def __init__(self):
if __debug__: logInstanceCreation(self, 'Node.Node')
# Note that we no longer explicitly initialize a self.builder
# attribute to None here. That's because the self.builder
# attribute may be created on-the-fly later by a subclass (the
# canonical example being a builder to fetch a file from a
# source code system like CVS or Subversion).
# Each list of children that we maintain is accompanied by a
# dictionary used to look up quickly whether a node is already
# present in the list. Empirical tests showed that it was
# fastest to maintain them as side-by-side Node attributes in
# this way, instead of wrapping up each list+dictionary pair in
# a class. (Of course, we could always still do that in the
# future if we had a good reason to...).
self.sources = [] # source files used to build node
self.sources_set = set()
self._specific_sources = False
self.depends = [] # explicit dependencies (from Depends)
self.depends_set = set()
self.ignore = [] # dependencies to ignore
self.ignore_set = set()
self.prerequisites = SCons.Util.UniqueList()
self.implicit = None # implicit (scanned) dependencies (None means not scanned yet)
self.waiting_parents = set()
self.waiting_s_e = set()
self.ref_count = 0
self.wkids = None # Kids yet to walk, when it's an array
self.env = None
self.state = no_state
self.precious = None
self.noclean = 0
self.nocache = 0
self.always_build = None
self.includes = None
self.attributes = self.Attrs() # Generic place to stick information about the Node.
self.side_effect = 0 # true iff this node is a side effect
self.side_effects = [] # the side effects of building this target
self.linked = 0 # is this node linked to the variant directory?
self.clear_memoized_values()
# Let the interface in which the build engine is embedded
# annotate this Node with its own info (like a description of
# what line in what file created the node, for example).
Annotate(self)
def disambiguate(self, must_exist=None):
return self
def get_suffix(self):
return ''
memoizer_counters.append(SCons.Memoize.CountValue('get_build_env'))
def get_build_env(self):
"""Fetch the appropriate Environment to build this node.
"""
try:
return self._memo['get_build_env']
except KeyError:
pass
result = self.get_executor().get_build_env()
self._memo['get_build_env'] = result
return result
def get_build_scanner_path(self, scanner):
"""Fetch the appropriate scanner path for this node."""
return self.get_executor().get_build_scanner_path(scanner)
def set_executor(self, executor):
"""Set the action executor for this node."""
self.executor = executor
def get_executor(self, create=1):
"""Fetch the action executor for this node. Create one if
there isn't already one, and requested to do so."""
try:
executor = self.executor
except AttributeError:
if not create:
raise
try:
act = self.builder.action
except AttributeError:
executor = SCons.Executor.Null(targets=[self])
else:
executor = SCons.Executor.Executor(act,
self.env or self.builder.env,
[self.builder.overrides],
[self],
self.sources)
self.executor = executor
return executor
def executor_cleanup(self):
"""Let the executor clean up any cached information."""
try:
executor = self.get_executor(create=None)
except AttributeError:
pass
else:
executor.cleanup()
def reset_executor(self):
"Remove cached executor; forces recompute when needed."
try:
delattr(self, 'executor')
except AttributeError:
pass
def push_to_cache(self):
"""Try to push a node into a cache
"""
pass
def retrieve_from_cache(self):
"""Try to retrieve the node's content from a cache
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff in
built().
Returns true iff the node was successfully retrieved.
"""
return 0
#
# Taskmaster interface subsystem
#
def make_ready(self):
"""Get a Node ready for evaluation.
This is called before the Taskmaster decides if the Node is
up-to-date or not. Overriding this method allows for a Node
subclass to be disambiguated if necessary, or for an implicit
source builder to be attached.
"""
pass
def prepare(self):
"""Prepare for this Node to be built.
This is called after the Taskmaster has decided that the Node
is out-of-date and must be rebuilt, but before actually calling
the method to build the Node.
This default implementation checks that explicit or implicit
dependencies either exist or are derived, and initializes the
BuildInfo structure that will hold the information about how
this node is, uh, built.
(The existence of source files is checked separately by the
Executor, which aggregates checks for all of the targets built
by a specific action.)
Overriding this method allows for for a Node subclass to remove
the underlying file from the file system. Note that subclass
methods should call this base class method to get the child
check and the BuildInfo structure.
"""
for d in self.depends:
if d.missing():
msg = "Explicit dependency `%s' not found, needed by target `%s'."
raise SCons.Errors.StopError, msg % (d, self)
if self.implicit is not None:
for i in self.implicit:
if i.missing():
msg = "Implicit dependency `%s' not found, needed by target `%s'."
raise SCons.Errors.StopError, msg % (i, self)
self.binfo = self.get_binfo()
def build(self, **kw):
"""Actually build the node.
This is called by the Taskmaster after it's decided that the
Node is out-of-date and must be rebuilt, and after the prepare()
method has gotten everything, uh, prepared.
This method is called from multiple threads in a parallel build,
so only do thread safe stuff here. Do thread unsafe stuff
in built().
"""
try:
apply(self.get_executor(), (self,), kw)
except SCons.Errors.BuildError, e:
e.node = self
raise
def built(self):
"""Called just after this node is successfully built."""
# Clear the implicit dependency caches of any Nodes
# waiting for this Node to be built.
for parent in self.waiting_parents:
parent.implicit = None
self.clear()
self.ninfo.update(self)
def visited(self):
"""Called just after this node has been visited (with or
without a build)."""
try:
binfo = self.binfo
except AttributeError:
# Apparently this node doesn't need build info, so
# don't bother calculating or storing it.
pass
else:
self.ninfo.update(self)
self.store_info()
#
#
#
def add_to_waiting_s_e(self, node):
self.waiting_s_e.add(node)
def add_to_waiting_parents(self, node):
"""
Returns the number of nodes added to our waiting parents list:
1 if we add a unique waiting parent, 0 if not. (Note that the
returned values are intended to be used to increment a reference
count, so don't think you can "clean up" this function by using
True and False instead...)
"""
wp = self.waiting_parents
if node in wp:
return 0
wp.add(node)
return 1
def postprocess(self):
"""Clean up anything we don't need to hang onto after we've
been built."""
self.executor_cleanup()
self.waiting_parents = set()
def clear(self):
"""Completely clear a Node of all its cached state (so that it
can be re-evaluated by interfaces that do continuous integration
builds).
"""
# The del_binfo() call here isn't necessary for normal execution,
# but is for interactive mode, where we might rebuild the same
# target and need to start from scratch.
self.del_binfo()
self.clear_memoized_values()
self.ninfo = self.new_ninfo()
self.executor_cleanup()
try:
delattr(self, '_calculated_sig')
except AttributeError:
pass
self.includes = None
def clear_memoized_values(self):
self._memo = {}
def builder_set(self, builder):
self.builder = builder
try:
del self.executor
except AttributeError:
pass
def has_builder(self):
"""Return whether this Node has a builder or not.
In Boolean tests, this turns out to be a *lot* more efficient
than simply examining the builder attribute directly ("if
node.builder: ..."). When the builder attribute is examined
directly, it ends up calling __getattr__ for both the __len__
and __nonzero__ attributes on instances of our Builder Proxy
class(es), generating a bazillion extra calls and slowing
things down immensely.
"""
try:
b = self.builder
except AttributeError:
# There was no explicit builder for this Node, so initialize
# the self.builder attribute to None now.
b = self.builder = None
return b is not None
def set_explicit(self, is_explicit):
self.is_explicit = is_explicit
def has_explicit_builder(self):
"""Return whether this Node has an explicit builder
This allows an internal Builder created by SCons to be marked
non-explicit, so that it can be overridden by an explicit
builder that the user supplies (the canonical example being
directories)."""
try:
return self.is_explicit
except AttributeError:
self.is_explicit = None
return self.is_explicit
def get_builder(self, default_builder=None):
"""Return the set builder, or a specified default value"""
try:
return self.builder
except AttributeError:
return default_builder
multiple_side_effect_has_builder = has_builder
def is_derived(self):
"""
Returns true iff this node is derived (i.e. built).
This should return true only for nodes whose path should be in
the variant directory when duplicate=0 and should contribute their build
signatures when they are used as source files to other derived files. For
example: source with source builders are not derived in this sense,
and hence should not return true.
"""
return self.has_builder() or self.side_effect
def alter_targets(self):
"""Return a list of alternate targets for this Node.
"""
return [], None
def get_found_includes(self, env, scanner, path):
"""Return the scanned include lines (implicit dependencies)
found in this node.
The default is no implicit dependencies. We expect this method
to be overridden by any subclass that can be scanned for
implicit dependencies.
"""
return []
def get_implicit_deps(self, env, scanner, path):
"""Return a list of implicit dependencies for this node.
This method exists to handle recursive invocation of the scanner
on the implicit dependencies returned by the scanner, if the
scanner's recursive flag says that we should.
"""
if not scanner:
return []
# Give the scanner a chance to select a more specific scanner
# for this Node.
#scanner = scanner.select(self)
nodes = [self]
seen = {}
seen[self] = 1
deps = []
while nodes:
n = nodes.pop(0)
d = filter(lambda x, seen=seen: not seen.has_key(x),
n.get_found_includes(env, scanner, path))
if d:
deps.extend(d)
for n in d:
seen[n] = 1
nodes.extend(scanner.recurse_nodes(d))
return deps
def get_env_scanner(self, env, kw={}):
return env.get_scanner(self.scanner_key())
def get_target_scanner(self):
return self.builder.target_scanner
def get_source_scanner(self, node):
"""Fetch the source scanner for the specified node
NOTE: "self" is the target being built, "node" is
the source file for which we want to fetch the scanner.
Implies self.has_builder() is true; again, expect to only be
called from locations where this is already verified.
This function may be called very often; it attempts to cache
the scanner found to improve performance.
"""
scanner = None
try:
scanner = self.builder.source_scanner
except AttributeError:
pass
if not scanner:
# The builder didn't have an explicit scanner, so go look up
# a scanner from env['SCANNERS'] based on the node's scanner
# key (usually the file extension).
scanner = self.get_env_scanner(self.get_build_env())
if scanner:
scanner = scanner.select(node)
return scanner
def add_to_implicit(self, deps):
if not hasattr(self, 'implicit') or self.implicit is None:
self.implicit = []
self.implicit_set = set()
self._children_reset()
self._add_child(self.implicit, self.implicit_set, deps)
def scan(self):
"""Scan this node's dependents for implicit dependencies."""
# Don't bother scanning non-derived files, because we don't
# care what their dependencies are.
# Don't scan again, if we already have scanned.
if self.implicit is not None:
return
self.implicit = []
self.implicit_set = set()
self._children_reset()
if not self.has_builder():
return
build_env = self.get_build_env()
executor = self.get_executor()
# Here's where we implement --implicit-cache.
if implicit_cache and not implicit_deps_changed:
implicit = self.get_stored_implicit()
if implicit is not None:
# We now add the implicit dependencies returned from the
# stored .sconsign entry to have already been converted
# to Nodes for us. (We used to run them through a
# source_factory function here.)
# Update all of the targets with them. This
# essentially short-circuits an N*M scan of the
# sources for each individual target, which is a hell
# of a lot more efficient.
for tgt in executor.get_all_targets():
tgt.add_to_implicit(implicit)
if implicit_deps_unchanged or self.is_up_to_date():
return
# one of this node's sources has changed,
# so we must recalculate the implicit deps:
self.implicit = []
self.implicit_set = set()
# Have the executor scan the sources.
executor.scan_sources(self.builder.source_scanner)
# If there's a target scanner, have the executor scan the target
# node itself and associated targets that might be built.
scanner = self.get_target_scanner()
if scanner:
executor.scan_targets(scanner)
def scanner_key(self):
return None
def select_scanner(self, scanner):
"""Selects a scanner for this Node.
This is a separate method so it can be overridden by Node
subclasses (specifically, Node.FS.Dir) that *must* use their
own Scanner and don't select one the Scanner.Selector that's
configured for the target.
"""
return scanner.select(self)
def env_set(self, env, safe=0):
if safe and self.env:
return
self.env = env
#
# SIGNATURE SUBSYSTEM
#
NodeInfo = NodeInfoBase
BuildInfo = BuildInfoBase
def new_ninfo(self):
ninfo = self.NodeInfo(self)
return ninfo
def get_ninfo(self):
try:
return self.ninfo
except AttributeError:
self.ninfo = self.new_ninfo()
return self.ninfo
def new_binfo(self):
binfo = self.BuildInfo(self)
return binfo
def get_binfo(self):
"""
Fetch a node's build information.
node - the node whose sources will be collected
cache - alternate node to use for the signature cache
returns - the build signature
This no longer handles the recursive descent of the
node's children's signatures. We expect that they're
already built and updated by someone else, if that's
what's wanted.
"""
try:
return self.binfo
except AttributeError:
pass
binfo = self.new_binfo()
self.binfo = binfo
executor = self.get_executor()
ignore_set = self.ignore_set
if self.has_builder():
binfo.bact = str(executor)
binfo.bactsig = SCons.Util.MD5signature(executor.get_contents())
if self._specific_sources:
sources = []
for s in self.sources:
if s not in ignore_set:
sources.append(s)
else:
sources = executor.get_unignored_sources(self, self.ignore)
seen = set()
bsources = []
bsourcesigs = []
for s in sources:
if not s in seen:
seen.add(s)
bsources.append(s)
bsourcesigs.append(s.get_ninfo())
binfo.bsources = bsources
binfo.bsourcesigs = bsourcesigs
depends = self.depends
dependsigs = []
for d in depends:
if d not in ignore_set:
dependsigs.append(d.get_ninfo())
binfo.bdepends = depends
binfo.bdependsigs = dependsigs
implicit = self.implicit or []
implicitsigs = []
for i in implicit:
if i not in ignore_set:
implicitsigs.append(i.get_ninfo())
binfo.bimplicit = implicit
binfo.bimplicitsigs = implicitsigs
return binfo
def del_binfo(self):
"""Delete the build info from this node."""
try:
delattr(self, 'binfo')
except AttributeError:
pass
def get_csig(self):
try:
return self.ninfo.csig
except AttributeError:
ninfo = self.get_ninfo()
ninfo.csig = SCons.Util.MD5signature(self.get_contents())
return self.ninfo.csig
def get_cachedir_csig(self):
return self.get_csig()
def store_info(self):
"""Make the build signature permanent (that is, store it in the
.sconsign file or equivalent)."""
pass
def do_not_store_info(self):
pass
def get_stored_info(self):
return None
def get_stored_implicit(self):
"""Fetch the stored implicit dependencies"""
return None
#
#
#
def set_precious(self, precious = 1):
"""Set the Node's precious value."""
self.precious = precious
def set_noclean(self, noclean = 1):
"""Set the Node's noclean value."""
# Make sure noclean is an integer so the --debug=stree
# output in Util.py can use it as an index.
self.noclean = noclean and 1 or 0
def set_nocache(self, nocache = 1):
"""Set the Node's nocache value."""
# Make sure nocache is an integer so the --debug=stree
# output in Util.py can use it as an index.
self.nocache = nocache and 1 or 0
def set_always_build(self, always_build = 1):
"""Set the Node's always_build value."""
self.always_build = always_build
def exists(self):
"""Does this node exists?"""
# All node exist by default:
return 1
def rexists(self):
"""Does this node exist locally or in a repositiory?"""
# There are no repositories by default:
return self.exists()
def missing(self):
return not self.is_derived() and \
not self.linked and \
not self.rexists()
def remove(self):
"""Remove this Node: no-op by default."""
return None
def add_dependency(self, depend):
"""Adds dependencies."""
try:
self._add_child(self.depends, self.depends_set, depend)
except TypeError, e:
e = e.args[0]
if SCons.Util.is_List(e):
s = map(str, e)
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
def add_prerequisite(self, prerequisite):
"""Adds prerequisites"""
self.prerequisites.extend(prerequisite)
self._children_reset()
def add_ignore(self, depend):
"""Adds dependencies to ignore."""
try:
self._add_child(self.ignore, self.ignore_set, depend)
except TypeError, e:
e = e.args[0]
if SCons.Util.is_List(e):
s = map(str, e)
else:
s = str(e)
raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
def add_source(self, source):
"""Adds sources."""
if self._specific_sources:
return
try:
self._add_child(self.sources, self.sources_set, source)
except TypeError, e:
e = e.args[0]
if SCons.Util.is_List(e):
s = map(str, e)
else:
s = str(e)
raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
def _add_child(self, collection, set, child):
"""Adds 'child' to 'collection', first checking 'set' to see if it's
already present."""
#if type(child) is not type([]):
# child = [child]
#for c in child:
# if not isinstance(c, Node):
# raise TypeError, c
added = None
for c in child:
if c not in set:
set.add(c)
collection.append(c)
added = 1
if added:
self._children_reset()
def set_specific_source(self, source):
self.add_source(source)
self._specific_sources = True
def add_wkid(self, wkid):
"""Add a node to the list of kids waiting to be evaluated"""
if self.wkids is not None:
self.wkids.append(wkid)
def _children_reset(self):
self.clear_memoized_values()
# We need to let the Executor clear out any calculated
# build info that it's cached so we can re-calculate it.
self.executor_cleanup()
memoizer_counters.append(SCons.Memoize.CountValue('_children_get'))
def _children_get(self):
try:
return self._memo['children_get']
except KeyError:
pass
# The return list may contain duplicate Nodes, especially in
# source trees where there are a lot of repeated #includes
# of a tangle of .h files. Profiling shows, however, that
# eliminating the duplicates with a brute-force approach that
# preserves the order (that is, something like:
#
# u = []
# for n in list:
# if n not in u:
# u.append(n)"
#
# takes more cycles than just letting the underlying methods
# hand back cached values if a Node's information is requested
# multiple times. (Other methods of removing duplicates, like
# using dictionary keys, lose the order, and the only ordered
# dictionary patterns I found all ended up using "not in"
# internally anyway...)
if self.ignore_set:
if self.implicit is None:
iter = chain(self.sources,self.depends)
else:
iter = chain(self.sources, self.depends, self.implicit)
children = []
for i in iter:
if i not in self.ignore_set:
children.append(i)
else:
if self.implicit is None:
children = self.sources + self.depends
else:
children = self.sources + self.depends + self.implicit
self._memo['children_get'] = children
return children
def all_children(self, scan=1):
"""Return a list of all the node's direct children."""
if scan:
self.scan()
# The return list may contain duplicate Nodes, especially in
# source trees where there are a lot of repeated #includes
# of a tangle of .h files. Profiling shows, however, that
# eliminating the duplicates with a brute-force approach that
# preserves the order (that is, something like:
#
# u = []
# for n in list:
# if n not in u:
# u.append(n)"
#
# takes more cycles than just letting the underlying methods
# hand back cached values if a Node's information is requested
# multiple times. (Other methods of removing duplicates, like
# using dictionary keys, lose the order, and the only ordered
# dictionary patterns I found all ended up using "not in"
# internally anyway...)
if self.implicit is None:
return self.sources + self.depends
else:
return self.sources + self.depends + self.implicit
def children(self, scan=1):
"""Return a list of the node's direct children, minus those
that are ignored by this node."""
if scan:
self.scan()
return self._children_get()
def set_state(self, state):
self.state = state
def get_state(self):
return self.state
def state_has_changed(self, target, prev_ni):
return (self.state != SCons.Node.up_to_date)
def get_env(self):
env = self.env
if not env:
import SCons.Defaults
env = SCons.Defaults.DefaultEnvironment()
return env
def changed_since_last_build(self, target, prev_ni):
"""
Must be overridden in a specific subclass to return True if this
Node (a dependency) has changed since the last time it was used
to build the specified target. prev_ni is this Node's state (for
example, its file timestamp, length, maybe content signature)
as of the last time the target was built.
Note that this method is called through the dependency, not the
target, because a dependency Node must be able to use its own
logic to decide if it changed. For example, File Nodes need to
obey if we're configured to use timestamps, but Python Value Nodes
never use timestamps and always use the content. If this method
were called through the target, then each Node's implementation
of this method would have to have more complicated logic to
handle all the different Node types on which it might depend.
"""
raise NotImplementedError
def Decider(self, function):
SCons.Util.AddMethod(self, function, 'changed_since_last_build')
def changed(self, node=None):
"""
Returns if the node is up-to-date with respect to the BuildInfo
stored last time it was built. The default behavior is to compare
it against our own previously stored BuildInfo, but the stored
BuildInfo from another Node (typically one in a Repository)
can be used instead.
Note that we now *always* check every dependency. We used to
short-circuit the check by returning as soon as we detected
any difference, but we now rely on checking every dependency
to make sure that any necessary Node information (for example,
the content signature of an #included .h file) is updated.
"""
t = 0
if t: Trace('changed(%s [%s], %s)' % (self, classname(self), node))
if node is None:
node = self
result = False
bi = node.get_stored_info().binfo
then = bi.bsourcesigs + bi.bdependsigs + bi.bimplicitsigs
children = self.children()
diff = len(children) - len(then)
if diff:
# The old and new dependency lists are different lengths.
# This always indicates that the Node must be rebuilt.
# We also extend the old dependency list with enough None
# entries to equal the new dependency list, for the benefit
# of the loop below that updates node information.
then.extend([None] * diff)
if t: Trace(': old %s new %s' % (len(then), len(children)))
result = True
for child, prev_ni in izip(children, then):
if child.changed_since_last_build(self, prev_ni):
if t: Trace(': %s changed' % child)
result = True
contents = self.get_executor().get_contents()
if self.has_builder():
import SCons.Util
newsig = SCons.Util.MD5signature(contents)
if bi.bactsig != newsig:
if t: Trace(': bactsig %s != newsig %s' % (bi.bactsig, newsig))
result = True
if not result:
if t: Trace(': up to date')
if t: Trace('\n')
return result
def is_up_to_date(self):
"""Default check for whether the Node is current: unknown Node
subtypes are always out of date, so they will always get built."""
return None
def children_are_up_to_date(self):
"""Alternate check for whether the Node is current: If all of
our children were up-to-date, then this Node was up-to-date, too.
The SCons.Node.Alias and SCons.Node.Python.Value subclasses
rebind their current() method to this method."""
# Allow the children to calculate their signatures.
self.binfo = self.get_binfo()
if self.always_build:
return None
state = 0
for kid in self.children(None):
s = kid.get_state()
if s and (not state or s > state):
state = s
return (state == 0 or state == SCons.Node.up_to_date)
def is_literal(self):
"""Always pass the string representation of a Node to
the command interpreter literally."""
return 1
def render_include_tree(self):
"""
Return a text representation, suitable for displaying to the
user, of the include tree for the sources of this node.
"""
if self.is_derived() and self.env:
env = self.get_build_env()
for s in self.sources:
scanner = self.get_source_scanner(s)
if scanner:
path = self.get_build_scanner_path(scanner)
else:
path = None
def f(node, env=env, scanner=scanner, path=path):
return node.get_found_includes(env, scanner, path)
return SCons.Util.render_tree(s, f, 1)
else:
return None
def get_abspath(self):
"""
Return an absolute path to the Node. This will return simply
str(Node) by default, but for Node types that have a concept of
relative path, this might return something different.
"""
return str(self)
def for_signature(self):
"""
Return a string representation of the Node that will always
be the same for this particular Node, no matter what. This
is by contrast to the __str__() method, which might, for
instance, return a relative path for a file Node. The purpose
of this method is to generate a value to be used in signature
calculation for the command line used to build a target, and
we use this method instead of str() to avoid unnecessary
rebuilds. This method does not need to return something that
would actually work in a command line; it can return any kind of
nonsense, so long as it does not change.
"""
return str(self)
def get_string(self, for_signature):
"""This is a convenience function designed primarily to be
used in command generators (i.e., CommandGeneratorActions or
Environment variables that are callable), which are called
with a for_signature argument that is nonzero if the command
generator is being called to generate a signature for the
command line, which determines if we should rebuild or not.
Such command generators should use this method in preference
to str(Node) when converting a Node to a string, passing
in the for_signature parameter, such that we will call
Node.for_signature() or str(Node) properly, depending on whether
we are calculating a signature or actually constructing a
command line."""
if for_signature:
return self.for_signature()
return str(self)
def get_subst_proxy(self):
"""
This method is expected to return an object that will function
exactly like this Node, except that it implements any additional
special features that we would like to be in effect for
Environment variable substitution. The principle use is that
some Nodes would like to implement a __getattr__() method,
but putting that in the Node type itself has a tendency to kill
performance. We instead put it in a proxy and return it from
this method. It is legal for this method to return self
if no new functionality is needed for Environment substitution.
"""
return self
def explain(self):
if not self.exists():
return "building `%s' because it doesn't exist\n" % self
if self.always_build:
return "rebuilding `%s' because AlwaysBuild() is specified\n" % self
old = self.get_stored_info()
if old is None:
return None
old = old.binfo
old.prepare_dependencies()
try:
old_bkids = old.bsources + old.bdepends + old.bimplicit
old_bkidsigs = old.bsourcesigs + old.bdependsigs + old.bimplicitsigs
except AttributeError:
return "Cannot explain why `%s' is being rebuilt: No previous build information found\n" % self
new = self.get_binfo()
new_bkids = new.bsources + new.bdepends + new.bimplicit
new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs
osig = dict(izip(old_bkids, old_bkidsigs))
nsig = dict(izip(new_bkids, new_bkidsigs))
# The sources and dependencies we'll want to report are all stored
# as relative paths to this target's directory, but we want to
# report them relative to the top-level SConstruct directory,
# so we only print them after running them through this lambda
# to turn them into the right relative Node and then return
# its string.
def stringify( s, E=self.dir.Entry ) :
if hasattr( s, 'dir' ) :
return str(E(s))
return str(s)
lines = []
removed = filter(lambda x, nk=new_bkids: not x in nk, old_bkids)
if removed:
removed = map(stringify, removed)
fmt = "`%s' is no longer a dependency\n"
lines.extend(map(lambda s, fmt=fmt: fmt % s, removed))
for k in new_bkids:
if not k in old_bkids:
lines.append("`%s' is a new dependency\n" % stringify(k))
elif k.changed_since_last_build(self, osig[k]):
lines.append("`%s' changed\n" % stringify(k))
if len(lines) == 0 and old_bkids != new_bkids:
lines.append("the dependency order changed:\n" +
"%sold: %s\n" % (' '*15, map(stringify, old_bkids)) +
"%snew: %s\n" % (' '*15, map(stringify, new_bkids)))
if len(lines) == 0:
def fmt_with_title(title, strlines):
lines = string.split(strlines, '\n')
sep = '\n' + ' '*(15 + len(title))
return ' '*15 + title + string.join(lines, sep) + '\n'
if old.bactsig != new.bactsig:
if old.bact == new.bact:
lines.append("the contents of the build action changed\n" +
fmt_with_title('action: ', new.bact))
else:
lines.append("the build action changed:\n" +
fmt_with_title('old: ', old.bact) +
fmt_with_title('new: ', new.bact))
if len(lines) == 0:
return "rebuilding `%s' for unknown reasons\n" % self
preamble = "rebuilding `%s' because" % self
if len(lines) == 1:
return "%s %s" % (preamble, lines[0])
else:
lines = ["%s:\n" % preamble] + lines
return string.join(lines, ' '*11)
try:
[].extend(UserList.UserList([]))
except TypeError:
# Python 1.5.2 doesn't allow a list to be extended by list-like
# objects (such as UserList instances), so just punt and use
# real lists.
def NodeList(l):
return l
else:
class NodeList(UserList.UserList):
def __str__(self):
return str(map(str, self.data))
def get_children(node, parent): return node.children()
def ignore_cycle(node, stack): pass
def do_nothing(node, parent): pass
class Walker:
"""An iterator for walking a Node tree.
This is depth-first, children are visited before the parent.
The Walker object can be initialized with any node, and
returns the next node on the descent with each next() call.
'kids_func' is an optional function that will be called to
get the children of a node instead of calling 'children'.
'cycle_func' is an optional function that will be called
when a cycle is detected.
This class does not get caught in node cycles caused, for example,
by C header file include loops.
"""
def __init__(self, node, kids_func=get_children,
cycle_func=ignore_cycle,
eval_func=do_nothing):
self.kids_func = kids_func
self.cycle_func = cycle_func
self.eval_func = eval_func
node.wkids = copy.copy(kids_func(node, None))
self.stack = [node]
self.history = {} # used to efficiently detect and avoid cycles
self.history[node] = None
def next(self):
"""Return the next node for this walk of the tree.
This function is intentionally iterative, not recursive,
to sidestep any issues of stack size limitations.
"""
while self.stack:
if self.stack[-1].wkids:
node = self.stack[-1].wkids.pop(0)
if not self.stack[-1].wkids:
self.stack[-1].wkids = None
if self.history.has_key(node):
self.cycle_func(node, self.stack)
else:
node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
self.stack.append(node)
self.history[node] = None
else:
node = self.stack.pop()
del self.history[node]
if node:
if self.stack:
parent = self.stack[-1]
else:
parent = None
self.eval_func(node, parent)
return node
return None
def is_done(self):
return not self.stack
arg2nodes_lookups = []
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""scons.Node.Python
Python nodes.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Node/Python.py 4720 2010/03/24 03:14:11 jars"
import SCons.Node
class ValueNodeInfo(SCons.Node.NodeInfoBase):
current_version_id = 1
field_list = ['csig']
def str_to_node(self, s):
return Value(s)
class ValueBuildInfo(SCons.Node.BuildInfoBase):
current_version_id = 1
class Value(SCons.Node.Node):
"""A class for Python variables, typically passed on the command line
or generated by a script, but not from a file or some other source.
"""
NodeInfo = ValueNodeInfo
BuildInfo = ValueBuildInfo
def __init__(self, value, built_value=None):
SCons.Node.Node.__init__(self)
self.value = value
if built_value is not None:
self.built_value = built_value
def str_for_display(self):
return repr(self.value)
def __str__(self):
return str(self.value)
def make_ready(self):
self.get_csig()
def build(self, **kw):
if not hasattr(self, 'built_value'):
apply (SCons.Node.Node.build, (self,), kw)
is_up_to_date = SCons.Node.Node.children_are_up_to_date
def is_under(self, dir):
# Make Value nodes get built regardless of
# what directory scons was run from. Value nodes
# are outside the filesystem:
return 1
def write(self, built_value):
"""Set the value of the node."""
self.built_value = built_value
def read(self):
"""Return the value. If necessary, the value is built."""
self.build()
if not hasattr(self, 'built_value'):
self.built_value = self.value
return self.built_value
def get_text_contents(self):
"""By the assumption that the node.built_value is a
deterministic product of the sources, the contents of a Value
are the concatenation of all the contents of its sources. As
the value need not be built when get_contents() is called, we
cannot use the actual node.built_value."""
###TODO: something reasonable about universal newlines
contents = str(self.value)
for kid in self.children(None):
contents = contents + kid.get_contents()
return contents
get_contents = get_text_contents ###TODO should return 'bytes' value
def changed_since_last_build(self, target, prev_ni):
cur_csig = self.get_csig()
try:
return cur_csig != prev_ni.csig
except AttributeError:
return 1
def get_csig(self, calc=None):
"""Because we're a Python value node and don't have a real
timestamp, we get to ignore the calculator and just use the
value contents."""
try:
return self.ninfo.csig
except AttributeError:
pass
contents = self.get_contents()
self.get_ninfo().csig = contents
return contents
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""scons.Node.Alias
Alias nodes.
This creates a hash of global Aliases (dummy targets).
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Node/Alias.py 4720 2010/03/24 03:14:11 jars"
import string
import UserDict
import SCons.Errors
import SCons.Node
import SCons.Util
class AliasNameSpace(UserDict.UserDict):
def Alias(self, name, **kw):
if isinstance(name, SCons.Node.Alias.Alias):
return name
try:
a = self[name]
except KeyError:
a = apply(SCons.Node.Alias.Alias, (name,), kw)
self[name] = a
return a
def lookup(self, name, **kw):
try:
return self[name]
except KeyError:
return None
class AliasNodeInfo(SCons.Node.NodeInfoBase):
current_version_id = 1
field_list = ['csig']
def str_to_node(self, s):
return default_ans.Alias(s)
class AliasBuildInfo(SCons.Node.BuildInfoBase):
current_version_id = 1
class Alias(SCons.Node.Node):
NodeInfo = AliasNodeInfo
BuildInfo = AliasBuildInfo
def __init__(self, name):
SCons.Node.Node.__init__(self)
self.name = name
def str_for_display(self):
return '"' + self.__str__() + '"'
def __str__(self):
return self.name
def make_ready(self):
self.get_csig()
really_build = SCons.Node.Node.build
is_up_to_date = SCons.Node.Node.children_are_up_to_date
def is_under(self, dir):
# Make Alias nodes get built regardless of
# what directory scons was run from. Alias nodes
# are outside the filesystem:
return 1
def get_contents(self):
"""The contents of an alias is the concatenation
of the content signatures of all its sources."""
childsigs = map(lambda n: n.get_csig(), self.children())
return string.join(childsigs, '')
def sconsign(self):
"""An Alias is not recorded in .sconsign files"""
pass
#
#
#
def changed_since_last_build(self, target, prev_ni):
cur_csig = self.get_csig()
try:
return cur_csig != prev_ni.csig
except AttributeError:
return 1
def build(self):
"""A "builder" for aliases."""
pass
def convert(self):
try: del self.builder
except AttributeError: pass
self.reset_executor()
self.build = self.really_build
def get_csig(self):
"""
Generate a node's content signature, the digested signature
of its content.
node - the node
cache - alternate node to use for the signature cache
returns - the content signature
"""
try:
return self.ninfo.csig
except AttributeError:
pass
contents = self.get_contents()
csig = SCons.Util.MD5signature(contents)
self.get_ninfo().csig = csig
return csig
default_ans = AliasNameSpace()
SCons.Node.arg2nodes_lookups.append(default_ans.lookup)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Job
This module defines the Serial and Parallel classes that execute tasks to
complete a build. The Jobs class provides a higher level interface to start,
stop, and wait on jobs.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Job.py 4720 2010/03/24 03:14:11 jars"
import os
import signal
import SCons.Errors
# The default stack size (in kilobytes) of the threads used to execute
# jobs in parallel.
#
# We use a stack size of 256 kilobytes. The default on some platforms
# is too large and prevents us from creating enough threads to fully
# parallelized the build. For example, the default stack size on linux
# is 8 MBytes.
explicit_stack_size = None
default_stack_size = 256
interrupt_msg = 'Build interrupted.'
class InterruptState:
def __init__(self):
self.interrupted = False
def set(self):
self.interrupted = True
def __call__(self):
return self.interrupted
class Jobs:
"""An instance of this class initializes N jobs, and provides
methods for starting, stopping, and waiting on all N jobs.
"""
def __init__(self, num, taskmaster):
"""
create 'num' jobs using the given taskmaster.
If 'num' is 1 or less, then a serial job will be used,
otherwise a parallel job with 'num' worker threads will
be used.
The 'num_jobs' attribute will be set to the actual number of jobs
allocated. If more than one job is requested but the Parallel
class can't do it, it gets reset to 1. Wrapping interfaces that
care should check the value of 'num_jobs' after initialization.
"""
self.job = None
if num > 1:
stack_size = explicit_stack_size
if stack_size is None:
stack_size = default_stack_size
try:
self.job = Parallel(taskmaster, num, stack_size)
self.num_jobs = num
except NameError:
pass
if self.job is None:
self.job = Serial(taskmaster)
self.num_jobs = 1
def run(self, postfunc=lambda: None):
"""Run the jobs.
postfunc() will be invoked after the jobs has run. It will be
invoked even if the jobs are interrupted by a keyboard
interrupt (well, in fact by a signal such as either SIGINT,
SIGTERM or SIGHUP). The execution of postfunc() is protected
against keyboard interrupts and is guaranteed to run to
completion."""
self._setup_sig_handler()
try:
self.job.start()
finally:
postfunc()
self._reset_sig_handler()
def were_interrupted(self):
"""Returns whether the jobs were interrupted by a signal."""
return self.job.interrupted()
def _setup_sig_handler(self):
"""Setup an interrupt handler so that SCons can shutdown cleanly in
various conditions:
a) SIGINT: Keyboard interrupt
b) SIGTERM: kill or system shutdown
c) SIGHUP: Controlling shell exiting
We handle all of these cases by stopping the taskmaster. It
turns out that it very difficult to stop the build process
by throwing asynchronously an exception such as
KeyboardInterrupt. For example, the python Condition
variables (threading.Condition) and Queue's do not seem to
asynchronous-exception-safe. It would require adding a whole
bunch of try/finally block and except KeyboardInterrupt all
over the place.
Note also that we have to be careful to handle the case when
SCons forks before executing another process. In that case, we
want the child to exit immediately.
"""
def handler(signum, stack, self=self, parentpid=os.getpid()):
if os.getpid() == parentpid:
self.job.taskmaster.stop()
self.job.interrupted.set()
else:
os._exit(2)
self.old_sigint = signal.signal(signal.SIGINT, handler)
self.old_sigterm = signal.signal(signal.SIGTERM, handler)
try:
self.old_sighup = signal.signal(signal.SIGHUP, handler)
except AttributeError:
pass
def _reset_sig_handler(self):
"""Restore the signal handlers to their previous state (before the
call to _setup_sig_handler()."""
signal.signal(signal.SIGINT, self.old_sigint)
signal.signal(signal.SIGTERM, self.old_sigterm)
try:
signal.signal(signal.SIGHUP, self.old_sighup)
except AttributeError:
pass
class Serial:
"""This class is used to execute tasks in series, and is more efficient
than Parallel, but is only appropriate for non-parallel builds. Only
one instance of this class should be in existence at a time.
This class is not thread safe.
"""
def __init__(self, taskmaster):
"""Create a new serial job given a taskmaster.
The taskmaster's next_task() method should return the next task
that needs to be executed, or None if there are no more tasks. The
taskmaster's executed() method will be called for each task when it
is successfully executed or failed() will be called if it failed to
execute (e.g. execute() raised an exception)."""
self.taskmaster = taskmaster
self.interrupted = InterruptState()
def start(self):
"""Start the job. This will begin pulling tasks from the taskmaster
and executing them, and return when there are no more tasks. If a task
fails to execute (i.e. execute() raises an exception), then the job will
stop."""
while 1:
task = self.taskmaster.next_task()
if task is None:
break
try:
task.prepare()
if task.needs_execute():
task.execute()
except:
if self.interrupted():
try:
raise SCons.Errors.BuildError(
task.targets[0], errstr=interrupt_msg)
except:
task.exception_set()
else:
task.exception_set()
# Let the failed() callback function arrange for the
# build to stop if that's appropriate.
task.failed()
else:
task.executed()
task.postprocess()
self.taskmaster.cleanup()
# Trap import failure so that everything in the Job module but the
# Parallel class (and its dependent classes) will work if the interpreter
# doesn't support threads.
try:
import Queue
import threading
except ImportError:
pass
else:
class Worker(threading.Thread):
"""A worker thread waits on a task to be posted to its request queue,
dequeues the task, executes it, and posts a tuple including the task
and a boolean indicating whether the task executed successfully. """
def __init__(self, requestQueue, resultsQueue, interrupted):
threading.Thread.__init__(self)
self.setDaemon(1)
self.requestQueue = requestQueue
self.resultsQueue = resultsQueue
self.interrupted = interrupted
self.start()
def run(self):
while 1:
task = self.requestQueue.get()
if task is None:
# The "None" value is used as a sentinel by
# ThreadPool.cleanup(). This indicates that there
# are no more tasks, so we should quit.
break
try:
if self.interrupted():
raise SCons.Errors.BuildError(
task.targets[0], errstr=interrupt_msg)
task.execute()
except:
task.exception_set()
ok = False
else:
ok = True
self.resultsQueue.put((task, ok))
class ThreadPool:
"""This class is responsible for spawning and managing worker threads."""
def __init__(self, num, stack_size, interrupted):
"""Create the request and reply queues, and 'num' worker threads.
One must specify the stack size of the worker threads. The
stack size is specified in kilobytes.
"""
self.requestQueue = Queue.Queue(0)
self.resultsQueue = Queue.Queue(0)
try:
prev_size = threading.stack_size(stack_size*1024)
except AttributeError, e:
# Only print a warning if the stack size has been
# explicitly set.
if not explicit_stack_size is None:
msg = "Setting stack size is unsupported by this version of Python:\n " + \
e.args[0]
SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
except ValueError, e:
msg = "Setting stack size failed:\n " + str(e)
SCons.Warnings.warn(SCons.Warnings.StackSizeWarning, msg)
# Create worker threads
self.workers = []
for _ in range(num):
worker = Worker(self.requestQueue, self.resultsQueue, interrupted)
self.workers.append(worker)
# Once we drop Python 1.5 we can change the following to:
#if 'prev_size' in locals():
if 'prev_size' in locals().keys():
threading.stack_size(prev_size)
def put(self, task):
"""Put task into request queue."""
self.requestQueue.put(task)
def get(self):
"""Remove and return a result tuple from the results queue."""
return self.resultsQueue.get()
def preparation_failed(self, task):
self.resultsQueue.put((task, False))
def cleanup(self):
"""
Shuts down the thread pool, giving each worker thread a
chance to shut down gracefully.
"""
# For each worker thread, put a sentinel "None" value
# on the requestQueue (indicating that there's no work
# to be done) so that each worker thread will get one and
# terminate gracefully.
for _ in self.workers:
self.requestQueue.put(None)
# Wait for all of the workers to terminate.
#
# If we don't do this, later Python versions (2.4, 2.5) often
# seem to raise exceptions during shutdown. This happens
# in requestQueue.get(), as an assertion failure that
# requestQueue.not_full is notified while not acquired,
# seemingly because the main thread has shut down (or is
# in the process of doing so) while the workers are still
# trying to pull sentinels off the requestQueue.
#
# Normally these terminations should happen fairly quickly,
# but we'll stick a one-second timeout on here just in case
# someone gets hung.
for worker in self.workers:
worker.join(1.0)
self.workers = []
class Parallel:
"""This class is used to execute tasks in parallel, and is somewhat
less efficient than Serial, but is appropriate for parallel builds.
This class is thread safe.
"""
def __init__(self, taskmaster, num, stack_size):
"""Create a new parallel job given a taskmaster.
The taskmaster's next_task() method should return the next
task that needs to be executed, or None if there are no more
tasks. The taskmaster's executed() method will be called
for each task when it is successfully executed or failed()
will be called if the task failed to execute (i.e. execute()
raised an exception).
Note: calls to taskmaster are serialized, but calls to
execute() on distinct tasks are not serialized, because
that is the whole point of parallel jobs: they can execute
multiple tasks simultaneously. """
self.taskmaster = taskmaster
self.interrupted = InterruptState()
self.tp = ThreadPool(num, stack_size, self.interrupted)
self.maxjobs = num
def start(self):
"""Start the job. This will begin pulling tasks from the
taskmaster and executing them, and return when there are no
more tasks. If a task fails to execute (i.e. execute() raises
an exception), then the job will stop."""
jobs = 0
while 1:
# Start up as many available tasks as we're
# allowed to.
while jobs < self.maxjobs:
task = self.taskmaster.next_task()
if task is None:
break
try:
# prepare task for execution
task.prepare()
except:
task.exception_set()
task.failed()
task.postprocess()
else:
if task.needs_execute():
# dispatch task
self.tp.put(task)
jobs = jobs + 1
else:
task.executed()
task.postprocess()
if not task and not jobs: break
# Let any/all completed tasks finish up before we go
# back and put the next batch of tasks on the queue.
while 1:
task, ok = self.tp.get()
jobs = jobs - 1
if ok:
task.executed()
else:
if self.interrupted():
try:
raise SCons.Errors.BuildError(
task.targets[0], errstr=interrupt_msg)
except:
task.exception_set()
# Let the failed() callback function arrange
# for the build to stop if that's appropriate.
task.failed()
task.postprocess()
if self.tp.resultsQueue.empty():
break
self.tp.cleanup()
self.taskmaster.cleanup()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Conftest
Autoconf-like configuration support; low level implementation of tests.
"""
#
# Copyright (c) 2003 Stichting NLnet Labs
# Copyright (c) 2001, 2002, 2003 Steven Knight
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#
# The purpose of this module is to define how a check is to be performed.
# Use one of the Check...() functions below.
#
#
# A context class is used that defines functions for carrying out the tests,
# logging and messages. The following methods and members must be present:
#
# context.Display(msg) Function called to print messages that are normally
# displayed for the user. Newlines are explicitly used.
# The text should also be written to the logfile!
#
# context.Log(msg) Function called to write to a log file.
#
# context.BuildProg(text, ext)
# Function called to build a program, using "ext" for the
# file extention. Must return an empty string for
# success, an error message for failure.
# For reliable test results building should be done just
# like an actual program would be build, using the same
# command and arguments (including configure results so
# far).
#
# context.CompileProg(text, ext)
# Function called to compile a program, using "ext" for
# the file extention. Must return an empty string for
# success, an error message for failure.
# For reliable test results compiling should be done just
# like an actual source file would be compiled, using the
# same command and arguments (including configure results
# so far).
#
# context.AppendLIBS(lib_name_list)
# Append "lib_name_list" to the value of LIBS.
# "lib_namelist" is a list of strings.
# Return the value of LIBS before changing it (any type
# can be used, it is passed to SetLIBS() later.)
#
# context.PrependLIBS(lib_name_list)
# Prepend "lib_name_list" to the value of LIBS.
# "lib_namelist" is a list of strings.
# Return the value of LIBS before changing it (any type
# can be used, it is passed to SetLIBS() later.)
#
# context.SetLIBS(value)
# Set LIBS to "value". The type of "value" is what
# AppendLIBS() returned.
# Return the value of LIBS before changing it (any type
# can be used, it is passed to SetLIBS() later.)
#
# context.headerfilename
# Name of file to append configure results to, usually
# "confdefs.h".
# The file must not exist or be empty when starting.
# Empty or None to skip this (some tests will not work!).
#
# context.config_h (may be missing). If present, must be a string, which
# will be filled with the contents of a config_h file.
#
# context.vardict Dictionary holding variables used for the tests and
# stores results from the tests, used for the build
# commands.
# Normally contains "CC", "LIBS", "CPPFLAGS", etc.
#
# context.havedict Dictionary holding results from the tests that are to
# be used inside a program.
# Names often start with "HAVE_". These are zero
# (feature not present) or one (feature present). Other
# variables may have any value, e.g., "PERLVERSION" can
# be a number and "SYSTEMNAME" a string.
#
import re
import string
from types import IntType
#
# PUBLIC VARIABLES
#
LogInputFiles = 1 # Set that to log the input files in case of a failed test
LogErrorMessages = 1 # Set that to log Conftest-generated error messages
#
# PUBLIC FUNCTIONS
#
# Generic remarks:
# - When a language is specified which is not supported the test fails. The
# message is a bit different, because not all the arguments for the normal
# message are available yet (chicken-egg problem).
def CheckBuilder(context, text = None, language = None):
"""
Configure check to see if the compiler works.
Note that this uses the current value of compiler and linker flags, make
sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
"language" should be "C" or "C++" and is used to select the compiler.
Default is "C".
"text" may be used to specify the code to be build.
Returns an empty string for success, an error message for failure.
"""
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("%s\n" % msg)
return msg
if not text:
text = """
int main() {
return 0;
}
"""
context.Display("Checking if building a %s file works... " % lang)
ret = context.BuildProg(text, suffix)
_YesNoResult(context, ret, None, text)
return ret
def CheckCC(context):
"""
Configure check for a working C compiler.
This checks whether the C compiler, as defined in the $CC construction
variable, can compile a C source file. It uses the current $CCCOM value
too, so that it can test against non working flags.
"""
context.Display("Checking whether the C compiler works")
text = """
int main()
{
return 0;
}
"""
ret = _check_empty_program(context, 'CC', text, 'C')
_YesNoResult(context, ret, None, text)
return ret
def CheckSHCC(context):
"""
Configure check for a working shared C compiler.
This checks whether the C compiler, as defined in the $SHCC construction
variable, can compile a C source file. It uses the current $SHCCCOM value
too, so that it can test against non working flags.
"""
context.Display("Checking whether the (shared) C compiler works")
text = """
int foo()
{
return 0;
}
"""
ret = _check_empty_program(context, 'SHCC', text, 'C', use_shared = True)
_YesNoResult(context, ret, None, text)
return ret
def CheckCXX(context):
"""
Configure check for a working CXX compiler.
This checks whether the CXX compiler, as defined in the $CXX construction
variable, can compile a CXX source file. It uses the current $CXXCOM value
too, so that it can test against non working flags.
"""
context.Display("Checking whether the C++ compiler works")
text = """
int main()
{
return 0;
}
"""
ret = _check_empty_program(context, 'CXX', text, 'C++')
_YesNoResult(context, ret, None, text)
return ret
def CheckSHCXX(context):
"""
Configure check for a working shared CXX compiler.
This checks whether the CXX compiler, as defined in the $SHCXX construction
variable, can compile a CXX source file. It uses the current $SHCXXCOM value
too, so that it can test against non working flags.
"""
context.Display("Checking whether the (shared) C++ compiler works")
text = """
int main()
{
return 0;
}
"""
ret = _check_empty_program(context, 'SHCXX', text, 'C++', use_shared = True)
_YesNoResult(context, ret, None, text)
return ret
def _check_empty_program(context, comp, text, language, use_shared = False):
"""Return 0 on success, 1 otherwise."""
if not context.env.has_key(comp) or not context.env[comp]:
# The compiler construction variable is not set or empty
return 1
lang, suffix, msg = _lang2suffix(language)
if msg:
return 1
if use_shared:
return context.CompileSharedObject(text, suffix)
else:
return context.CompileProg(text, suffix)
def CheckFunc(context, function_name, header = None, language = None):
"""
Configure check for a function "function_name".
"language" should be "C" or "C++" and is used to select the compiler.
Default is "C".
Optional "header" can be defined to define a function prototype, include a
header file or anything else that comes before main().
Sets HAVE_function_name in context.havedict according to the result.
Note that this uses the current value of compiler and linker flags, make
sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
Returns an empty string for success, an error message for failure.
"""
# Remarks from autoconf:
# - Don't include <ctype.h> because on OSF/1 3.0 it includes <sys/types.h>
# which includes <sys/select.h> which contains a prototype for select.
# Similarly for bzero.
# - assert.h is included to define __stub macros and hopefully few
# prototypes, which can conflict with char $1(); below.
# - Override any gcc2 internal prototype to avoid an error.
# - We use char for the function declaration because int might match the
# return type of a gcc2 builtin and then its argument prototype would
# still apply.
# - The GNU C library defines this for functions which it implements to
# always fail with ENOSYS. Some functions are actually named something
# starting with __ and the normal name is an alias.
if context.headerfilename:
includetext = '#include "%s"' % context.headerfilename
else:
includetext = ''
if not header:
header = """
#ifdef __cplusplus
extern "C"
#endif
char %s();""" % function_name
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("Cannot check for %s(): %s\n" % (function_name, msg))
return msg
text = """
%(include)s
#include <assert.h>
%(hdr)s
int main() {
#if defined (__stub_%(name)s) || defined (__stub___%(name)s)
fail fail fail
#else
%(name)s();
#endif
return 0;
}
""" % { 'name': function_name,
'include': includetext,
'hdr': header }
context.Display("Checking for %s function %s()... " % (lang, function_name))
ret = context.BuildProg(text, suffix)
_YesNoResult(context, ret, "HAVE_" + function_name, text,
"Define to 1 if the system has the function `%s'." %\
function_name)
return ret
def CheckHeader(context, header_name, header = None, language = None,
include_quotes = None):
"""
Configure check for a C or C++ header file "header_name".
Optional "header" can be defined to do something before including the
header file (unusual, supported for consistency).
"language" should be "C" or "C++" and is used to select the compiler.
Default is "C".
Sets HAVE_header_name in context.havedict according to the result.
Note that this uses the current value of compiler and linker flags, make
sure $CFLAGS and $CPPFLAGS are set correctly.
Returns an empty string for success, an error message for failure.
"""
# Why compile the program instead of just running the preprocessor?
# It is possible that the header file exists, but actually using it may
# fail (e.g., because it depends on other header files). Thus this test is
# more strict. It may require using the "header" argument.
#
# Use <> by default, because the check is normally used for system header
# files. SCons passes '""' to overrule this.
# Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
if context.headerfilename:
includetext = '#include "%s"\n' % context.headerfilename
else:
includetext = ''
if not header:
header = ""
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("Cannot check for header file %s: %s\n"
% (header_name, msg))
return msg
if not include_quotes:
include_quotes = "<>"
text = "%s%s\n#include %s%s%s\n\n" % (includetext, header,
include_quotes[0], header_name, include_quotes[1])
context.Display("Checking for %s header file %s... " % (lang, header_name))
ret = context.CompileProg(text, suffix)
_YesNoResult(context, ret, "HAVE_" + header_name, text,
"Define to 1 if you have the <%s> header file." % header_name)
return ret
def CheckType(context, type_name, fallback = None,
header = None, language = None):
"""
Configure check for a C or C++ type "type_name".
Optional "header" can be defined to include a header file.
"language" should be "C" or "C++" and is used to select the compiler.
Default is "C".
Sets HAVE_type_name in context.havedict according to the result.
Note that this uses the current value of compiler and linker flags, make
sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
Returns an empty string for success, an error message for failure.
"""
# Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
if context.headerfilename:
includetext = '#include "%s"' % context.headerfilename
else:
includetext = ''
if not header:
header = ""
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("Cannot check for %s type: %s\n" % (type_name, msg))
return msg
# Remarks from autoconf about this test:
# - Grepping for the type in include files is not reliable (grep isn't
# portable anyway).
# - Using "TYPE my_var;" doesn't work for const qualified types in C++.
# Adding an initializer is not valid for some C++ classes.
# - Using the type as parameter to a function either fails for K&$ C or for
# C++.
# - Using "TYPE *my_var;" is valid in C for some types that are not
# declared (struct something).
# - Using "sizeof(TYPE)" is valid when TYPE is actually a variable.
# - Using the previous two together works reliably.
text = """
%(include)s
%(header)s
int main() {
if ((%(name)s *) 0)
return 0;
if (sizeof (%(name)s))
return 0;
}
""" % { 'include': includetext,
'header': header,
'name': type_name }
context.Display("Checking for %s type %s... " % (lang, type_name))
ret = context.BuildProg(text, suffix)
_YesNoResult(context, ret, "HAVE_" + type_name, text,
"Define to 1 if the system has the type `%s'." % type_name)
if ret and fallback and context.headerfilename:
f = open(context.headerfilename, "a")
f.write("typedef %s %s;\n" % (fallback, type_name))
f.close()
return ret
def CheckTypeSize(context, type_name, header = None, language = None, expect = None):
"""This check can be used to get the size of a given type, or to check whether
the type is of expected size.
Arguments:
- type : str
the type to check
- includes : sequence
list of headers to include in the test code before testing the type
- language : str
'C' or 'C++'
- expect : int
if given, will test wether the type has the given number of bytes.
If not given, will automatically find the size.
Returns:
status : int
0 if the check failed, or the found size of the type if the check succeeded."""
# Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
if context.headerfilename:
includetext = '#include "%s"' % context.headerfilename
else:
includetext = ''
if not header:
header = ""
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("Cannot check for %s type: %s\n" % (type_name, msg))
return msg
src = includetext + header
if not expect is None:
# Only check if the given size is the right one
context.Display('Checking %s is %d bytes... ' % (type_name, expect))
# test code taken from autoconf: this is a pretty clever hack to find that
# a type is of a given size using only compilation. This speeds things up
# quite a bit compared to straightforward code using TryRun
src = src + r"""
typedef %s scons_check_type;
int main()
{
static int test_array[1 - 2 * !(((long int) (sizeof(scons_check_type))) == %d)];
test_array[0] = 0;
return 0;
}
"""
st = context.CompileProg(src % (type_name, expect), suffix)
if not st:
context.Display("yes\n")
_Have(context, "SIZEOF_%s" % type_name, expect,
"The size of `%s', as computed by sizeof." % type_name)
return expect
else:
context.Display("no\n")
_LogFailed(context, src, st)
return 0
else:
# Only check if the given size is the right one
context.Message('Checking size of %s ... ' % type_name)
# We have to be careful with the program we wish to test here since
# compilation will be attempted using the current environment's flags.
# So make sure that the program will compile without any warning. For
# example using: 'int main(int argc, char** argv)' will fail with the
# '-Wall -Werror' flags since the variables argc and argv would not be
# used in the program...
#
src = src + """
#include <stdlib.h>
#include <stdio.h>
int main() {
printf("%d", (int)sizeof(""" + type_name + """));
return 0;
}
"""
st, out = context.RunProg(src, suffix)
try:
size = int(out)
except ValueError:
# If cannot convert output of test prog to an integer (the size),
# something went wront, so just fail
st = 1
size = 0
if not st:
context.Display("yes\n")
_Have(context, "SIZEOF_%s" % type_name, size,
"The size of `%s', as computed by sizeof." % type_name)
return size
else:
context.Display("no\n")
_LogFailed(context, src, st)
return 0
return 0
def CheckDeclaration(context, symbol, includes = None, language = None):
"""Checks whether symbol is declared.
Use the same test as autoconf, that is test whether the symbol is defined
as a macro or can be used as an r-value.
Arguments:
symbol : str
the symbol to check
includes : str
Optional "header" can be defined to include a header file.
language : str
only C and C++ supported.
Returns:
status : bool
True if the check failed, False if succeeded."""
# Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
if context.headerfilename:
includetext = '#include "%s"' % context.headerfilename
else:
includetext = ''
if not includes:
includes = ""
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("Cannot check for declaration %s: %s\n" % (type_name, msg))
return msg
src = includetext + includes
context.Display('Checking whether %s is declared... ' % symbol)
src = src + r"""
int main()
{
#ifndef %s
(void) %s;
#endif
;
return 0;
}
""" % (symbol, symbol)
st = context.CompileProg(src, suffix)
_YesNoResult(context, st, "HAVE_DECL_" + symbol, src,
"Set to 1 if %s is defined." % symbol)
return st
def CheckLib(context, libs, func_name = None, header = None,
extra_libs = None, call = None, language = None, autoadd = 1,
append = True):
"""
Configure check for a C or C++ libraries "libs". Searches through
the list of libraries, until one is found where the test succeeds.
Tests if "func_name" or "call" exists in the library. Note: if it exists
in another library the test succeeds anyway!
Optional "header" can be defined to include a header file. If not given a
default prototype for "func_name" is added.
Optional "extra_libs" is a list of library names to be added after
"lib_name" in the build command. To be used for libraries that "lib_name"
depends on.
Optional "call" replaces the call to "func_name" in the test code. It must
consist of complete C statements, including a trailing ";".
Both "func_name" and "call" arguments are optional, and in that case, just
linking against the libs is tested.
"language" should be "C" or "C++" and is used to select the compiler.
Default is "C".
Note that this uses the current value of compiler and linker flags, make
sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
Returns an empty string for success, an error message for failure.
"""
# Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
if context.headerfilename:
includetext = '#include "%s"' % context.headerfilename
else:
includetext = ''
if not header:
header = ""
text = """
%s
%s""" % (includetext, header)
# Add a function declaration if needed.
if func_name and func_name != "main":
if not header:
text = text + """
#ifdef __cplusplus
extern "C"
#endif
char %s();
""" % func_name
# The actual test code.
if not call:
call = "%s();" % func_name
# if no function to test, leave main() blank
text = text + """
int
main() {
%s
return 0;
}
""" % (call or "")
if call:
i = string.find(call, "\n")
if i > 0:
calltext = call[:i] + ".."
elif call[-1] == ';':
calltext = call[:-1]
else:
calltext = call
for lib_name in libs:
lang, suffix, msg = _lang2suffix(language)
if msg:
context.Display("Cannot check for library %s: %s\n" % (lib_name, msg))
return msg
# if a function was specified to run in main(), say it
if call:
context.Display("Checking for %s in %s library %s... "
% (calltext, lang, lib_name))
# otherwise, just say the name of library and language
else:
context.Display("Checking for %s library %s... "
% (lang, lib_name))
if lib_name:
l = [ lib_name ]
if extra_libs:
l.extend(extra_libs)
if append:
oldLIBS = context.AppendLIBS(l)
else:
oldLIBS = context.PrependLIBS(l)
sym = "HAVE_LIB" + lib_name
else:
oldLIBS = -1
sym = None
ret = context.BuildProg(text, suffix)
_YesNoResult(context, ret, sym, text,
"Define to 1 if you have the `%s' library." % lib_name)
if oldLIBS != -1 and (ret or not autoadd):
context.SetLIBS(oldLIBS)
if not ret:
return ret
return ret
#
# END OF PUBLIC FUNCTIONS
#
def _YesNoResult(context, ret, key, text, comment = None):
"""
Handle the result of a test with a "yes" or "no" result.
"ret" is the return value: empty if OK, error message when not.
"key" is the name of the symbol to be defined (HAVE_foo).
"text" is the source code of the program used for testing.
"comment" is the C comment to add above the line defining the symbol (the
comment is automatically put inside a /* */). If None, no comment is added.
"""
if key:
_Have(context, key, not ret, comment)
if ret:
context.Display("no\n")
_LogFailed(context, text, ret)
else:
context.Display("yes\n")
def _Have(context, key, have, comment = None):
"""
Store result of a test in context.havedict and context.headerfilename.
"key" is a "HAVE_abc" name. It is turned into all CAPITALS and non-
alphanumerics are replaced by an underscore.
The value of "have" can be:
1 - Feature is defined, add "#define key".
0 - Feature is not defined, add "/* #undef key */".
Adding "undef" is what autoconf does. Not useful for the
compiler, but it shows that the test was done.
number - Feature is defined to this number "#define key have".
Doesn't work for 0 or 1, use a string then.
string - Feature is defined to this string "#define key have".
Give "have" as is should appear in the header file, include quotes
when desired and escape special characters!
"""
key_up = string.upper(key)
key_up = re.sub('[^A-Z0-9_]', '_', key_up)
context.havedict[key_up] = have
if have == 1:
line = "#define %s 1\n" % key_up
elif have == 0:
line = "/* #undef %s */\n" % key_up
elif type(have) == IntType:
line = "#define %s %d\n" % (key_up, have)
else:
line = "#define %s %s\n" % (key_up, str(have))
if comment is not None:
lines = "\n/* %s */\n" % comment + line
else:
lines = "\n" + line
if context.headerfilename:
f = open(context.headerfilename, "a")
f.write(lines)
f.close()
elif hasattr(context,'config_h'):
context.config_h = context.config_h + lines
def _LogFailed(context, text, msg):
"""
Write to the log about a failed program.
Add line numbers, so that error messages can be understood.
"""
if LogInputFiles:
context.Log("Failed program was:\n")
lines = string.split(text, '\n')
if len(lines) and lines[-1] == '':
lines = lines[:-1] # remove trailing empty line
n = 1
for line in lines:
context.Log("%d: %s\n" % (n, line))
n = n + 1
if LogErrorMessages:
context.Log("Error message: %s\n" % msg)
def _lang2suffix(lang):
"""
Convert a language name to a suffix.
When "lang" is empty or None C is assumed.
Returns a tuple (lang, suffix, None) when it works.
For an unrecognized language returns (None, None, msg).
Where:
lang = the unified language name
suffix = the suffix, including the leading dot
msg = an error message
"""
if not lang or lang in ["C", "c"]:
return ("C", ".c", None)
if lang in ["c++", "C++", "cpp", "CXX", "cxx"]:
return ("C++", ".cpp", None)
return None, None, "Unsupported language: %s" % lang
# vim: set sw=4 et sts=4 tw=79 fo+=l:
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.as
Tool-specific initialization for as, the generic Posix assembler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/as.py 4720 2010/03/24 03:14:11 jars"
import SCons.Defaults
import SCons.Tool
import SCons.Util
assemblers = ['as']
ASSuffixes = ['.s', '.asm', '.ASM']
ASPPSuffixes = ['.spp', '.SPP', '.sx']
if SCons.Util.case_sensitive_suffixes('.s', '.S'):
ASPPSuffixes.extend(['.S'])
else:
ASSuffixes.extend(['.S'])
def generate(env):
"""Add Builders and construction variables for as to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ASSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASAction)
shared_obj.add_action(suffix, SCons.Defaults.ASAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
for suffix in ASPPSuffixes:
static_obj.add_action(suffix, SCons.Defaults.ASPPAction)
shared_obj.add_action(suffix, SCons.Defaults.ASPPAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['AS'] = env.Detect(assemblers) or 'as'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASCOM'] = '$AS $ASFLAGS -o $TARGET $SOURCES'
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o $TARGET $SOURCES'
def exists(env):
return env.Detect(assemblers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""engine.SCons.Tool.msvc
Tool-specific initialization for Microsoft Visual C/C++.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/msvc.py 4720 2010/03/24 03:14:11 jars"
import os.path
import re
import string
import sys
import SCons.Action
import SCons.Builder
import SCons.Errors
import SCons.Platform.win32
import SCons.Tool
import SCons.Tool.msvs
import SCons.Util
import SCons.Warnings
import SCons.Scanner.RC
from MSCommon import msvc_exists, msvc_setup_env_once
CSuffixes = ['.c', '.C']
CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++']
def validate_vars(env):
"""Validate the PCH and PCHSTOP construction variables."""
if env.has_key('PCH') and env['PCH']:
if not env.has_key('PCHSTOP'):
raise SCons.Errors.UserError, "The PCHSTOP construction must be defined if PCH is defined."
if not SCons.Util.is_String(env['PCHSTOP']):
raise SCons.Errors.UserError, "The PCHSTOP construction variable must be a string: %r"%env['PCHSTOP']
def pch_emitter(target, source, env):
"""Adds the object file target."""
validate_vars(env)
pch = None
obj = None
for t in target:
if SCons.Util.splitext(str(t))[1] == '.pch':
pch = t
if SCons.Util.splitext(str(t))[1] == '.obj':
obj = t
if not obj:
obj = SCons.Util.splitext(str(pch))[0]+'.obj'
target = [pch, obj] # pch must be first, and obj second for the PCHCOM to work
return (target, source)
def object_emitter(target, source, env, parent_emitter):
"""Sets up the PCH dependencies for an object file."""
validate_vars(env)
parent_emitter(target, source, env)
# Add a dependency, but only if the target (e.g. 'Source1.obj')
# doesn't correspond to the pre-compiled header ('Source1.pch').
# If the basenames match, then this was most likely caused by
# someone adding the source file to both the env.PCH() and the
# env.Program() calls, and adding the explicit dependency would
# cause a cycle on the .pch file itself.
#
# See issue #2505 for a discussion of what to do if it turns
# out this assumption causes trouble in the wild:
# http://scons.tigris.org/issues/show_bug.cgi?id=2505
if env.has_key('PCH'):
pch = env['PCH']
if str(target[0]) != SCons.Util.splitext(str(pch))[0] + '.obj':
env.Depends(target, pch)
return (target, source)
def static_object_emitter(target, source, env):
return object_emitter(target, source, env,
SCons.Defaults.StaticObjectEmitter)
def shared_object_emitter(target, source, env):
return object_emitter(target, source, env,
SCons.Defaults.SharedObjectEmitter)
pch_action = SCons.Action.Action('$PCHCOM', '$PCHCOMSTR')
pch_builder = SCons.Builder.Builder(action=pch_action, suffix='.pch',
emitter=pch_emitter,
source_scanner=SCons.Tool.SourceFileScanner)
# Logic to build .rc files into .res files (resource files)
res_scanner = SCons.Scanner.RC.RCScan()
res_action = SCons.Action.Action('$RCCOM', '$RCCOMSTR')
res_builder = SCons.Builder.Builder(action=res_action,
src_suffix='.rc',
suffix='.res',
src_builder=[],
source_scanner=res_scanner)
def msvc_batch_key(action, env, target, source):
"""
Returns a key to identify unique batches of sources for compilation.
If batching is enabled (via the $MSVC_BATCH setting), then all
target+source pairs that use the same action, defined by the same
environment, and have the same target and source directories, will
be batched.
Returning None specifies that the specified target+source should not
be batched with other compilations.
"""
b = env.subst('$MSVC_BATCH')
if b in (None, '', '0'):
# We're not using batching; return no key.
return None
t = target[0]
s = source[0]
if os.path.splitext(t.name)[0] != os.path.splitext(s.name)[0]:
# The base names are different, so this *must* be compiled
# separately; return no key.
return None
return (id(action), id(env), t.dir, s.dir)
def msvc_output_flag(target, source, env, for_signature):
"""
Returns the correct /Fo flag for batching.
If batching is disabled or there's only one source file, then we
return an /Fo string that specifies the target explicitly. Otherwise,
we return an /Fo string that just specifies the first target's
directory (where the Visual C/C++ compiler will put the .obj files).
"""
b = env.subst('$MSVC_BATCH')
if b in (None, '', '0') or len(source) == 1:
return '/Fo$TARGET'
else:
# The Visual C/C++ compiler requires a \ at the end of the /Fo
# option to indicate an output directory. We use os.sep here so
# that the test(s) for this can be run on non-Windows systems
# without having a hard-coded backslash mess up command-line
# argument parsing.
return '/Fo${TARGET.dir}' + os.sep
CAction = SCons.Action.Action("$CCCOM", "$CCCOMSTR",
batch_key=msvc_batch_key,
targets='$CHANGED_TARGETS')
ShCAction = SCons.Action.Action("$SHCCCOM", "$SHCCCOMSTR",
batch_key=msvc_batch_key,
targets='$CHANGED_TARGETS')
CXXAction = SCons.Action.Action("$CXXCOM", "$CXXCOMSTR",
batch_key=msvc_batch_key,
targets='$CHANGED_TARGETS')
ShCXXAction = SCons.Action.Action("$SHCXXCOM", "$SHCXXCOMSTR",
batch_key=msvc_batch_key,
targets='$CHANGED_TARGETS')
def generate(env):
"""Add Builders and construction variables for MSVC++ to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
# TODO(batch): shouldn't reach in to cmdgen this way; necessary
# for now to bypass the checks in Builder.DictCmdGenerator.__call__()
# and allow .cc and .cpp to be compiled in the same command line.
static_obj.cmdgen.source_ext_match = False
shared_obj.cmdgen.source_ext_match = False
for suffix in CSuffixes:
static_obj.add_action(suffix, CAction)
shared_obj.add_action(suffix, ShCAction)
static_obj.add_emitter(suffix, static_object_emitter)
shared_obj.add_emitter(suffix, shared_object_emitter)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, CXXAction)
shared_obj.add_action(suffix, ShCXXAction)
static_obj.add_emitter(suffix, static_object_emitter)
shared_obj.add_emitter(suffix, shared_object_emitter)
env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}'])
env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s /Fp%s"%(PCHSTOP or "",File(PCH))) or ""}'])
env['_MSVC_OUTPUT_FLAG'] = msvc_output_flag
env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS'
env['CC'] = 'cl'
env['CCFLAGS'] = SCons.Util.CLVar('/nologo')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM'
env['CXX'] = '$CC'
env['CXXFLAGS'] = SCons.Util.CLVar('$( /TP $)')
env['CXXCOM'] = '$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM'
env['SHCXX'] = '$CXX'
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
env['SHCXXCOM'] = '$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM'
env['CPPDEFPREFIX'] = '/D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '/I'
env['INCSUFFIX'] = ''
# env.Append(OBJEMITTER = [static_object_emitter])
# env.Append(SHOBJEMITTER = [shared_object_emitter])
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['RC'] = 'rc'
env['RCFLAGS'] = SCons.Util.CLVar('')
env['RCSUFFIXES']=['.rc','.rc2']
env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
env['BUILDERS']['RES'] = res_builder
env['OBJPREFIX'] = ''
env['OBJSUFFIX'] = '.obj'
env['SHOBJPREFIX'] = '$OBJPREFIX'
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
# Set-up ms tools paths
msvc_setup_env_once(env)
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cc'
env['PCHPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Yd") or ""}'])
env['PCHCOM'] = '$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'
env['BUILDERS']['PCH'] = pch_builder
if not env.has_key('ENV'):
env['ENV'] = {}
if not env['ENV'].has_key('SystemRoot'): # required for dlls in the winsxs folders
env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root()
def exists(env):
return msvc_exists()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.sgicc
Tool-specific initialization for MIPSPro cc on SGI.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/sgicc.py 4720 2010/03/24 03:14:11 jars"
import cc
def generate(env):
"""Add Builders and construction variables for gcc to an Environment."""
cc.generate(env)
env['CXX'] = 'CC'
env['SHOBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
def exists(env):
return env.Detect('cc')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.sgilink
Tool-specific initialization for the SGI MIPSPro linker on SGI.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/sgilink.py 4720 2010/03/24 03:14:11 jars"
import SCons.Util
import link
linkers = ['CC', 'cc']
def generate(env):
"""Add Builders and construction variables for MIPSPro to an Environment."""
link.generate(env)
env['LINK'] = env.Detect(linkers) or 'cc'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
# __RPATH is set to $_RPATH in the platform specification if that
# platform supports it.
env.Append(LINKFLAGS=['$__RPATH'])
env['RPATHPREFIX'] = '-rpath '
env['RPATHSUFFIX'] = ''
env['_RPATH'] = '${_concat(RPATHPREFIX, RPATH, RPATHSUFFIX, __env__)}'
def exists(env):
return env.Detect(linkers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.latex
Tool-specific initialization for LaTeX.
Generates .dvi files from .latex or .ltx files
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/latex.py 4720 2010/03/24 03:14:11 jars"
import SCons.Action
import SCons.Defaults
import SCons.Scanner.LaTeX
import SCons.Util
import SCons.Tool
import SCons.Tool.tex
def LaTeXAuxFunction(target = None, source= None, env=None):
result = SCons.Tool.tex.InternalLaTeXAuxAction( SCons.Tool.tex.LaTeXAction, target, source, env )
if result != 0:
print env['LATEX']," returned an error, check the log file"
return result
LaTeXAuxAction = SCons.Action.Action(LaTeXAuxFunction,
strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)
def generate(env):
"""Add Builders and construction variables for LaTeX to an Environment."""
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
import dvi
dvi.generate(env)
import pdf
pdf.generate(env)
bld = env['BUILDERS']['DVI']
bld.add_action('.ltx', LaTeXAuxAction)
bld.add_action('.latex', LaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_eps_emitter)
bld.add_emitter('.latex', SCons.Tool.tex.tex_eps_emitter)
SCons.Tool.tex.generate_common(env)
def exists(env):
return env.Detect('latex')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.tar
Tool-specific initialization for tar.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/tar.py 4720 2010/03/24 03:14:11 jars"
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Node.FS
import SCons.Util
tars = ['tar', 'gtar']
TarAction = SCons.Action.Action('$TARCOM', '$TARCOMSTR')
TarBuilder = SCons.Builder.Builder(action = TarAction,
source_factory = SCons.Node.FS.Entry,
source_scanner = SCons.Defaults.DirScanner,
suffix = '$TARSUFFIX',
multi = 1)
def generate(env):
"""Add Builders and construction variables for tar to an Environment."""
try:
bld = env['BUILDERS']['Tar']
except KeyError:
bld = TarBuilder
env['BUILDERS']['Tar'] = bld
env['TAR'] = env.Detect(tars) or 'gtar'
env['TARFLAGS'] = SCons.Util.CLVar('-c')
env['TARCOM'] = '$TAR $TARFLAGS -f $TARGET $SOURCES'
env['TARSUFFIX'] = '.tar'
def exists(env):
return env.Detect(tars)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.BitKeeper.py
Tool-specific initialization for the BitKeeper source code control
system.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/BitKeeper.py 4720 2010/03/24 03:14:11 jars"
import SCons.Action
import SCons.Builder
import SCons.Util
def generate(env):
"""Add a Builder factory function and construction variables for
BitKeeper to an Environment."""
def BitKeeperFactory(env=env):
""" """
act = SCons.Action.Action("$BITKEEPERCOM", "$BITKEEPERCOMSTR")
return SCons.Builder.Builder(action = act, env = env)
#setattr(env, 'BitKeeper', BitKeeperFactory)
env.BitKeeper = BitKeeperFactory
env['BITKEEPER'] = 'bk'
env['BITKEEPERGET'] = '$BITKEEPER get'
env['BITKEEPERGETFLAGS'] = SCons.Util.CLVar('')
env['BITKEEPERCOM'] = '$BITKEEPERGET $BITKEEPERGETFLAGS $TARGET'
def exists(env):
return env.Detect('bk')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.mslib
Tool-specific initialization for lib (MicroSoft library archiver).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/mslib.py 4720 2010/03/24 03:14:11 jars"
import SCons.Defaults
import SCons.Tool
import SCons.Tool.msvs
import SCons.Tool.msvc
import SCons.Util
from MSCommon import msvc_exists, msvc_setup_env_once
def generate(env):
"""Add Builders and construction variables for lib to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
# Set-up ms tools paths
msvc_setup_env_once(env)
env['AR'] = 'lib'
env['ARFLAGS'] = SCons.Util.CLVar('/nologo')
env['ARCOM'] = "${TEMPFILE('$AR $ARFLAGS /OUT:$TARGET $SOURCES')}"
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
def exists(env):
return msvc_exists()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.pdftex
Tool-specific initialization for pdftex.
Generates .pdf files from .tex files
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/pdftex.py 4720 2010/03/24 03:14:11 jars"
import os
import SCons.Action
import SCons.Util
import SCons.Tool.tex
PDFTeXAction = None
# This action might be needed more than once if we are dealing with
# labels and bibtex.
PDFLaTeXAction = None
def PDFLaTeXAuxAction(target = None, source= None, env=None):
result = SCons.Tool.tex.InternalLaTeXAuxAction( PDFLaTeXAction, target, source, env )
return result
def PDFTeXLaTeXFunction(target = None, source= None, env=None):
"""A builder for TeX and LaTeX that scans the source file to
decide the "flavor" of the source and then executes the appropriate
program."""
basedir = os.path.split(str(source[0]))[0]
abspath = os.path.abspath(basedir)
if SCons.Tool.tex.is_LaTeX(source,env,abspath):
result = PDFLaTeXAuxAction(target,source,env)
if result != 0:
print env['PDFLATEX']," returned an error, check the log file"
else:
result = PDFTeXAction(target,source,env)
if result != 0:
print env['PDFTEX']," returned an error, check the log file"
return result
PDFTeXLaTeXAction = None
def generate(env):
"""Add Builders and construction variables for pdftex to an Environment."""
global PDFTeXAction
if PDFTeXAction is None:
PDFTeXAction = SCons.Action.Action('$PDFTEXCOM', '$PDFTEXCOMSTR')
global PDFLaTeXAction
if PDFLaTeXAction is None:
PDFLaTeXAction = SCons.Action.Action("$PDFLATEXCOM", "$PDFLATEXCOMSTR")
global PDFTeXLaTeXAction
if PDFTeXLaTeXAction is None:
PDFTeXLaTeXAction = SCons.Action.Action(PDFTeXLaTeXFunction,
strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)
env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes)
import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.tex', PDFTeXLaTeXAction)
bld.add_emitter('.tex', SCons.Tool.tex.tex_pdf_emitter)
# Add the epstopdf builder after the pdftex builder
# so pdftex is the default for no source suffix
pdf.generate2(env)
SCons.Tool.tex.generate_common(env)
def exists(env):
return env.Detect('pdftex')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.386asm
Tool specification for the 386ASM assembler for the Phar Lap ETS embedded
operating system.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/386asm.py 4720 2010/03/24 03:14:11 jars"
from SCons.Tool.PharLapCommon import addPharLapPaths
import SCons.Util
as_module = __import__('as', globals(), locals(), [])
def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
as_module.generate(env)
env['AS'] = '386asm'
env['ASFLAGS'] = SCons.Util.CLVar('')
env['ASPPFLAGS'] = '$ASFLAGS'
env['ASCOM'] = '$AS $ASFLAGS $SOURCES -o $TARGET'
env['ASPPCOM'] = '$CC $ASPPFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $SOURCES -o $TARGET'
addPharLapPaths(env)
def exists(env):
return env.Detect('386asm')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.javah
Tool-specific initialization for javah.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/javah.py 4720 2010/03/24 03:14:11 jars"
import os.path
import string
import SCons.Action
import SCons.Builder
import SCons.Node.FS
import SCons.Tool.javac
import SCons.Util
def emit_java_headers(target, source, env):
"""Create and return lists of Java stub header files that will
be created from a set of class files.
"""
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
classdir = env.get('JAVACLASSDIR')
if not classdir:
try:
s = source[0]
except IndexError:
classdir = '.'
else:
try:
classdir = s.attributes.java_classdir
except AttributeError:
classdir = '.'
classdir = env.Dir(classdir).rdir()
if str(classdir) == '.':
c_ = None
else:
c_ = str(classdir) + os.sep
slist = []
for src in source:
try:
classname = src.attributes.java_classname
except AttributeError:
classname = str(src)
if c_ and classname[:len(c_)] == c_:
classname = classname[len(c_):]
if class_suffix and classname[-len(class_suffix):] == class_suffix:
classname = classname[:-len(class_suffix)]
classname = SCons.Tool.javac.classname(classname)
s = src.rfile()
s.attributes.java_classname = classname
slist.append(s)
s = source[0].rfile()
if not hasattr(s.attributes, 'java_classdir'):
s.attributes.java_classdir = classdir
if target[0].__class__ is SCons.Node.FS.File:
tlist = target
else:
if not isinstance(target[0], SCons.Node.FS.Dir):
target[0].__class__ = SCons.Node.FS.Dir
target[0]._morph()
tlist = []
for s in source:
fname = string.replace(s.attributes.java_classname, '.', '_') + '.h'
t = target[0].File(fname)
t.attributes.java_lookupdir = target[0]
tlist.append(t)
return tlist, source
def JavaHOutFlagGenerator(target, source, env, for_signature):
try:
t = target[0]
except (AttributeError, IndexError, TypeError):
t = target
try:
return '-d ' + str(t.attributes.java_lookupdir)
except AttributeError:
return '-o ' + str(t)
def getJavaHClassPath(env,target, source, for_signature):
path = "${SOURCE.attributes.java_classdir}"
if env.has_key('JAVACLASSPATH') and env['JAVACLASSPATH']:
path = SCons.Util.AppendPath(path, env['JAVACLASSPATH'])
return "-classpath %s" % (path)
def generate(env):
"""Add Builders and construction variables for javah to an Environment."""
java_javah = SCons.Tool.CreateJavaHBuilder(env)
java_javah.emitter = emit_java_headers
env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator
env['JAVAH'] = 'javah'
env['JAVAHFLAGS'] = SCons.Util.CLVar('')
env['_JAVAHCLASSPATH'] = getJavaHClassPath
env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}'
env['JAVACLASSSUFFIX'] = '.class'
def exists(env):
return env.Detect('javah')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.icl
Tool-specific initialization for the Intel C/C++ compiler.
Supports Linux and Windows compilers, v7 and up.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/intelc.py 4720 2010/03/24 03:14:11 jars"
import math, sys, os.path, glob, string, re
is_windows = sys.platform == 'win32'
is_win64 = is_windows and (os.environ['PROCESSOR_ARCHITECTURE'] == 'AMD64' or
(os.environ.has_key('PROCESSOR_ARCHITEW6432') and
os.environ['PROCESSOR_ARCHITEW6432'] == 'AMD64'))
is_linux = sys.platform == 'linux2'
is_mac = sys.platform == 'darwin'
if is_windows:
import SCons.Tool.msvc
elif is_linux:
import SCons.Tool.gcc
elif is_mac:
import SCons.Tool.gcc
import SCons.Util
import SCons.Warnings
# Exceptions for this tool
class IntelCError(SCons.Errors.InternalError):
pass
class MissingRegistryError(IntelCError): # missing registry entry
pass
class MissingDirError(IntelCError): # dir not found
pass
class NoRegistryModuleError(IntelCError): # can't read registry at all
pass
def uniquify(s):
"""Return a sequence containing only one copy of each unique element from input sequence s.
Does not preserve order.
Input sequence must be hashable (i.e. must be usable as a dictionary key)."""
u = {}
for x in s:
u[x] = 1
return u.keys()
def linux_ver_normalize(vstr):
"""Normalize a Linux compiler version number.
Intel changed from "80" to "9.0" in 2005, so we assume if the number
is greater than 60 it's an old-style number and otherwise new-style.
Always returns an old-style float like 80 or 90 for compatibility with Windows.
Shades of Y2K!"""
# Check for version number like 9.1.026: return 91.026
m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', vstr)
if m:
vmaj,vmin,build = m.groups()
return float(vmaj) * 10 + float(vmin) + float(build) / 1000.;
else:
f = float(vstr)
if is_windows:
return f
else:
if f < 60: return f * 10.0
else: return f
def check_abi(abi):
"""Check for valid ABI (application binary interface) name,
and map into canonical one"""
if not abi:
return None
abi = abi.lower()
# valid_abis maps input name to canonical name
if is_windows:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'ia64' : 'ia64',
'em64t' : 'em64t',
'amd64' : 'em64t'}
if is_linux:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'x86_64' : 'x86_64',
'em64t' : 'x86_64',
'amd64' : 'x86_64'}
if is_mac:
valid_abis = {'ia32' : 'ia32',
'x86' : 'ia32',
'x86_64' : 'x86_64',
'em64t' : 'x86_64'}
try:
abi = valid_abis[abi]
except KeyError:
raise SCons.Errors.UserError, \
"Intel compiler: Invalid ABI %s, valid values are %s"% \
(abi, valid_abis.keys())
return abi
def vercmp(a, b):
"""Compare strings as floats,
but Intel changed Linux naming convention at 9.0"""
return cmp(linux_ver_normalize(b), linux_ver_normalize(a))
def get_version_from_list(v, vlist):
"""See if we can match v (string) in vlist (list of strings)
Linux has to match in a fuzzy way."""
if is_windows:
# Simple case, just find it in the list
if v in vlist: return v
else: return None
else:
# Fuzzy match: normalize version number first, but still return
# original non-normalized form.
fuzz = 0.001
for vi in vlist:
if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz:
return vi
# Not found
return None
def get_intel_registry_value(valuename, version=None, abi=None):
"""
Return a value from the Intel compiler registry tree. (Windows only)
"""
# Open the key:
if is_win64:
K = 'Software\\Wow6432Node\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
else:
K = 'Software\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
try:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K)
except SCons.Util.RegError:
raise MissingRegistryError, \
"%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi)
# Get the value:
try:
v = SCons.Util.RegQueryValueEx(k, valuename)[0]
return v # or v.encode('iso-8859-1', 'replace') to remove unicode?
except SCons.Util.RegError:
raise MissingRegistryError, \
"%s\\%s was not found in the registry."%(K, valuename)
def get_all_compiler_versions():
"""Returns a sorted list of strings, like "70" or "80" or "9.0"
with most recent compiler version first.
"""
versions=[]
if is_windows:
if is_win64:
keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++'
else:
keyname = 'Software\\Intel\\Compilers\\C++'
try:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
keyname)
except WindowsError:
return []
i = 0
versions = []
try:
while i < 100:
subkey = SCons.Util.RegEnumKey(k, i) # raises EnvironmentError
# Check that this refers to an existing dir.
# This is not 100% perfect but should catch common
# installation issues like when the compiler was installed
# and then the install directory deleted or moved (rather
# than uninstalling properly), so the registry values
# are still there.
ok = False
for try_abi in ('IA32', 'IA32e', 'IA64', 'EM64T'):
try:
d = get_intel_registry_value('ProductDir', subkey, try_abi)
except MissingRegistryError:
continue # not found in reg, keep going
if os.path.exists(d): ok = True
if ok:
versions.append(subkey)
else:
try:
# Registry points to nonexistent dir. Ignore this
# version.
value = get_intel_registry_value('ProductDir', subkey, 'IA32')
except MissingRegistryError, e:
# Registry key is left dangling (potentially
# after uninstalling).
print \
"scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \
"scons: *** It seems that the compiler was uninstalled and that the registry\n" \
"scons: *** was not cleaned up properly.\n" % subkey
else:
print "scons: *** Ignoring "+str(value)
i = i + 1
except EnvironmentError:
# no more subkeys
pass
elif is_linux:
for d in glob.glob('/opt/intel_cc_*'):
# Typical dir here is /opt/intel_cc_80.
m = re.search(r'cc_(.*)$', d)
if m:
versions.append(m.group(1))
for d in glob.glob('/opt/intel/cc*/*'):
# Typical dir here is /opt/intel/cc/9.0 for IA32,
# /opt/intel/cce/9.0 for EMT64 (AMD64)
m = re.search(r'([0-9.]+)$', d)
if m:
versions.append(m.group(1))
elif is_mac:
for d in glob.glob('/opt/intel/cc*/*'):
# Typical dir here is /opt/intel/cc/9.0 for IA32,
# /opt/intel/cce/9.0 for EMT64 (AMD64)
m = re.search(r'([0-9.]+)$', d)
if m:
versions.append(m.group(1))
versions = uniquify(versions) # remove dups
versions.sort(vercmp)
return versions
def get_intel_compiler_top(version, abi):
"""
Return the main path to the top-level dir of the Intel compiler,
using the given version.
The compiler will be in <top>/bin/icl.exe (icc on linux),
the include dir is <top>/include, etc.
"""
if is_windows:
if not SCons.Util.can_read_reg:
raise NoRegistryModuleError, "No Windows registry module was found"
top = get_intel_registry_value('ProductDir', version, abi)
# pre-11, icl was in Bin. 11 and later, it's in Bin/<abi> apparently.
if not os.path.exists(os.path.join(top, "Bin", "icl.exe")) \
and not os.path.exists(os.path.join(top, "Bin", abi, "icl.exe")):
raise MissingDirError, \
"Can't find Intel compiler in %s"%(top)
elif is_mac or is_linux:
# first dir is new (>=9.0) style, second is old (8.0) style.
dirs=('/opt/intel/cc/%s', '/opt/intel_cc_%s')
if abi == 'x86_64':
dirs=('/opt/intel/cce/%s',) # 'e' stands for 'em64t', aka x86_64 aka amd64
top=None
for d in dirs:
if os.path.exists(os.path.join(d%version, "bin", "icc")):
top = d%version
break
if not top:
raise MissingDirError, \
"Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi)
return top
def generate(env, version=None, abi=None, topdir=None, verbose=0):
"""Add Builders and construction variables for Intel C/C++ compiler
to an Environment.
args:
version: (string) compiler version to use, like "80"
abi: (string) 'win32' or whatever Itanium version wants
topdir: (string) compiler top dir, like
"c:\Program Files\Intel\Compiler70"
If topdir is used, version and abi are ignored.
verbose: (int) if >0, prints compiler version used.
"""
if not (is_mac or is_linux or is_windows):
# can't handle this platform
return
if is_windows:
SCons.Tool.msvc.generate(env)
elif is_linux:
SCons.Tool.gcc.generate(env)
elif is_mac:
SCons.Tool.gcc.generate(env)
# if version is unspecified, use latest
vlist = get_all_compiler_versions()
if not version:
if vlist:
version = vlist[0]
else:
# User may have specified '90' but we need to get actual dirname '9.0'.
# get_version_from_list does that mapping.
v = get_version_from_list(version, vlist)
if not v:
raise SCons.Errors.UserError, \
"Invalid Intel compiler version %s: "%version + \
"installed versions are %s"%(', '.join(vlist))
version = v
# if abi is unspecified, use ia32
# alternatives are ia64 for Itanium, or amd64 or em64t or x86_64 (all synonyms here)
abi = check_abi(abi)
if abi is None:
if is_mac or is_linux:
# Check if we are on 64-bit linux, default to 64 then.
uname_m = os.uname()[4]
if uname_m == 'x86_64':
abi = 'x86_64'
else:
abi = 'ia32'
else:
if is_win64:
abi = 'em64t'
else:
abi = 'ia32'
if version and not topdir:
try:
topdir = get_intel_compiler_top(version, abi)
except (SCons.Util.RegError, IntelCError):
topdir = None
if not topdir:
# Normally this is an error, but it might not be if the compiler is
# on $PATH and the user is importing their env.
class ICLTopDirWarning(SCons.Warnings.Warning):
pass
if (is_mac or is_linux) and not env.Detect('icc') or \
is_windows and not env.Detect('icl'):
SCons.Warnings.enableWarningClass(ICLTopDirWarning)
SCons.Warnings.warn(ICLTopDirWarning,
"Failed to find Intel compiler for version='%s', abi='%s'"%
(str(version), str(abi)))
else:
# should be cleaned up to say what this other version is
# since in this case we have some other Intel compiler installed
SCons.Warnings.enableWarningClass(ICLTopDirWarning)
SCons.Warnings.warn(ICLTopDirWarning,
"Can't find Intel compiler top dir for version='%s', abi='%s'"%
(str(version), str(abi)))
if topdir:
if verbose:
print "Intel C compiler: using version %s (%g), abi %s, in '%s'"%\
(repr(version), linux_ver_normalize(version),abi,topdir)
if is_linux:
# Show the actual compiler version by running the compiler.
os.system('%s/bin/icc --version'%topdir)
if is_mac:
# Show the actual compiler version by running the compiler.
os.system('%s/bin/icc --version'%topdir)
env['INTEL_C_COMPILER_TOP'] = topdir
if is_linux:
paths={'INCLUDE' : 'include',
'LIB' : 'lib',
'PATH' : 'bin',
'LD_LIBRARY_PATH' : 'lib'}
for p in paths.keys():
env.PrependENVPath(p, os.path.join(topdir, paths[p]))
if is_mac:
paths={'INCLUDE' : 'include',
'LIB' : 'lib',
'PATH' : 'bin',
'LD_LIBRARY_PATH' : 'lib'}
for p in paths.keys():
env.PrependENVPath(p, os.path.join(topdir, paths[p]))
if is_windows:
# env key reg valname default subdir of top
paths=(('INCLUDE', 'IncludeDir', 'Include'),
('LIB' , 'LibDir', 'Lib'),
('PATH' , 'BinDir', 'Bin'))
# We are supposed to ignore version if topdir is set, so set
# it to the emptry string if it's not already set.
if version is None:
version = ''
# Each path has a registry entry, use that or default to subdir
for p in paths:
try:
path=get_intel_registry_value(p[1], version, abi)
# These paths may have $(ICInstallDir)
# which needs to be substituted with the topdir.
path=path.replace('$(ICInstallDir)', topdir + os.sep)
except IntelCError:
# Couldn't get it from registry: use default subdir of topdir
env.PrependENVPath(p[0], os.path.join(topdir, p[2]))
else:
env.PrependENVPath(p[0], string.split(path, os.pathsep))
# print "ICL %s: %s, final=%s"%(p[0], path, str(env['ENV'][p[0]]))
if is_windows:
env['CC'] = 'icl'
env['CXX'] = 'icl'
env['LINK'] = 'xilink'
else:
env['CC'] = 'icc'
env['CXX'] = 'icpc'
# Don't reset LINK here;
# use smart_link which should already be here from link.py.
#env['LINK'] = '$CC'
env['AR'] = 'xiar'
env['LD'] = 'xild' # not used by default
# This is not the exact (detailed) compiler version,
# just the major version as determined above or specified
# by the user. It is a float like 80 or 90, in normalized form for Linux
# (i.e. even for Linux 9.0 compiler, still returns 90 rather than 9.0)
if version:
env['INTEL_C_COMPILER_VERSION']=linux_ver_normalize(version)
if is_windows:
# Look for license file dir
# in system environment, registry, and default location.
envlicdir = os.environ.get("INTEL_LICENSE_FILE", '')
K = ('SOFTWARE\Intel\Licenses')
try:
k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K)
reglicdir = SCons.Util.RegQueryValueEx(k, "w_cpp")[0]
except (AttributeError, SCons.Util.RegError):
reglicdir = ""
defaultlicdir = r'C:\Program Files\Common Files\Intel\Licenses'
licdir = None
for ld in [envlicdir, reglicdir]:
# If the string contains an '@', then assume it's a network
# license (port@system) and good by definition.
if ld and (string.find(ld, '@') != -1 or os.path.exists(ld)):
licdir = ld
break
if not licdir:
licdir = defaultlicdir
if not os.path.exists(licdir):
class ICLLicenseDirWarning(SCons.Warnings.Warning):
pass
SCons.Warnings.enableWarningClass(ICLLicenseDirWarning)
SCons.Warnings.warn(ICLLicenseDirWarning,
"Intel license dir was not found."
" Tried using the INTEL_LICENSE_FILE environment variable (%s), the registry (%s) and the default path (%s)."
" Using the default path as a last resort."
% (envlicdir, reglicdir, defaultlicdir))
env['ENV']['INTEL_LICENSE_FILE'] = licdir
def exists(env):
if not (is_mac or is_linux or is_windows):
# can't handle this platform
return 0
try:
versions = get_all_compiler_versions()
except (SCons.Util.RegError, IntelCError):
versions = None
detected = versions is not None and len(versions) > 0
if not detected:
# try env.Detect, maybe that will work
if is_windows:
return env.Detect('icl')
elif is_linux:
return env.Detect('icc')
elif is_mac:
return env.Detect('icc')
return detected
# end of file
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Subversion.py
Tool-specific initialization for Subversion.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/Subversion.py 4720 2010/03/24 03:14:11 jars"
import os.path
import SCons.Action
import SCons.Builder
import SCons.Util
def generate(env):
"""Add a Builder factory function and construction variables for
Subversion to an Environment."""
def SubversionFactory(repos, module='', env=env):
""" """
# fail if repos is not an absolute path name?
if module != '':
module = os.path.join(module, '')
act = SCons.Action.Action('$SVNCOM', '$SVNCOMSTR')
return SCons.Builder.Builder(action = act,
env = env,
SVNREPOSITORY = repos,
SVNMODULE = module)
#setattr(env, 'Subversion', SubversionFactory)
env.Subversion = SubversionFactory
env['SVN'] = 'svn'
env['SVNFLAGS'] = SCons.Util.CLVar('')
env['SVNCOM'] = '$SVN $SVNFLAGS cat $SVNREPOSITORY/$SVNMODULE$TARGET > $TARGET'
def exists(env):
return env.Detect('svn')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
# -*- python -*-
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__doc__ = """
Textfile/Substfile builder for SCons.
Create file 'target' which typically is a textfile. The 'source'
may be any combination of strings, Nodes, or lists of same. A
'linesep' will be put between any part written and defaults to
os.linesep.
The only difference between the Textfile builder and the Substfile
builder is that strings are converted to Value() nodes for the
former and File() nodes for the latter. To insert files in the
former or strings in the latter, wrap them in a File() or Value(),
respectively.
The values of SUBST_DICT first have any construction variables
expanded (its keys are not expanded). If a value of SUBST_DICT is
a python callable function, it is called and the result is expanded
as the value. Values are substituted in a "random" order; if any
substitution could be further expanded by another subsitition, it
is unpredictible whether the expansion will occur.
"""
__revision__ = "src/engine/SCons/Tool/textfile.py 4720 2010/03/24 03:14:11 jars"
import SCons
import os
import re
from SCons.Node import Node
from SCons.Node.Python import Value
from SCons.Util import is_String, is_Sequence, is_Dict
def _do_subst(node, subs):
"""
Fetch the node contents and replace all instances of the keys with
their values. For example, if subs is
{'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'},
then all instances of %VERSION% in the file will be replaced with
1.2345 and so forth.
"""
contents = node.get_text_contents()
if not subs: return contents
for (k,v) in subs:
contents = re.sub(k, v, contents)
return contents
def _action(target, source, env):
# prepare the line separator
linesep = env['LINESEPARATOR']
if linesep is None:
linesep = os.linesep
elif is_String(linesep):
pass
elif isinstance(linesep, Value):
linesep = linesep.get_text_contents()
else:
raise SCons.Errors.UserError(
'unexpected type/class for LINESEPARATOR: %s'
% repr(linesep), None)
# create a dictionary to use for the substitutions
if not env.has_key('SUBST_DICT'):
subs = None # no substitutions
else:
d = env['SUBST_DICT']
if is_Dict(d):
d = d.items()
elif is_Sequence(d):
pass
else:
raise SCons.Errors.UserError('SUBST_DICT must be dict or sequence')
subs = []
for (k,v) in d:
if callable(v):
v = v()
if is_String(v):
v = env.subst(v)
else:
v = str(v)
subs.append((k,v))
# write the file
try:
fd = open(target[0].get_path(), "wb")
except (OSError,IOError), e:
raise SCons.Errors.UserError("Can't write target file %s" % target[0])
# separate lines by 'linesep' only if linesep is not empty
lsep = None
for s in source:
if lsep: fd.write(lsep)
fd.write(_do_subst(s, subs))
lsep = linesep
fd.close()
def _strfunc(target, source, env):
return "Creating '%s'" % target[0]
def _convert_list_R(newlist, sources):
for elem in sources:
if is_Sequence(elem):
_convert_list_R(newlist, elem)
elif isinstance(elem, Node):
newlist.append(elem)
else:
newlist.append(Value(elem))
def _convert_list(target, source, env):
if len(target) != 1:
raise SCons.Errors.UserError("Only one target file allowed")
newlist = []
_convert_list_R(newlist, source)
return target, newlist
_common_varlist = ['SUBST_DICT', 'LINESEPARATOR']
_text_varlist = _common_varlist + ['TEXTFILEPREFIX', 'TEXTFILESUFFIX']
_text_builder = SCons.Builder.Builder(
action = SCons.Action.Action(_action, _strfunc, varlist = _text_varlist),
source_factory = Value,
emitter = _convert_list,
prefix = '$TEXTFILEPREFIX',
suffix = '$TEXTFILESUFFIX',
)
_subst_varlist = _common_varlist + ['SUBSTFILEPREFIX', 'TEXTFILESUFFIX']
_subst_builder = SCons.Builder.Builder(
action = SCons.Action.Action(_action, _strfunc, varlist = _subst_varlist),
source_factory = SCons.Node.FS.File,
emitter = _convert_list,
prefix = '$SUBSTFILEPREFIX',
suffix = '$SUBSTFILESUFFIX',
src_suffix = ['.in'],
)
def generate(env):
env['LINESEPARATOR'] = os.linesep
env['BUILDERS']['Textfile'] = _text_builder
env['TEXTFILEPREFIX'] = ''
env['TEXTFILESUFFIX'] = '.txt'
env['BUILDERS']['Substfile'] = _subst_builder
env['SUBSTFILEPREFIX'] = ''
env['SUBSTFILESUFFIX'] = ''
def exists(env):
return 1
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.g++
Tool-specific initialization for g++.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/g++.py 4720 2010/03/24 03:14:11 jars"
import os.path
import re
import subprocess
import SCons.Tool
import SCons.Util
cplusplus = __import__('c++', globals(), locals(), [])
compilers = ['g++']
def generate(env):
"""Add Builders and construction variables for g++ to an Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
cplusplus.generate(env)
env['CXX'] = env.Detect(compilers)
# platform specific settings
if env['PLATFORM'] == 'aix':
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -mminimal-toc')
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1
env['SHOBJSUFFIX'] = '$OBJSUFFIX'
elif env['PLATFORM'] == 'hpux':
env['SHOBJSUFFIX'] = '.pic.o'
elif env['PLATFORM'] == 'sunos':
env['SHOBJSUFFIX'] = '.pic.o'
# determine compiler version
if env['CXX']:
#pipe = SCons.Action._subproc(env, [env['CXX'], '-dumpversion'],
pipe = SCons.Action._subproc(env, [env['CXX'], '--version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
# -dumpversion was added in GCC 3.0. As long as we're supporting
# GCC versions older than that, we should use --version and a
# regular expression.
#line = pipe.stdout.read().strip()
#if line:
# env['CXXVERSION'] = line
line = pipe.stdout.readline()
match = re.search(r'[0-9]+(\.[0-9]+)+', line)
if match:
env['CXXVERSION'] = match.group(0)
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.ipkg
Tool-specific initialization for ipkg.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
The ipkg tool calls the ipkg-build. Its only argument should be the
packages fake_root.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/ipkg.py 4720 2010/03/24 03:14:11 jars"
import os
import string
import SCons.Builder
def generate(env):
"""Add Builders and construction variables for ipkg to an Environment."""
try:
bld = env['BUILDERS']['Ipkg']
except KeyError:
bld = SCons.Builder.Builder( action = '$IPKGCOM',
suffix = '$IPKGSUFFIX',
source_scanner = None,
target_scanner = None)
env['BUILDERS']['Ipkg'] = bld
env['IPKG'] = 'ipkg-build'
env['IPKGCOM'] = '$IPKG $IPKGFLAGS ${SOURCE}'
# TODO(1.5)
#env['IPKGUSER'] = os.popen('id -un').read().strip()
#env['IPKGGROUP'] = os.popen('id -gn').read().strip()
env['IPKGUSER'] = string.strip(os.popen('id -un').read())
env['IPKGGROUP'] = string.strip(os.popen('id -gn').read())
env['IPKGFLAGS'] = SCons.Util.CLVar('-o $IPKGUSER -g $IPKGGROUP')
env['IPKGSUFFIX'] = '.ipk'
def exists(env):
return env.Detect('ipkg-build')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.aixc++
Tool-specific initialization for IBM xlC / Visual Age C++ compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/aixc++.py 4720 2010/03/24 03:14:11 jars"
import os.path
import SCons.Platform.aix
cplusplus = __import__('c++', globals(), locals(), [])
packages = ['vacpp.cmp.core', 'vacpp.cmp.batch', 'vacpp.cmp.C', 'ibmcxx.cmp']
def get_xlc(env):
xlc = env.get('CXX', 'xlC')
xlc_r = env.get('SHCXX', 'xlC_r')
return SCons.Platform.aix.get_xlc(env, xlc, xlc_r, packages)
def smart_cxxflags(source, target, env, for_signature):
build_dir = env.GetBuildPath()
if build_dir:
return '-qtempinc=' + os.path.join(build_dir, 'tempinc')
return ''
def generate(env):
"""Add Builders and construction variables for xlC / Visual Age
suite to an Environment."""
path, _cxx, _shcxx, version = get_xlc(env)
if path:
_cxx = os.path.join(path, _cxx)
_shcxx = os.path.join(path, _shcxx)
cplusplus.generate(env)
env['CXX'] = _cxx
env['SHCXX'] = _shcxx
env['CXXVERSION'] = version
env['SHOBJSUFFIX'] = '.pic.o'
def exists(env):
path, _cxx, _shcxx, version = get_xlc(env)
if path and _cxx:
xlc = os.path.join(path, _cxx)
if os.path.exists(xlc):
return xlc
return None
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.ifort
Tool-specific initialization for newer versions of the Intel Fortran Compiler
for Linux/Windows (and possibly Mac OS X).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/ifort.py 4720 2010/03/24 03:14:11 jars"
import string
import SCons.Defaults
from SCons.Scanner.Fortran import FortranScan
from FortranCommon import add_all_to_env
def generate(env):
"""Add Builders and construction variables for ifort to an Environment."""
# ifort supports Fortran 90 and Fortran 95
# Additionally, ifort recognizes more file extensions.
fscan = FortranScan("FORTRANPATH")
SCons.Tool.SourceFileScanner.add_scanner('.i', fscan)
SCons.Tool.SourceFileScanner.add_scanner('.i90', fscan)
if not env.has_key('FORTRANFILESUFFIXES'):
env['FORTRANFILESUFFIXES'] = ['.i']
else:
env['FORTRANFILESUFFIXES'].append('.i')
if not env.has_key('F90FILESUFFIXES'):
env['F90FILESUFFIXES'] = ['.i90']
else:
env['F90FILESUFFIXES'].append('.i90')
add_all_to_env(env)
fc = 'ifort'
for dialect in ['F77', 'F90', 'FORTRAN', 'F95']:
env['%s' % dialect] = fc
env['SH%s' % dialect] = '$%s' % dialect
if env['PLATFORM'] == 'posix':
env['SH%sFLAGS' % dialect] = SCons.Util.CLVar('$%sFLAGS -fPIC' % dialect)
if env['PLATFORM'] == 'win32':
# On Windows, the ifort compiler specifies the object on the
# command line with -object:, not -o. Massage the necessary
# command-line construction variables.
for dialect in ['F77', 'F90', 'FORTRAN', 'F95']:
for var in ['%sCOM' % dialect, '%sPPCOM' % dialect,
'SH%sCOM' % dialect, 'SH%sPPCOM' % dialect]:
env[var] = string.replace(env[var], '-o $TARGET', '-object:$TARGET')
env['FORTRANMODDIRPREFIX'] = "/module:"
else:
env['FORTRANMODDIRPREFIX'] = "-module "
def exists(env):
return env.Detect('ifort')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.tlib
XXX
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/tlib.py 4720 2010/03/24 03:14:11 jars"
import SCons.Tool
import SCons.Tool.bcc32
import SCons.Util
def generate(env):
SCons.Tool.bcc32.findIt('tlib', env)
"""Add Builders and construction variables for ar to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
env['AR'] = 'tlib'
env['ARFLAGS'] = SCons.Util.CLVar('')
env['ARCOM'] = '$AR $TARGET $ARFLAGS /a $SOURCES'
env['LIBPREFIX'] = ''
env['LIBSUFFIX'] = '.lib'
def exists(env):
return SCons.Tool.bcc32.findIt('tlib', env)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.jar
Tool-specific initialization for jar.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/jar.py 4720 2010/03/24 03:14:11 jars"
import SCons.Subst
import SCons.Util
def jarSources(target, source, env, for_signature):
"""Only include sources that are not a manifest file."""
try:
env['JARCHDIR']
except KeyError:
jarchdir_set = False
else:
jarchdir_set = True
jarchdir = env.subst('$JARCHDIR', target=target, source=source)
if jarchdir:
jarchdir = env.fs.Dir(jarchdir)
result = []
for src in source:
contents = src.get_text_contents()
if contents[:16] != "Manifest-Version":
if jarchdir_set:
_chdir = jarchdir
else:
try:
_chdir = src.attributes.java_classdir
except AttributeError:
_chdir = None
if _chdir:
# If we are changing the dir with -C, then sources should
# be relative to that directory.
src = SCons.Subst.Literal(src.get_path(_chdir))
result.append('-C')
result.append(_chdir)
result.append(src)
return result
def jarManifest(target, source, env, for_signature):
"""Look in sources for a manifest file, if any."""
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
return src
return ''
def jarFlags(target, source, env, for_signature):
"""If we have a manifest, make sure that the 'm'
flag is specified."""
jarflags = env.subst('$JARFLAGS', target=target, source=source)
for src in source:
contents = src.get_text_contents()
if contents[:16] == "Manifest-Version":
if not 'm' in jarflags:
return jarflags + 'm'
break
return jarflags
def generate(env):
"""Add Builders and construction variables for jar to an Environment."""
SCons.Tool.CreateJarBuilder(env)
env['JAR'] = 'jar'
env['JARFLAGS'] = SCons.Util.CLVar('cf')
env['_JARFLAGS'] = jarFlags
env['_JARMANIFEST'] = jarManifest
env['_JARSOURCES'] = jarSources
env['_JARCOM'] = '$JAR $_JARFLAGS $TARGET $_JARMANIFEST $_JARSOURCES'
env['JARCOM'] = "${TEMPFILE('$_JARCOM')}"
env['JARSUFFIX'] = '.jar'
def exists(env):
return env.Detect('jar')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/mssdk.py 4720 2010/03/24 03:14:11 jars"
"""engine.SCons.Tool.mssdk
Tool-specific initialization for Microsoft SDKs, both Platform
SDKs and Windows SDKs.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
from MSCommon import mssdk_exists, \
mssdk_setup_env
def generate(env):
"""Add construction variables for an MS SDK to an Environment."""
mssdk_setup_env(env)
def exists(env):
return mssdk_exists()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.c++
Tool-specific initialization for generic Posix C++ compilers.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/c++.py 4720 2010/03/24 03:14:11 jars"
import os.path
import SCons.Tool
import SCons.Defaults
import SCons.Util
compilers = ['CC', 'c++']
CXXSuffixes = ['.cpp', '.cc', '.cxx', '.c++', '.C++', '.mm']
if SCons.Util.case_sensitive_suffixes('.c', '.C'):
CXXSuffixes.append('.C')
def iscplusplus(source):
if not source:
# Source might be None for unusual cases like SConf.
return 0
for s in source:
if s.sources:
ext = os.path.splitext(str(s.sources[0]))[1]
if ext in CXXSuffixes:
return 1
return 0
def generate(env):
"""
Add Builders and construction variables for Visual Age C++ compilers
to an Environment.
"""
import SCons.Tool
import SCons.Tool.cc
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CXXAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
SCons.Tool.cc.add_common_cc_variables(env)
env['CXX'] = 'c++'
env['CXXFLAGS'] = SCons.Util.CLVar('')
env['CXXCOM'] = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES'
env['SHCXX'] = '$CXX'
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
env['SHCXXCOM'] = '$SHCXX -o $TARGET -c $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM $SOURCES'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
env['SHOBJSUFFIX'] = '.os'
env['OBJSUFFIX'] = '.o'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0
env['CXXFILESUFFIX'] = '.cc'
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.linkloc
Tool specification for the LinkLoc linker for the Phar Lap ETS embedded
operating system.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/linkloc.py 4720 2010/03/24 03:14:11 jars"
import os.path
import re
import SCons.Action
import SCons.Defaults
import SCons.Errors
import SCons.Tool
import SCons.Util
from SCons.Tool.MSCommon import msvs_exists, merge_default_version
from SCons.Tool.PharLapCommon import addPharLapPaths
_re_linker_command = re.compile(r'(\s)@\s*([^\s]+)')
def repl_linker_command(m):
# Replaces any linker command file directives (e.g. "@foo.lnk") with
# the actual contents of the file.
try:
f=open(m.group(2), "r")
return m.group(1) + f.read()
except IOError:
# the linker should return an error if it can't
# find the linker command file so we will remain quiet.
# However, we will replace the @ with a # so we will not continue
# to find it with recursive substitution
return m.group(1) + '#' + m.group(2)
class LinklocGenerator:
def __init__(self, cmdline):
self.cmdline = cmdline
def __call__(self, env, target, source, for_signature):
if for_signature:
# Expand the contents of any linker command files recursively
subs = 1
strsub = env.subst(self.cmdline, target=target, source=source)
while subs:
strsub, subs = _re_linker_command.subn(repl_linker_command, strsub)
return strsub
else:
return "${TEMPFILE('" + self.cmdline + "')}"
def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['SUBST_CMD_FILE'] = LinklocGenerator
env['SHLINK'] = '$LINK'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS')
env['SHLINKCOM'] = '${SUBST_CMD_FILE("$SHLINK $SHLINKFLAGS $_LIBDIRFLAGS $_LIBFLAGS -dll $TARGET $SOURCES")}'
env['SHLIBEMITTER']= None
env['LINK'] = "linkloc"
env['LINKFLAGS'] = SCons.Util.CLVar('')
env['LINKCOM'] = '${SUBST_CMD_FILE("$LINK $LINKFLAGS $_LIBDIRFLAGS $_LIBFLAGS -exe $TARGET $SOURCES")}'
env['LIBDIRPREFIX']='-libpath '
env['LIBDIRSUFFIX']=''
env['LIBLINKPREFIX']='-lib '
env['LIBLINKSUFFIX']='$LIBSUFFIX'
# Set-up ms tools paths for default version
merge_default_version(env)
addPharLapPaths(env)
def exists(env):
if msvs_exists():
return env.Detect('linkloc')
else:
return 0
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.mwcc
Tool-specific initialization for the Metrowerks CodeWarrior compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/mwcc.py 4720 2010/03/24 03:14:11 jars"
import os
import os.path
import string
import SCons.Util
def set_vars(env):
"""Set MWCW_VERSION, MWCW_VERSIONS, and some codewarrior environment vars
MWCW_VERSIONS is set to a list of objects representing installed versions
MWCW_VERSION is set to the version object that will be used for building.
MWCW_VERSION can be set to a string during Environment
construction to influence which version is chosen, otherwise
the latest one from MWCW_VERSIONS is used.
Returns true if at least one version is found, false otherwise
"""
desired = env.get('MWCW_VERSION', '')
# return right away if the variables are already set
if isinstance(desired, MWVersion):
return 1
elif desired is None:
return 0
versions = find_versions()
version = None
if desired:
for v in versions:
if str(v) == desired:
version = v
elif versions:
version = versions[-1]
env['MWCW_VERSIONS'] = versions
env['MWCW_VERSION'] = version
if version is None:
return 0
env.PrependENVPath('PATH', version.clpath)
env.PrependENVPath('PATH', version.dllpath)
ENV = env['ENV']
ENV['CWFolder'] = version.path
ENV['LM_LICENSE_FILE'] = version.license
plus = lambda x: '+%s' % x
ENV['MWCIncludes'] = string.join(map(plus, version.includes), os.pathsep)
ENV['MWLibraries'] = string.join(map(plus, version.libs), os.pathsep)
return 1
def find_versions():
"""Return a list of MWVersion objects representing installed versions"""
versions = []
### This function finds CodeWarrior by reading from the registry on
### Windows. Some other method needs to be implemented for other
### platforms, maybe something that calls env.WhereIs('mwcc')
if SCons.Util.can_read_reg:
try:
HLM = SCons.Util.HKEY_LOCAL_MACHINE
product = 'SOFTWARE\\Metrowerks\\CodeWarrior\\Product Versions'
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
while 1:
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
try:
version = SCons.Util.RegQueryValueEx(name_key, 'VERSION')
path = SCons.Util.RegQueryValueEx(name_key, 'PATH')
mwv = MWVersion(version[0], path[0], 'Win32-X86')
versions.append(mwv)
except SCons.Util.RegError:
pass
i = i + 1
except SCons.Util.RegError:
pass
return versions
class MWVersion:
def __init__(self, version, path, platform):
self.version = version
self.path = path
self.platform = platform
self.clpath = os.path.join(path, 'Other Metrowerks Tools',
'Command Line Tools')
self.dllpath = os.path.join(path, 'Bin')
# The Metrowerks tools don't store any configuration data so they
# are totally dumb when it comes to locating standard headers,
# libraries, and other files, expecting all the information
# to be handed to them in environment variables. The members set
# below control what information scons injects into the environment
### The paths below give a normal build environment in CodeWarrior for
### Windows, other versions of CodeWarrior might need different paths.
msl = os.path.join(path, 'MSL')
support = os.path.join(path, '%s Support' % platform)
self.license = os.path.join(path, 'license.dat')
self.includes = [msl, support]
self.libs = [msl, support]
def __str__(self):
return self.version
CSuffixes = ['.c', '.C']
CXXSuffixes = ['.cc', '.cpp', '.cxx', '.c++', '.C++']
def generate(env):
"""Add Builders and construction variables for the mwcc to an Environment."""
import SCons.Defaults
import SCons.Tool
set_vars(env)
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in CSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
for suffix in CXXSuffixes:
static_obj.add_action(suffix, SCons.Defaults.CXXAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCXXAction)
env['CCCOMFLAGS'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -nolink -o $TARGET $SOURCES'
env['CC'] = 'mwcc'
env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CCCOMFLAGS'
env['CXX'] = 'mwcc'
env['CXXCOM'] = '$CXX $CXXFLAGS $CCCOMFLAGS'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = '$CCFLAGS'
env['SHCFLAGS'] = '$CFLAGS'
env['SHCCCOM'] = '$SHCC $SHCFLAGS $SHCCFLAGS $CCCOMFLAGS'
env['SHCXX'] = '$CXX'
env['SHCXXFLAGS'] = '$CXXFLAGS'
env['SHCXXCOM'] = '$SHCXX $SHCXXFLAGS $CCCOMFLAGS'
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cpp'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
#env['PCH'] = ?
#env['PCHSTOP'] = ?
def exists(env):
return set_vars(env)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.gas
Tool-specific initialization for as, the Gnu assembler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/gas.py 4720 2010/03/24 03:14:11 jars"
as_module = __import__('as', globals(), locals(), [])
assemblers = ['as', 'gas']
def generate(env):
"""Add Builders and construction variables for as to an Environment."""
as_module.generate(env)
env['AS'] = env.Detect(assemblers) or 'as'
def exists(env):
return env.Detect(assemblers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.applelink
Tool-specific initialization for the Apple gnu-like linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/applelink.py 4720 2010/03/24 03:14:11 jars"
import SCons.Util
# Even though the Mac is based on the GNU toolchain, it doesn't understand
# the -rpath option, so we use the "link" tool instead of "gnulink".
import link
def generate(env):
"""Add Builders and construction variables for applelink to an
Environment."""
link.generate(env)
env['FRAMEWORKPATHPREFIX'] = '-F'
env['_FRAMEWORKPATH'] = '${_concat(FRAMEWORKPATHPREFIX, FRAMEWORKPATH, "", __env__)}'
env['_FRAMEWORKS'] = '${_concat("-framework ", FRAMEWORKS, "", __env__)}'
env['LINKCOM'] = env['LINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -dynamiclib')
env['SHLINKCOM'] = env['SHLINKCOM'] + ' $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
# override the default for loadable modules, which are different
# on OS X than dynamic shared libs. echoing what XCode does for
# pre/suffixes:
env['LDMODULEPREFIX'] = ''
env['LDMODULESUFFIX'] = ''
env['LDMODULEFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -bundle')
env['LDMODULECOM'] = '$LDMODULE -o ${TARGET} $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS $_FRAMEWORKPATH $_FRAMEWORKS $FRAMEWORKSFLAGS'
def exists(env):
return env['PLATFORM'] == 'darwin'
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""engine.SCons.Tool.icc
Tool-specific initialization for the OS/2 icc compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/icc.py 4720 2010/03/24 03:14:11 jars"
import cc
def generate(env):
"""Add Builders and construction variables for the OS/2 to an Environment."""
cc.generate(env)
env['CC'] = 'icc'
env['CCCOM'] = '$CC $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET'
env['CXXCOM'] = '$CXX $CXXFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Fo$TARGET'
env['CPPDEFPREFIX'] = '/D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '/I'
env['INCSUFFIX'] = ''
env['CFILESUFFIX'] = '.c'
env['CXXFILESUFFIX'] = '.cc'
def exists(env):
return env.Detect('icc')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.bcc32
XXX
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/bcc32.py 4720 2010/03/24 03:14:11 jars"
import os
import os.path
import string
import SCons.Defaults
import SCons.Tool
import SCons.Util
def findIt(program, env):
# First search in the SCons path and then the OS path:
borwin = env.WhereIs(program) or SCons.Util.WhereIs(program)
if borwin:
dir = os.path.dirname(borwin)
env.PrependENVPath('PATH', dir)
return borwin
def generate(env):
findIt('bcc32', env)
"""Add Builders and construction variables for bcc to an
Environment."""
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
for suffix in ['.c', '.cpp']:
static_obj.add_action(suffix, SCons.Defaults.CAction)
shared_obj.add_action(suffix, SCons.Defaults.ShCAction)
static_obj.add_emitter(suffix, SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter(suffix, SCons.Defaults.SharedObjectEmitter)
env['CC'] = 'bcc32'
env['CCFLAGS'] = SCons.Util.CLVar('')
env['CFLAGS'] = SCons.Util.CLVar('')
env['CCCOM'] = '$CC -q $CFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['SHCC'] = '$CC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
env['SHCFLAGS'] = SCons.Util.CLVar('$CFLAGS')
env['SHCCCOM'] = '$SHCC -WD $SHCFLAGS $SHCCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -c -o$TARGET $SOURCES'
env['CPPDEFPREFIX'] = '-D'
env['CPPDEFSUFFIX'] = ''
env['INCPREFIX'] = '-I'
env['INCSUFFIX'] = ''
env['SHOBJSUFFIX'] = '.dll'
env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 0
env['CFILESUFFIX'] = '.cpp'
def exists(env):
return findIt('bcc32', env)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.sunf77
Tool-specific initialization for sunf77, the Sun Studio F77 compiler.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/sunf77.py 4720 2010/03/24 03:14:11 jars"
import SCons.Util
from FortranCommon import add_all_to_env
compilers = ['sunf77', 'f77']
def generate(env):
"""Add Builders and construction variables for sunf77 to an Environment."""
add_all_to_env(env)
fcomp = env.Detect(compilers) or 'f77'
env['FORTRAN'] = fcomp
env['F77'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['SHF77'] = '$F77'
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -KPIC')
env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -KPIC')
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.hpcc
Tool-specific initialization for HP aCC and cc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/hpcc.py 4720 2010/03/24 03:14:11 jars"
import SCons.Util
import cc
def generate(env):
"""Add Builders and construction variables for aCC & cc to an Environment."""
cc.generate(env)
env['CXX'] = 'aCC'
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS +Z')
def exists(env):
return env.Detect('aCC')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.gcc
Tool-specific initialization for gcc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/gcc.py 4720 2010/03/24 03:14:11 jars"
import cc
import os
import re
import subprocess
import SCons.Util
compilers = ['gcc', 'cc']
def generate(env):
"""Add Builders and construction variables for gcc to an Environment."""
cc.generate(env)
env['CC'] = env.Detect(compilers) or 'gcc'
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
else:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC')
# determine compiler version
if env['CC']:
#pipe = SCons.Action._subproc(env, [env['CC'], '-dumpversion'],
pipe = SCons.Action._subproc(env, [env['CC'], '--version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
# -dumpversion was added in GCC 3.0. As long as we're supporting
# GCC versions older than that, we should use --version and a
# regular expression.
#line = pipe.stdout.read().strip()
#if line:
# env['CCVERSION'] = line
line = pipe.stdout.readline()
match = re.search(r'[0-9]+(\.[0-9]+)+', line)
if match:
env['CCVERSION'] = match.group(0)
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.swig
Tool-specific initialization for swig.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/swig.py 4720 2010/03/24 03:14:11 jars"
import os.path
import re
import string
import subprocess
import SCons.Action
import SCons.Defaults
import SCons.Scanner
import SCons.Tool
import SCons.Util
SwigAction = SCons.Action.Action('$SWIGCOM', '$SWIGCOMSTR')
def swigSuffixEmitter(env, source):
if '-c++' in SCons.Util.CLVar(env.subst("$SWIGFLAGS", source=source)):
return '$SWIGCXXFILESUFFIX'
else:
return '$SWIGCFILESUFFIX'
# Match '%module test', as well as '%module(directors="1") test'
# Also allow for test to be quoted (SWIG permits double quotes, but not single)
_reModule = re.compile(r'%module(\s*\(.*\))?\s+("?)(.+)\2')
def _find_modules(src):
"""Find all modules referenced by %module lines in `src`, a SWIG .i file.
Returns a list of all modules, and a flag set if SWIG directors have
been requested (SWIG will generate an additional header file in this
case.)"""
directors = 0
mnames = []
try:
matches = _reModule.findall(open(src).read())
except IOError:
# If the file's not yet generated, guess the module name from the filename
matches = []
mnames.append(os.path.splitext(src)[0])
for m in matches:
mnames.append(m[2])
directors = directors or string.find(m[0], 'directors') >= 0
return mnames, directors
def _add_director_header_targets(target, env):
# Directors only work with C++ code, not C
suffix = env.subst(env['SWIGCXXFILESUFFIX'])
# For each file ending in SWIGCXXFILESUFFIX, add a new target director
# header by replacing the ending with SWIGDIRECTORSUFFIX.
for x in target[:]:
n = x.name
d = x.dir
if n[-len(suffix):] == suffix:
target.append(d.File(n[:-len(suffix)] + env['SWIGDIRECTORSUFFIX']))
def _swigEmitter(target, source, env):
swigflags = env.subst("$SWIGFLAGS", target=target, source=source)
flags = SCons.Util.CLVar(swigflags)
for src in source:
src = str(src.rfile())
mnames = None
if "-python" in flags and "-noproxy" not in flags:
if mnames is None:
mnames, directors = _find_modules(src)
if directors:
_add_director_header_targets(target, env)
python_files = map(lambda m: m + ".py", mnames)
outdir = env.subst('$SWIGOUTDIR', target=target, source=source)
# .py files should be generated in SWIGOUTDIR if specified,
# otherwise in the same directory as the target
if outdir:
python_files = map(lambda j, o=outdir, e=env:
e.fs.File(os.path.join(o, j)),
python_files)
else:
python_files = map(lambda m, d=target[0].dir:
d.File(m), python_files)
target.extend(python_files)
if "-java" in flags:
if mnames is None:
mnames, directors = _find_modules(src)
if directors:
_add_director_header_targets(target, env)
java_files = map(lambda m: [m + ".java", m + "JNI.java"], mnames)
java_files = SCons.Util.flatten(java_files)
outdir = env.subst('$SWIGOUTDIR', target=target, source=source)
if outdir:
java_files = map(lambda j, o=outdir: os.path.join(o, j), java_files)
java_files = map(env.fs.File, java_files)
for jf in java_files:
t_from_s = lambda t, p, s, x: t.dir
SCons.Util.AddMethod(jf, t_from_s, 'target_from_source')
target.extend(java_files)
return (target, source)
def _get_swig_version(env):
"""Run the SWIG command line tool to get and return the version number"""
pipe = SCons.Action._subproc(env, [env['SWIG'], '-version'],
stdin = 'devnull',
stderr = 'devnull',
stdout = subprocess.PIPE)
if pipe.wait() != 0: return
out = pipe.stdout.read()
match = re.search(r'SWIG Version\s+(\S+)$', out, re.MULTILINE)
if match:
return match.group(1)
def generate(env):
"""Add Builders and construction variables for swig to an Environment."""
c_file, cxx_file = SCons.Tool.createCFileBuilders(env)
c_file.suffix['.i'] = swigSuffixEmitter
cxx_file.suffix['.i'] = swigSuffixEmitter
c_file.add_action('.i', SwigAction)
c_file.add_emitter('.i', _swigEmitter)
cxx_file.add_action('.i', SwigAction)
cxx_file.add_emitter('.i', _swigEmitter)
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_file.suffix['.i'] = swigSuffixEmitter
java_file.add_action('.i', SwigAction)
java_file.add_emitter('.i', _swigEmitter)
env['SWIG'] = 'swig'
env['SWIGVERSION'] = _get_swig_version(env)
env['SWIGFLAGS'] = SCons.Util.CLVar('')
env['SWIGDIRECTORSUFFIX'] = '_wrap.h'
env['SWIGCFILESUFFIX'] = '_wrap$CFILESUFFIX'
env['SWIGCXXFILESUFFIX'] = '_wrap$CXXFILESUFFIX'
env['_SWIGOUTDIR'] = r'${"-outdir \"%s\"" % SWIGOUTDIR}'
env['SWIGPATH'] = []
env['SWIGINCPREFIX'] = '-I'
env['SWIGINCSUFFIX'] = ''
env['_SWIGINCFLAGS'] = '$( ${_concat(SWIGINCPREFIX, SWIGPATH, SWIGINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['SWIGCOM'] = '$SWIG -o $TARGET ${_SWIGOUTDIR} ${_SWIGINCFLAGS} $SWIGFLAGS $SOURCES'
expr = '^[ \t]*%[ \t]*(?:include|import|extern)[ \t]*(<|"?)([^>\s"]+)(?:>|"?)'
scanner = SCons.Scanner.ClassicCPP("SWIGScan", ".i", "SWIGPATH", expr)
env.Append(SCANNERS = scanner)
def exists(env):
return env.Detect(['swig'])
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""engine.SCons.Tool.g77
Tool-specific initialization for g77.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/g77.py 4720 2010/03/24 03:14:11 jars"
import SCons.Util
from SCons.Tool.FortranCommon import add_all_to_env, add_f77_to_env
compilers = ['g77', 'f77']
def generate(env):
"""Add Builders and construction variables for g77 to an Environment."""
add_all_to_env(env)
add_f77_to_env(env)
fcomp = env.Detect(compilers) or 'g77'
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS')
env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS')
else:
env['SHFORTRANFLAGS'] = SCons.Util.CLVar('$FORTRANFLAGS -fPIC')
env['SHF77FLAGS'] = SCons.Util.CLVar('$F77FLAGS -fPIC')
env['FORTRAN'] = fcomp
env['SHFORTRAN'] = '$FORTRAN'
env['F77'] = fcomp
env['SHF77'] = '$F77'
env['INCFORTRANPREFIX'] = "-I"
env['INCFORTRANSUFFIX'] = ""
env['INCF77PREFIX'] = "-I"
env['INCF77SUFFIX'] = ""
def exists(env):
return env.Detect(compilers)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.sunc++
Tool-specific initialization for C++ on SunOS / Solaris.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/sunc++.py 4720 2010/03/24 03:14:11 jars"
import SCons
import os
import re
import subprocess
cplusplus = __import__('c++', globals(), locals(), [])
package_info = {}
def get_package_info(package_name, pkginfo, pkgchk):
try:
return package_info[package_name]
except KeyError:
version = None
pathname = None
try:
sadm_contents = open('/var/sadm/install/contents', 'r').read()
except EnvironmentError:
pass
else:
sadm_re = re.compile('^(\S*/bin/CC)(=\S*)? %s$' % package_name, re.M)
sadm_match = sadm_re.search(sadm_contents)
if sadm_match:
pathname = os.path.dirname(sadm_match.group(1))
try:
p = subprocess.Popen([pkginfo, '-l', package_name],
stdout=subprocess.PIPE,
stderr=open('/dev/null', 'w'))
except EnvironmentError:
pass
else:
pkginfo_contents = p.communicate()[0]
version_re = re.compile('^ *VERSION:\s*(.*)$', re.M)
version_match = version_re.search(pkginfo_contents)
if version_match:
version = version_match.group(1)
if pathname is None:
try:
p = subprocess.Popen([pkgchk, '-l', package_name],
stdout=subprocess.PIPE,
stderr=open('/dev/null', 'w'))
except EnvironmentError:
pass
else:
pkgchk_contents = p.communicate()[0]
pathname_re = re.compile(r'^Pathname:\s*(.*/bin/CC)$', re.M)
pathname_match = pathname_re.search(pkgchk_contents)
if pathname_match:
pathname = os.path.dirname(pathname_match.group(1))
package_info[package_name] = (pathname, version)
return package_info[package_name]
# use the package installer tool lslpp to figure out where cppc and what
# version of it is installed
def get_cppc(env):
cxx = env.subst('$CXX')
if cxx:
cppcPath = os.path.dirname(cxx)
else:
cppcPath = None
cppcVersion = None
pkginfo = env.subst('$PKGINFO')
pkgchk = env.subst('$PKGCHK')
for package in ['SPROcpl']:
path, version = get_package_info(package, pkginfo, pkgchk)
if path and version:
cppcPath, cppcVersion = path, version
break
return (cppcPath, 'CC', 'CC', cppcVersion)
def generate(env):
"""Add Builders and construction variables for SunPRO C++."""
path, cxx, shcxx, version = get_cppc(env)
if path:
cxx = os.path.join(path, cxx)
shcxx = os.path.join(path, shcxx)
cplusplus.generate(env)
env['CXX'] = cxx
env['SHCXX'] = shcxx
env['CXXVERSION'] = version
env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -KPIC')
env['SHOBJPREFIX'] = 'so_'
env['SHOBJSUFFIX'] = '.o'
def exists(env):
path, cxx, shcxx, version = get_cppc(env)
if path and cxx:
cppc = os.path.join(path, cxx)
if os.path.exists(cppc):
return cppc
return None
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.link
Tool-specific initialization for the generic Posix linker.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/link.py 4720 2010/03/24 03:14:11 jars"
import SCons.Defaults
import SCons.Tool
import SCons.Util
import SCons.Warnings
from SCons.Tool.FortranCommon import isfortran
cplusplus = __import__('c++', globals(), locals(), [])
issued_mixed_link_warning = False
def smart_link(source, target, env, for_signature):
has_cplusplus = cplusplus.iscplusplus(source)
has_fortran = isfortran(env, source)
if has_cplusplus and has_fortran:
global issued_mixed_link_warning
if not issued_mixed_link_warning:
msg = "Using $CXX to link Fortran and C++ code together.\n\t" + \
"This may generate a buggy executable if the '%s'\n\t" + \
"compiler does not know how to deal with Fortran runtimes."
SCons.Warnings.warn(SCons.Warnings.FortranCxxMixWarning,
msg % env.subst('$CXX'))
issued_mixed_link_warning = True
return '$CXX'
elif has_fortran:
return '$FORTRAN'
elif has_cplusplus:
return '$CXX'
return '$CC'
def shlib_emitter(target, source, env):
for tgt in target:
tgt.attributes.shared = 1
return (target, source)
def generate(env):
"""Add Builders and construction variables for gnulink to an Environment."""
SCons.Tool.createSharedLibBuilder(env)
SCons.Tool.createProgBuilder(env)
env['SHLINK'] = '$LINK'
env['SHLINKFLAGS'] = SCons.Util.CLVar('$LINKFLAGS -shared')
env['SHLINKCOM'] = '$SHLINK -o $TARGET $SHLINKFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
# don't set up the emitter, cause AppendUnique will generate a list
# starting with None :-(
env.Append(SHLIBEMITTER = [shlib_emitter])
env['SMARTLINK'] = smart_link
env['LINK'] = "$SMARTLINK"
env['LINKFLAGS'] = SCons.Util.CLVar('')
env['LINKCOM'] = '$LINK -o $TARGET $LINKFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
env['LIBDIRPREFIX']='-L'
env['LIBDIRSUFFIX']=''
env['_LIBFLAGS']='${_stripixes(LIBLINKPREFIX, LIBS, LIBLINKSUFFIX, LIBPREFIXES, LIBSUFFIXES, __env__)}'
env['LIBLINKPREFIX']='-l'
env['LIBLINKSUFFIX']=''
if env['PLATFORM'] == 'hpux':
env['SHLIBSUFFIX'] = '.sl'
elif env['PLATFORM'] == 'aix':
env['SHLIBSUFFIX'] = '.a'
# For most platforms, a loadable module is the same as a shared
# library. Platforms which are different can override these, but
# setting them the same means that LoadableModule works everywhere.
SCons.Tool.createLoadableModuleBuilder(env)
env['LDMODULE'] = '$SHLINK'
# don't set up the emitter, cause AppendUnique will generate a list
# starting with None :-(
env.Append(LDMODULEEMITTER='$SHLIBEMITTER')
env['LDMODULEPREFIX'] = '$SHLIBPREFIX'
env['LDMODULESUFFIX'] = '$SHLIBSUFFIX'
env['LDMODULEFLAGS'] = '$SHLINKFLAGS'
env['LDMODULECOM'] = '$LDMODULE -o $TARGET $LDMODULEFLAGS $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'
def exists(env):
# This module isn't really a Tool on its own, it's common logic for
# other linkers.
return None
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.gs
Tool-specific initialization for Ghostscript.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/gs.py 4720 2010/03/24 03:14:11 jars"
import SCons.Action
import SCons.Platform
import SCons.Util
# Ghostscript goes by different names on different platforms...
platform = SCons.Platform.platform_default()
if platform == 'os2':
gs = 'gsos2'
elif platform == 'win32':
gs = 'gswin32c'
else:
gs = 'gs'
GhostscriptAction = None
def generate(env):
"""Add Builders and construction variables for Ghostscript to an
Environment."""
global GhostscriptAction
if GhostscriptAction is None:
GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ps', GhostscriptAction)
env['GS'] = gs
env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite')
env['GSCOM'] = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES'
def exists(env):
if env.has_key('PS2PDF'):
return env.Detect(env['PS2PDF'])
else:
return env.Detect(gs) or SCons.Util.WhereIs(gs)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.ar
Tool-specific initialization for ar (library archive).
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/ar.py 4720 2010/03/24 03:14:11 jars"
import SCons.Defaults
import SCons.Tool
import SCons.Util
def generate(env):
"""Add Builders and construction variables for ar to an Environment."""
SCons.Tool.createStaticLibBuilder(env)
env['AR'] = 'ar'
env['ARFLAGS'] = SCons.Util.CLVar('rc')
env['ARCOM'] = '$AR $ARFLAGS $TARGET $SOURCES'
env['LIBPREFIX'] = 'lib'
env['LIBSUFFIX'] = '.a'
if env.Detect('ranlib'):
env['RANLIB'] = 'ranlib'
env['RANLIBFLAGS'] = SCons.Util.CLVar('')
env['RANLIBCOM'] = '$RANLIB $RANLIBFLAGS $TARGET'
def exists(env):
return env.Detect('ar')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.dmd
Tool-specific initialization for the Digital Mars D compiler.
(http://digitalmars.com/d)
Coded by Andy Friesen (andy@ikagames.com)
15 November 2003
There are a number of problems with this script at this point in time.
The one that irritates me the most is the Windows linker setup. The D
linker doesn't have a way to add lib paths on the commandline, as far
as I can see. You have to specify paths relative to the SConscript or
use absolute paths. To hack around it, add '#/blah'. This will link
blah.lib from the directory where SConstruct resides.
Compiler variables:
DC - The name of the D compiler to use. Defaults to dmd or gdmd,
whichever is found.
DPATH - List of paths to search for import modules.
DVERSIONS - List of version tags to enable when compiling.
DDEBUG - List of debug tags to enable when compiling.
Linker related variables:
LIBS - List of library files to link in.
DLINK - Name of the linker to use. Defaults to dmd or gdmd.
DLINKFLAGS - List of linker flags.
Lib tool variables:
DLIB - Name of the lib tool to use. Defaults to lib.
DLIBFLAGS - List of flags to pass to the lib tool.
LIBS - Same as for the linker. (libraries to pull into the .lib)
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/dmd.py 4720 2010/03/24 03:14:11 jars"
import os
import string
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Scanner.D
import SCons.Tool
# Adapted from c++.py
def isD(source):
if not source:
return 0
for s in source:
if s.sources:
ext = os.path.splitext(str(s.sources[0]))[1]
if ext == '.d':
return 1
return 0
smart_link = {}
smart_lib = {}
def generate(env):
global smart_link
global smart_lib
static_obj, shared_obj = SCons.Tool.createObjBuilders(env)
DAction = SCons.Action.Action('$DCOM', '$DCOMSTR')
static_obj.add_action('.d', DAction)
shared_obj.add_action('.d', DAction)
static_obj.add_emitter('.d', SCons.Defaults.StaticObjectEmitter)
shared_obj.add_emitter('.d', SCons.Defaults.SharedObjectEmitter)
dc = env.Detect(['dmd', 'gdmd'])
env['DC'] = dc
env['DCOM'] = '$DC $_DINCFLAGS $_DVERFLAGS $_DDEBUGFLAGS $_DFLAGS -c -of$TARGET $SOURCES'
env['_DINCFLAGS'] = '$( ${_concat(DINCPREFIX, DPATH, DINCSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['_DVERFLAGS'] = '$( ${_concat(DVERPREFIX, DVERSIONS, DVERSUFFIX, __env__)} $)'
env['_DDEBUGFLAGS'] = '$( ${_concat(DDEBUGPREFIX, DDEBUG, DDEBUGSUFFIX, __env__)} $)'
env['_DFLAGS'] = '$( ${_concat(DFLAGPREFIX, DFLAGS, DFLAGSUFFIX, __env__)} $)'
env['DPATH'] = ['#/']
env['DFLAGS'] = []
env['DVERSIONS'] = []
env['DDEBUG'] = []
if dc:
# Add the path to the standard library.
# This is merely for the convenience of the dependency scanner.
dmd_path = env.WhereIs(dc)
if dmd_path:
x = string.rindex(dmd_path, dc)
phobosDir = dmd_path[:x] + '/../src/phobos'
if os.path.isdir(phobosDir):
env.Append(DPATH = [phobosDir])
env['DINCPREFIX'] = '-I'
env['DINCSUFFIX'] = ''
env['DVERPREFIX'] = '-version='
env['DVERSUFFIX'] = ''
env['DDEBUGPREFIX'] = '-debug='
env['DDEBUGSUFFIX'] = ''
env['DFLAGPREFIX'] = '-'
env['DFLAGSUFFIX'] = ''
env['DFILESUFFIX'] = '.d'
# Need to use the Digital Mars linker/lib on windows.
# *nix can just use GNU link.
if env['PLATFORM'] == 'win32':
env['DLINK'] = '$DC'
env['DLINKCOM'] = '$DLINK -of$TARGET $SOURCES $DFLAGS $DLINKFLAGS $_DLINKLIBFLAGS'
env['DLIB'] = 'lib'
env['DLIBCOM'] = '$DLIB $_DLIBFLAGS -c $TARGET $SOURCES $_DLINKLIBFLAGS'
env['_DLINKLIBFLAGS'] = '$( ${_concat(DLIBLINKPREFIX, LIBS, DLIBLINKSUFFIX, __env__, RDirs, TARGET, SOURCE)} $)'
env['_DLIBFLAGS'] = '$( ${_concat(DLIBFLAGPREFIX, DLIBFLAGS, DLIBFLAGSUFFIX, __env__)} $)'
env['DLINKFLAGS'] = []
env['DLIBLINKPREFIX'] = ''
env['DLIBLINKSUFFIX'] = '.lib'
env['DLIBFLAGPREFIX'] = '-'
env['DLIBFLAGSUFFIX'] = ''
env['DLINKFLAGPREFIX'] = '-'
env['DLINKFLAGSUFFIX'] = ''
SCons.Tool.createStaticLibBuilder(env)
# Basically, we hijack the link and ar builders with our own.
# these builders check for the presence of D source, and swap out
# the system's defaults for the Digital Mars tools. If there's no D
# source, then we silently return the previous settings.
linkcom = env.get('LINKCOM')
try:
env['SMART_LINKCOM'] = smart_link[linkcom]
except KeyError:
def _smartLink(source, target, env, for_signature,
defaultLinker=linkcom):
if isD(source):
# XXX I'm not sure how to add a $DLINKCOMSTR variable
# so that it works with this _smartLink() logic,
# and I don't have a D compiler/linker to try it out,
# so we'll leave it alone for now.
return '$DLINKCOM'
else:
return defaultLinker
env['SMART_LINKCOM'] = smart_link[linkcom] = _smartLink
arcom = env.get('ARCOM')
try:
env['SMART_ARCOM'] = smart_lib[arcom]
except KeyError:
def _smartLib(source, target, env, for_signature,
defaultLib=arcom):
if isD(source):
# XXX I'm not sure how to add a $DLIBCOMSTR variable
# so that it works with this _smartLib() logic, and
# I don't have a D compiler/archiver to try it out,
# so we'll leave it alone for now.
return '$DLIBCOM'
else:
return defaultLib
env['SMART_ARCOM'] = smart_lib[arcom] = _smartLib
# It is worth noting that the final space in these strings is
# absolutely pivotal. SCons sees these as actions and not generators
# if it is not there. (very bad)
env['ARCOM'] = '$SMART_ARCOM '
env['LINKCOM'] = '$SMART_LINKCOM '
else: # assuming linux
linkcom = env.get('LINKCOM')
try:
env['SMART_LINKCOM'] = smart_link[linkcom]
except KeyError:
def _smartLink(source, target, env, for_signature,
defaultLinker=linkcom, dc=dc):
if isD(source):
try:
libs = env['LIBS']
except KeyError:
libs = []
if 'phobos' not in libs and 'gphobos' not in libs:
if dc is 'dmd':
env.Append(LIBS = ['phobos'])
elif dc is 'gdmd':
env.Append(LIBS = ['gphobos'])
if 'pthread' not in libs:
env.Append(LIBS = ['pthread'])
if 'm' not in libs:
env.Append(LIBS = ['m'])
return defaultLinker
env['SMART_LINKCOM'] = smart_link[linkcom] = _smartLink
env['LINKCOM'] = '$SMART_LINKCOM '
def exists(env):
return env.Detect(['dmd', 'gdmd'])
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.zip
The zip SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/src_zip.py 4720 2010/03/24 03:14:11 jars"
from SCons.Tool.packaging import putintopackageroot
def package(env, target, source, PACKAGEROOT, **kw):
bld = env['BUILDERS']['Zip']
bld.set_suffix('.zip')
target, source = putintopackageroot(target, source, env, PACKAGEROOT, honor_install_location=0)
return bld(env, target, source)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.rpm
The rpm packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/rpm.py 4720 2010/03/24 03:14:11 jars"
import os
import string
import SCons.Builder
from SCons.Environment import OverrideEnvironment
from SCons.Tool.packaging import stripinstallbuilder, src_targz
from SCons.Errors import UserError
def package(env, target, source, PACKAGEROOT, NAME, VERSION,
PACKAGEVERSION, DESCRIPTION, SUMMARY, X_RPM_GROUP, LICENSE,
**kw):
# initialize the rpm tool
SCons.Tool.Tool('rpm').generate(env)
bld = env['BUILDERS']['Rpm']
# Generate a UserError whenever the target name has been set explicitly,
# since rpm does not allow for controlling it. This is detected by
# checking if the target has been set to the default by the Package()
# Environment function.
if str(target[0])!="%s-%s"%(NAME, VERSION):
raise UserError( "Setting target is not supported for rpm." )
else:
# This should be overridable from the construction environment,
# which it is by using ARCHITECTURE=.
# Guessing based on what os.uname() returns at least allows it
# to work for both i386 and x86_64 Linux systems.
archmap = {
'i686' : 'i386',
'i586' : 'i386',
'i486' : 'i386',
}
buildarchitecture = os.uname()[4]
buildarchitecture = archmap.get(buildarchitecture, buildarchitecture)
if kw.has_key('ARCHITECTURE'):
buildarchitecture = kw['ARCHITECTURE']
fmt = '%s-%s-%s.%s.rpm'
srcrpm = fmt % (NAME, VERSION, PACKAGEVERSION, 'src')
binrpm = fmt % (NAME, VERSION, PACKAGEVERSION, buildarchitecture)
target = [ srcrpm, binrpm ]
# get the correct arguments into the kw hash
loc=locals()
del loc['kw']
kw.update(loc)
del kw['source'], kw['target'], kw['env']
# if no "SOURCE_URL" tag is given add a default one.
if not kw.has_key('SOURCE_URL'):
#kw['SOURCE_URL']=(str(target[0])+".tar.gz").replace('.rpm', '')
kw['SOURCE_URL']=string.replace(str(target[0])+".tar.gz", '.rpm', '')
# mangle the source and target list for the rpmbuild
env = OverrideEnvironment(env, kw)
target, source = stripinstallbuilder(target, source, env)
target, source = addspecfile(target, source, env)
target, source = collectintargz(target, source, env)
# now call the rpm builder to actually build the packet.
return apply(bld, [env, target, source], kw)
def collectintargz(target, source, env):
""" Puts all source files into a tar.gz file. """
# the rpm tool depends on a source package, until this is chagned
# this hack needs to be here that tries to pack all sources in.
sources = env.FindSourceFiles()
# filter out the target we are building the source list for.
#sources = [s for s in sources if not (s in target)]
sources = filter(lambda s, t=target: not (s in t), sources)
# find the .spec file for rpm and add it since it is not necessarily found
# by the FindSourceFiles function.
#sources.extend( [s for s in source if str(s).rfind('.spec')!=-1] )
spec_file = lambda s: string.rfind(str(s), '.spec') != -1
sources.extend( filter(spec_file, source) )
# as the source contains the url of the source package this rpm package
# is built from, we extract the target name
#tarball = (str(target[0])+".tar.gz").replace('.rpm', '')
tarball = string.replace(str(target[0])+".tar.gz", '.rpm', '')
try:
#tarball = env['SOURCE_URL'].split('/')[-1]
tarball = string.split(env['SOURCE_URL'], '/')[-1]
except KeyError, e:
raise SCons.Errors.UserError( "Missing PackageTag '%s' for RPM packager" % e.args[0] )
tarball = src_targz.package(env, source=sources, target=tarball,
PACKAGEROOT=env['PACKAGEROOT'], )
return (target, tarball)
def addspecfile(target, source, env):
specfile = "%s-%s" % (env['NAME'], env['VERSION'])
bld = SCons.Builder.Builder(action = build_specfile,
suffix = '.spec',
target_factory = SCons.Node.FS.File)
source.extend(bld(env, specfile, source))
return (target,source)
def build_specfile(target, source, env):
""" Builds a RPM specfile from a dictionary with string metadata and
by analyzing a tree of nodes.
"""
file = open(target[0].abspath, 'w')
str = ""
try:
file.write( build_specfile_header(env) )
file.write( build_specfile_sections(env) )
file.write( build_specfile_filesection(env, source) )
file.close()
# call a user specified function
if env.has_key('CHANGE_SPECFILE'):
env['CHANGE_SPECFILE'](target, source)
except KeyError, e:
raise SCons.Errors.UserError( '"%s" package field for RPM is missing.' % e.args[0] )
#
# mandatory and optional package tag section
#
def build_specfile_sections(spec):
""" Builds the sections of a rpm specfile.
"""
str = ""
mandatory_sections = {
'DESCRIPTION' : '\n%%description\n%s\n\n', }
str = str + SimpleTagCompiler(mandatory_sections).compile( spec )
optional_sections = {
'DESCRIPTION_' : '%%description -l %s\n%s\n\n',
'CHANGELOG' : '%%changelog\n%s\n\n',
'X_RPM_PREINSTALL' : '%%pre\n%s\n\n',
'X_RPM_POSTINSTALL' : '%%post\n%s\n\n',
'X_RPM_PREUNINSTALL' : '%%preun\n%s\n\n',
'X_RPM_POSTUNINSTALL' : '%%postun\n%s\n\n',
'X_RPM_VERIFY' : '%%verify\n%s\n\n',
# These are for internal use but could possibly be overriden
'X_RPM_PREP' : '%%prep\n%s\n\n',
'X_RPM_BUILD' : '%%build\n%s\n\n',
'X_RPM_INSTALL' : '%%install\n%s\n\n',
'X_RPM_CLEAN' : '%%clean\n%s\n\n',
}
# Default prep, build, install and clean rules
# TODO: optimize those build steps, to not compile the project a second time
if not spec.has_key('X_RPM_PREP'):
spec['X_RPM_PREP'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"' + '\n%setup -q'
if not spec.has_key('X_RPM_BUILD'):
spec['X_RPM_BUILD'] = 'mkdir "$RPM_BUILD_ROOT"'
if not spec.has_key('X_RPM_INSTALL'):
spec['X_RPM_INSTALL'] = 'scons --install-sandbox="$RPM_BUILD_ROOT" "$RPM_BUILD_ROOT"'
if not spec.has_key('X_RPM_CLEAN'):
spec['X_RPM_CLEAN'] = '[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT"'
str = str + SimpleTagCompiler(optional_sections, mandatory=0).compile( spec )
return str
def build_specfile_header(spec):
""" Builds all section but the %file of a rpm specfile
"""
str = ""
# first the mandatory sections
mandatory_header_fields = {
'NAME' : '%%define name %s\nName: %%{name}\n',
'VERSION' : '%%define version %s\nVersion: %%{version}\n',
'PACKAGEVERSION' : '%%define release %s\nRelease: %%{release}\n',
'X_RPM_GROUP' : 'Group: %s\n',
'SUMMARY' : 'Summary: %s\n',
'LICENSE' : 'License: %s\n', }
str = str + SimpleTagCompiler(mandatory_header_fields).compile( spec )
# now the optional tags
optional_header_fields = {
'VENDOR' : 'Vendor: %s\n',
'X_RPM_URL' : 'Url: %s\n',
'SOURCE_URL' : 'Source: %s\n',
'SUMMARY_' : 'Summary(%s): %s\n',
'X_RPM_DISTRIBUTION' : 'Distribution: %s\n',
'X_RPM_ICON' : 'Icon: %s\n',
'X_RPM_PACKAGER' : 'Packager: %s\n',
'X_RPM_GROUP_' : 'Group(%s): %s\n',
'X_RPM_REQUIRES' : 'Requires: %s\n',
'X_RPM_PROVIDES' : 'Provides: %s\n',
'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
'X_RPM_BUILDREQUIRES' : 'BuildRequires: %s\n',
'X_RPM_SERIAL' : 'Serial: %s\n',
'X_RPM_EPOCH' : 'Epoch: %s\n',
'X_RPM_AUTOREQPROV' : 'AutoReqProv: %s\n',
'X_RPM_EXCLUDEARCH' : 'ExcludeArch: %s\n',
'X_RPM_EXCLUSIVEARCH' : 'ExclusiveArch: %s\n',
'X_RPM_PREFIX' : 'Prefix: %s\n',
'X_RPM_CONFLICTS' : 'Conflicts: %s\n',
# internal use
'X_RPM_BUILDROOT' : 'BuildRoot: %s\n', }
# fill in default values:
# Adding a BuildRequires renders the .rpm unbuildable under System, which
# are not managed by rpm, since the database to resolve this dependency is
# missing (take Gentoo as an example)
# if not s.has_key('x_rpm_BuildRequires'):
# s['x_rpm_BuildRequires'] = 'scons'
if not spec.has_key('X_RPM_BUILDROOT'):
spec['X_RPM_BUILDROOT'] = '%{_tmppath}/%{name}-%{version}-%{release}'
str = str + SimpleTagCompiler(optional_header_fields, mandatory=0).compile( spec )
return str
#
# mandatory and optional file tags
#
def build_specfile_filesection(spec, files):
""" builds the %file section of the specfile
"""
str = '%files\n'
if not spec.has_key('X_RPM_DEFATTR'):
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' : '%%config %s',
'PACKAGING_CONFIG_NOREPLACE' : '%%config(noreplace) %s',
'PACKAGING_DOC' : '%%doc %s',
'PACKAGING_UNIX_ATTR' : '%%attr %s',
'PACKAGING_LANG_' : '%%lang(%s) %s',
'PACKAGING_X_RPM_VERIFY' : '%%verify %s',
'PACKAGING_X_RPM_DIR' : '%%dir %s',
'PACKAGING_X_RPM_DOCDIR' : '%%docdir %s',
'PACKAGING_X_RPM_GHOST' : '%%ghost %s', }
for file in files:
# build the tagset
tags = {}
for k in supported_tags.keys():
try:
tags[k]=getattr(file, k)
except AttributeError:
pass
# compile the tagset
str = str + SimpleTagCompiler(supported_tags, mandatory=0).compile( tags )
str = str + ' '
str = str + file.PACKAGING_INSTALL_LOCATION
str = str + '\n\n'
return str
class SimpleTagCompiler:
""" This class is a simple string substition utility:
the replacement specfication is stored in the tagset dictionary, something
like:
{ "abc" : "cdef %s ",
"abc_" : "cdef %s %s" }
the compile function gets a value dictionary, which may look like:
{ "abc" : "ghij",
"abc_gh" : "ij" }
The resulting string will be:
"cdef ghij cdef gh ij"
"""
def __init__(self, tagset, mandatory=1):
self.tagset = tagset
self.mandatory = mandatory
def compile(self, values):
""" compiles the tagset and returns a str containing the result
"""
def is_international(tag):
#return tag.endswith('_')
return tag[-1:] == '_'
def get_country_code(tag):
return tag[-2:]
def strip_country_code(tag):
return tag[:-2]
replacements = self.tagset.items()
str = ""
#domestic = [ (k,v) for k,v in replacements if not is_international(k) ]
domestic = filter(lambda t, i=is_international: not i(t[0]), replacements)
for key, replacement in domestic:
try:
str = str + replacement % values[key]
except KeyError, e:
if self.mandatory:
raise e
#international = [ (k,v) for k,v in replacements if is_international(k) ]
international = filter(lambda t, i=is_international: i(t[0]), replacements)
for key, replacement in international:
try:
#int_values_for_key = [ (get_country_code(k),v) for k,v in values.items() if strip_country_code(k) == key ]
x = filter(lambda t,key=key,s=strip_country_code: s(t[0]) == key, values.items())
int_values_for_key = map(lambda t,g=get_country_code: (g(t[0]),t[1]), x)
for v in int_values_for_key:
str = str + replacement % v
except KeyError, e:
if self.mandatory:
raise e
return str
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.ipk
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/ipk.py 4720 2010/03/24 03:14:11 jars"
import SCons.Builder
import SCons.Node.FS
import os
from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot
def package(env, target, source, PACKAGEROOT, NAME, VERSION, DESCRIPTION,
SUMMARY, X_IPK_PRIORITY, X_IPK_SECTION, SOURCE_URL,
X_IPK_MAINTAINER, X_IPK_DEPENDS, **kw):
""" this function prepares the packageroot directory for packaging with the
ipkg builder.
"""
SCons.Tool.Tool('ipkg').generate(env)
# setup the Ipkg builder
bld = env['BUILDERS']['Ipkg']
target, source = stripinstallbuilder(target, source, env)
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
# This should be overridable from the construction environment,
# which it is by using ARCHITECTURE=.
# Guessing based on what os.uname() returns at least allows it
# to work for both i386 and x86_64 Linux systems.
archmap = {
'i686' : 'i386',
'i586' : 'i386',
'i486' : 'i386',
}
buildarchitecture = os.uname()[4]
buildarchitecture = archmap.get(buildarchitecture, buildarchitecture)
if kw.has_key('ARCHITECTURE'):
buildarchitecture = kw['ARCHITECTURE']
# setup the kw to contain the mandatory arguments to this fucntion.
# do this before calling any builder or setup function
loc=locals()
del loc['kw']
kw.update(loc)
del kw['source'], kw['target'], kw['env']
# generate the specfile
specfile = gen_ipk_dir(PACKAGEROOT, source, env, kw)
# override the default target.
if str(target[0])=="%s-%s"%(NAME, VERSION):
target=[ "%s_%s_%s.ipk"%(NAME, VERSION, buildarchitecture) ]
# now apply the Ipkg builder
return apply(bld, [env, target, specfile], kw)
def gen_ipk_dir(proot, source, env, kw):
# make sure the packageroot is a Dir object.
if SCons.Util.is_String(proot): proot=env.Dir(proot)
# create the specfile builder
s_bld=SCons.Builder.Builder(
action = build_specfiles,
)
# create the specfile targets
spec_target=[]
control=proot.Dir('CONTROL')
spec_target.append(control.File('control'))
spec_target.append(control.File('conffiles'))
spec_target.append(control.File('postrm'))
spec_target.append(control.File('prerm'))
spec_target.append(control.File('postinst'))
spec_target.append(control.File('preinst'))
# apply the builder to the specfile targets
apply(s_bld, [env, spec_target, source], kw)
# the packageroot directory does now contain the specfiles.
return proot
def build_specfiles(source, target, env):
""" filter the targets for the needed files and use the variables in env
to create the specfile.
"""
#
# At first we care for the CONTROL/control file, which is the main file for ipk.
#
# For this we need to open multiple files in random order, so we store into
# a dict so they can be easily accessed.
#
#
opened_files={}
def open_file(needle, haystack):
try:
return opened_files[needle]
except KeyError:
file=filter(lambda x: x.get_path().rfind(needle)!=-1, haystack)[0]
opened_files[needle]=open(file.abspath, 'w')
return opened_files[needle]
control_file=open_file('control', target)
if not env.has_key('X_IPK_DESCRIPTION'):
env['X_IPK_DESCRIPTION']="%s\n %s"%(env['SUMMARY'],
env['DESCRIPTION'].replace('\n', '\n '))
content = """
Package: $NAME
Version: $VERSION
Priority: $X_IPK_PRIORITY
Section: $X_IPK_SECTION
Source: $SOURCE_URL
Architecture: $ARCHITECTURE
Maintainer: $X_IPK_MAINTAINER
Depends: $X_IPK_DEPENDS
Description: $X_IPK_DESCRIPTION
"""
control_file.write(env.subst(content))
#
# now handle the various other files, which purpose it is to set post-,
# pre-scripts and mark files as config files.
#
# We do so by filtering the source files for files which are marked with
# the "config" tag and afterwards we do the same for x_ipk_postrm,
# x_ipk_prerm, x_ipk_postinst and x_ipk_preinst tags.
#
# The first one will write the name of the file into the file
# CONTROL/configfiles, the latter add the content of the x_ipk_* variable
# into the same named file.
#
for f in [x for x in source if 'PACKAGING_CONFIG' in dir(x)]:
config=open_file('conffiles')
config.write(f.PACKAGING_INSTALL_LOCATION)
config.write('\n')
for str in 'POSTRM PRERM POSTINST PREINST'.split():
name="PACKAGING_X_IPK_%s"%str
for f in [x for x in source if name in dir(x)]:
file=open_file(name)
file.write(env[str])
#
# close all opened files
for f in opened_files.values():
f.close()
# call a user specified function
if env.has_key('CHANGE_SPECFILE'):
content += env['CHANGE_SPECFILE'](target)
return 0
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.tarbz2
The tarbz2 SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/tarbz2.py 4720 2010/03/24 03:14:11 jars"
from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot
def package(env, target, source, PACKAGEROOT, **kw):
bld = env['BUILDERS']['Tar']
bld.set_suffix('.tar.gz')
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
target, source = stripinstallbuilder(target, source, env)
return bld(env, target, source, TARFLAGS='-jc')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.zip
The zip SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/zip.py 4720 2010/03/24 03:14:11 jars"
from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot
def package(env, target, source, PACKAGEROOT, **kw):
bld = env['BUILDERS']['Zip']
bld.set_suffix('.zip')
target, source = stripinstallbuilder(target, source, env)
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
return bld(env, target, source)
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.targz
The targz SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/targz.py 4720 2010/03/24 03:14:11 jars"
from SCons.Tool.packaging import stripinstallbuilder, putintopackageroot
def package(env, target, source, PACKAGEROOT, **kw):
bld = env['BUILDERS']['Tar']
bld.set_suffix('.tar.gz')
target, source = stripinstallbuilder(target, source, env)
target, source = putintopackageroot(target, source, env, PACKAGEROOT)
return bld(env, target, source, TARFLAGS='-zc')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
"""SCons.Tool.Packaging.targz
The targz SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "src/engine/SCons/Tool/packaging/src_targz.py 4720 2010/03/24 03:14:11 jars"
from SCons.Tool.packaging import putintopackageroot
def package(env, target, source, PACKAGEROOT, **kw):
bld = env['BUILDERS']['Tar']
bld.set_suffix('.tar.gz')
target, source = putintopackageroot(target, source, env, PACKAGEROOT, honor_install_location=0)
return bld(env, target, source, TARFLAGS='-zc')
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.