|
| 1 | +# Shorty module compiler |
| 2 | +# Copyright 2009 Joshua Roesslein |
| 3 | +# See LICENSE |
| 4 | + |
| 5 | +importsys |
| 6 | +importos |
| 7 | + |
| 8 | +_services=dict() |
| 9 | + |
| 10 | +# remove any template comments |
| 11 | +defremove_comments(text): |
| 12 | + |
| 13 | +output=str() |
| 14 | +forlineintext.splitlines(): |
| 15 | +ifline.startswith('##'):continue |
| 16 | +output+=line+'\n' |
| 17 | +returnoutput |
| 18 | + |
| 19 | +# process module source |
| 20 | +defprocess_module(name,source): |
| 21 | + |
| 22 | +output=str() |
| 23 | + |
| 24 | +# iterate through source and process any @ tags |
| 25 | +forlineinsource.splitlines(): |
| 26 | +ifline.startswith('##'): |
| 27 | +# is a url tag? |
| 28 | +pos=line.find('@url') |
| 29 | +ifpos>=0: |
| 30 | +urls=line[pos+4:].split() |
| 31 | +_services.update(dict((url.strip(),name)forurlinurls)) |
| 32 | +output+='# %s\n'%name |
| 33 | +else: |
| 34 | +output+=line+'\n' |
| 35 | + |
| 36 | +# write out service global instance |
| 37 | +output+='%s = %s()\n'% (name,name.capitalize()) |
| 38 | + |
| 39 | +returnoutput |
| 40 | + |
| 41 | +defcompile_shorty(services): |
| 42 | + |
| 43 | +# open shorty.py file |
| 44 | +sfp=open('shorty.py','w') |
| 45 | + |
| 46 | +# write out the header (license/ascii art/etc) |
| 47 | +header=open('header','r') |
| 48 | +sfp.write(header.read()) |
| 49 | +header.close() |
| 50 | + |
| 51 | +# write out imports |
| 52 | +imports=open('imports.py','r') |
| 53 | +sfp.write(remove_comments(imports.read())) |
| 54 | +imports.close() |
| 55 | + |
| 56 | +# write out common code |
| 57 | +common=open('common.py','r') |
| 58 | +sfp.write(remove_comments(common.read())) |
| 59 | +common.close() |
| 60 | + |
| 61 | +# write service module code |
| 62 | +forserviceinservices: |
| 63 | +try: |
| 64 | +module=open('services/%s.py'%service,'r') |
| 65 | +exceptIOError: |
| 66 | +print'%s not found! Skipping'%service |
| 67 | +continue |
| 68 | + |
| 69 | +sfp.write(process_module(service,module.read())) |
| 70 | +module.close() |
| 71 | + |
| 72 | +# write out services dict |
| 73 | +sfp.write('\nservices = {\n') |
| 74 | +fork,vin_services.items(): |
| 75 | +sfp.write(" '%s': %s,\n"% (k,v)) |
| 76 | +sfp.write('}\n\n') |
| 77 | + |
| 78 | +sfp.close() |
| 79 | + |
| 80 | +if__name__=='__main__': |
| 81 | + |
| 82 | +# make sure enough args are provided |
| 83 | +iflen(sys.argv)<2: |
| 84 | +print'Usage: compile.py <services>' |
| 85 | +print' services -- names of the services to include in compiled module' |
| 86 | +print'Example: compile.py sandbox tinyurl bitly' |
| 87 | + |
| 88 | +# get list of services to compile |
| 89 | +ifsys.argv[1]=='--all': |
| 90 | +services=list(m.split('.')[0]forminos.listdir('services')) |
| 91 | +else: |
| 92 | +services=sys.argv[1:] |
| 93 | + |
| 94 | +# compile shorty |
| 95 | +compile_shorty(services) |
| 96 | + |