Skip to content

Instantly share code, notes, and snippets.

@Hardtack
Last active December 16, 2015 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hardtack/5425332 to your computer and use it in GitHub Desktop.
Save Hardtack/5425332 to your computer and use it in GitHub Desktop.
Compiles javascript to bookmarklet
import sys
import json
import urllib
import argparse
def request_compile(code):
url = 'http://closure-compiler.appspot.com/compile'
# Encode data
params = urllib.urlencode([
('js_code', code),
('compilation_level', 'WHITESPACE_ONLY'),
('output_format', 'json'),
('output_info', 'compiled_code'),
('output_info', 'warnings'),
('output_info', 'errors'),
])
# Send request
data = urllib.urlopen(url, params).read()
data = json.loads(data)
return data
def bookmarkletify(code):
code = code.replace(' ', '%20')
return 'javascript:' + code
def print_error(e):
charno = e['charno']
print >> sys.stderr, 'Error :', e['error']
print >> sys.stderr, 'Error Type :', e['type']
print >> sys.stderr, 'Line No :', e['lineno']
print >> sys.stderr, 'Char No :', charno
print >> sys.stderr, 'File :', e['file']
print >> sys.stderr, 'Line :', e['line']
print >> sys.stderr, ' ', (' ' * charno) + '^'
def print_warning(w):
print >> sys.stderr, 'Warning :', w['warning']
print >> sys.stderr, 'Warn Type :', w['type']
print >> sys.stderr, 'Line No :', w['lineno']
print >> sys.stderr, 'Char No :', w['charno']
print >> sys.stderr, 'File :', w['file']
print >> sys.stderr, 'Line :', w['line']
def main():
parser = argparse.ArgumentParser(prog='COMPILE')
parser.add_argument('source', metavar='SOURCE', type=str, nargs=1,
help='source file name that will be compiled')
parser.add_argument('dest', metavar='DEST', type=str, nargs=1,
help='destination file name that will save compiled source')
args = parser.parse_args()
source = args.source[0]
dest = args.dest[0]
with open(source) as f:
code = f.read()
data = request_compile(code)
warnings = data.get('warnings', [])
errors = data.get('errors', [])
for w in warnings:
WARNING = 'WANRNING'
cnt = 80 - len(WARNING) - 2
print ('=' * (cnt//2)) + ' ' + WARNING + ' ' + ('=' * (cnt//2))
print_warning(w)
for e in errors:
ERROR = 'ERROR'
cnt = 80 - len(ERROR) - 2
print ('=' * (cnt//2)) + ' ' + ERROR +' ' + ('=' * ((cnt//2) + 1))
print_error(e)
print '%d error(s), %d warning(s)' % (len(errors), len(warnings))
if len(errors) == 0:
code = data['compiledCode']
with open(dest, 'w') as f:
f.write(bookmarkletify(code))
print 'Compression Finished!'
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment