Last active
November 2, 2018 09:21
-
-
Save jonlabelle/03c1152250a428aebfd94c0a8d1c7e8b to your computer and use it in GitHub Desktop.
Compiles JavaScript using the Closure Compiler Service API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from __future__ import print_function | |
| try: | |
| # python 3 | |
| import http.client as httplib | |
| except ImportError: | |
| # python 2 | |
| import httplib | |
| import errno | |
| import os.path | |
| import sys | |
| import urllib | |
| # | |
| # API Docs: https://developers.google.com/closure/compiler/ | |
| # Web-based: http://closure-compiler.appspot.com/ | |
| # | |
| PROG_NAME = None | |
| def usage(): | |
| print('') | |
| print('Compiles JavaScript using the Closure Compiler Service API.') | |
| print('') | |
| print('Usage:') | |
| print('') | |
| print(' %s <code,file,url>' % PROG_NAME) | |
| print('') | |
| def compile_code(js_code): | |
| params = urllib.urlencode(( | |
| ('js_code', js_code), | |
| ('compilation_level', 'SIMPLE_OPTIMIZATIONS'), | |
| ('output_format', 'text'), | |
| ('output_info', 'compiled_code'), | |
| )) | |
| headers = {'Content-type': 'application/x-www-form-urlencoded'} | |
| conn = httplib.HTTPConnection('closure-compiler.appspot.com') | |
| conn.request('POST', '/compile', params, headers) | |
| response = conn.getresponse() | |
| response_data = response.read() | |
| conn.close() | |
| return response_data | |
| def compile_url(js_url): | |
| params = urllib.urlencode([ | |
| ('code_url', js_url), | |
| ('compilation_level', 'SIMPLE_OPTIMIZATIONS'), | |
| ('output_format', 'text'), | |
| ('output_info', 'compiled_code'), | |
| ]) | |
| headers = {'Content-type': 'application/x-www-form-urlencoded'} | |
| conn = httplib.HTTPConnection('closure-compiler.appspot.com') | |
| conn.request('POST', '/compile', params, headers) | |
| response = conn.getresponse() | |
| response_data = response.read() | |
| conn.close() | |
| return response_data | |
| if __name__ == '__main__': | |
| PROG_NAME = os.path.basename(str(sys.argv[0])) | |
| if len(sys.argv) < 2: | |
| usage() | |
| sys.exit(errno.EINVAL) | |
| else: | |
| arg = sys.argv[1] | |
| if arg == '-h' or arg == '--help': | |
| usage() | |
| sys.exit(2) | |
| if arg.startswith('http'): | |
| data = compile_url(arg) | |
| print(data) | |
| elif os.path.isfile(arg): | |
| fo = open(arg, 'r') | |
| str_in = fo.read() | |
| fo.close() | |
| data = compile_code(str_in) | |
| print(data) | |
| else: | |
| print("%s error : no such file: '%s'" % PROG_NAME, arg) | |
| sys.exit(errno.ENOENT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment