Last active
August 29, 2015 14:25
-
-
Save mbarkhau/b073bd7ae51bedc61b1d to your computer and use it in GitHub Desktop.
script to minify javascript using google closure compiler
This file contains 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 | |
import os | |
import sys | |
import json | |
from zlib import compress | |
from httplib import HTTPSConnection | |
from urllib import urlencode | |
COMPILER_JAR_PATH = os.path.expanduser("~/closure-compiler/compiler.jar") | |
JAVA_BIN_PATH = "/usr/bin/java" | |
def minify(code, simple=False, advanced=False, pretty=False): | |
options = [] | |
if simple: | |
options.append(("compilation_level", 'SIMPLE_OPTIMIZATIONS')) | |
if advanced: | |
options.append(("compilation_level", 'ADVANCED_OPTIMIZATIONS')) | |
if pretty: | |
options.append(("formatting", 'PRETTY_PRINT')) | |
if os.path.exists(COMPILER_JAR_PATH): | |
return minify_local(code, options) | |
return minify_http(code, options) | |
def minify_local(code, options): | |
import plumbum as pb | |
java_cmd = pb.local[JAVA_BIN_PATH] | |
cmd = java_cmd["-jar", COMPILER_JAR_PATH] | |
for option_name, option_value in options: | |
cmd = cmd["--" + option_name, option_value] | |
code = ((pb.cmd.cat << code) | cmd)() | |
return code, None | |
def minify_http(code, options): | |
args = [ | |
('js_code', code), | |
('output_format', 'json'), | |
('output_info', 'compiled_code'), | |
('output_info', 'errors'), | |
] | |
for option in options: | |
args.insert(1, option) | |
conn = HTTPSConnection('closure-compiler.appspot.com') | |
conn.request('POST', '/compile', urlencode(args), { | |
"Content-type": "application/x-www-form-urlencoded" | |
}) | |
resp = conn.getresponse() | |
data = json.loads(resp.read()) | |
code = data['compiledCode'].strip() if 'compiledCode' in data else None | |
errs = data.get('errors', None) or data.get('serverErrors', None) | |
conn.close() | |
return code, errs | |
def main(args=sys.argv[1:]): | |
if len(args) > 0: | |
in_fn = sys.argv[1] | |
assert in_fn.endswith(".js") | |
in_f = open(in_fn, 'r') | |
out_fn = in_fn.replace(".js", ".min.js") | |
out_f = open(out_fn, 'w') | |
else: | |
in_f = sys.stdin | |
out_f = sys.stdout | |
original = in_f.read() | |
in_f.close() | |
minified, errors = minify(original) | |
if errors: | |
for e in errors: | |
print(e['lineno'], e['charno'], e['error']) | |
return -1 | |
out_f.write(minified) | |
out_f.close() | |
if len(args) == 1: | |
print("wrote to \"%s\"" % out_fn) | |
print("normal :", len(original)) | |
print("minified :", len(minified)) | |
print("minify+gzip:", len(compress(minified, 9))) | |
if __name__ == '__main__': | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment