1 #!/usr/bin/python2.6 2 3 import config, httplib, json, urllib, subprocess, sys 4 5 # Read all the Javascript files. 6 js_code = [('js_code', open(f).read()) for f in config.js_in_files] 7 8 # Read all the CSS files and concatenate them. 9 css_code = ''.join(open(f).read() for f in config.css_in_files) 10 11 # Define the parameters for the POST request and encode them in 12 # a URL-safe format. 13 params = urllib.urlencode(js_code + [ 14 ('language', 'ECMASCRIPT5'), 15 ('compilation_level', 'SIMPLE_OPTIMIZATIONS'), 16 ('output_format', 'json'), 17 ('output_info', 'errors'), 18 ('output_info', 'compiled_code'), 19 ]) 20 21 # Always use the following value for the Content-type header. 22 headers = { "Content-type": "application/x-www-form-urlencoded" } 23 conn = httplib.HTTPConnection('closure-compiler.appspot.com') 24 conn.request('POST', '/compile', params, headers) 25 response = conn.getresponse() 26 data = response.read() 27 conn.close 28 29 if response.status != 200: 30 print sys.stderr, "error returned from JS compile service: %d" % response.status 31 sys.exit(1) 32 33 result = json.loads(data) 34 if 'errors' in result: 35 for e in result['errors']: 36 filenum = int(e['file'][6:]) 37 filename = config.js_in_files[filenum] 38 lineno = e['lineno'] 39 charno = e['charno'] 40 err = e['error'] 41 print '%s:%d:%d: %s' % (filename, lineno, charno, err) 42 print 'Failed to generate %s.' % config.js_out_file 43 sys.exit(1) 44 45 open(config.js_out_file, 'wt').write(result['compiledCode'] + '\n') 46 print 'Generated %s' % config.js_out_file 47 48 yuic_args = ['yui-compressor', '--type', 'css', '-o', config.css_out_file] 49 p = subprocess.Popen(yuic_args, stdin=subprocess.PIPE) 50 p.communicate(input=css_code) 51 if p.wait() != 0: 52 print 'Failed to generate %s.' % config.css_out_file 53 sys.exit(1) 54 55 print 'Generated %s' % config.css_out_file 56